[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M69BE9GW375EBM6ETNWD84E3":3,"skill-same:01M69BE9GW375EBM6ETNWD84E3":93},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":50,"linkOnly":51,"markdownContent":52,"markdownBody":53,"frontMatter":54,"refName":70,"commitSha":71,"skillDirectory":72,"forksCount":73,"repositoryHtmlUrl":74,"repositoryHomepageUrl":17,"ownerHtmlUrl":75,"ownerBlogUrl":76,"ownerDescription":77,"updatedAt":78,"install":79,"resources":92},"01M69BE9GW375EBM6ETNWD84E3","add-example-agents","Discovery 示例智能体导入","Add agents from the public microsoft\u002Fdiscovery GitHub repository to this workspace, either (a) locally for the Copilot app by emitting a `.agent.md` companion per agent (so each is invocable via `runSubagent`), (b) into a Microsoft Discovery project via `UpsertAgent` sourced fresh from upstream (binding pre-existing tool ARM resources when present, or building + pushing + registering them in Azure first when missing), or (c) promoting an agent already added to the local Copilot app (sourced from its `.github\u002Fagents\u002F\u003Cname>.agent.md` companion; tool-bearing agents also carry a `discovery_catalog\u002F\u003Cname>\u002F` folder plus a locally-built tool container, while toolless agents have only the companion) up to a specific Microsoft Discovery project + Azure without re-fetching or refreshing from upstream. The user picks exactly one of the three targets per run. USE FOR: 'add the discovery agents', 'download discovery agents', 'install all Microsoft discovery agents', 'add agents from microsoft\u002Fdiscovery', 'create copilot agents from microsoft\u002Fdiscovery', 'deploy discovery agents to Foundry', 'deploy discovery agents to Azure', 'promote a local agent to Microsoft Discovery', 'push my local agent and container to a Discovery project', 'copy a local app agent to Azure'. Always refreshes every selected subfolder under `agents\u002F\u003Cname>\u002F` of the upstream repo into `discovery_catalog\u002F\u003Cname>\u002F` so the local catalog stays current (new agents appear, removed agents are surfaced, updated content is applied). The presence check for what is 'already locally added' uses `.github\u002Fagents\u002F\u003Cname>.agent.md` (the Copilot companion), not the `discovery_catalog\u002F` folder. For local deployment, each generated `.agent.md` carries a lazy Docker-bootstrap preamble so the agent builds its tool image on first use only if absent. For Discovery + Azure deployment, pre-flights every declared tool via `GetDiscoveryTool` against the workspace's RG and **skips Docker build \u002F ACR push \u002F AcrPull RBAC entirely when the tool already exists** (common for shared catalog images on registries like `mdqacr`); only builds + registers tools that are actually missing. Always creates the agent in the chosen Discovery project via `UpsertAgent` and polls **`GetAgent` for `provisioningState=Succeeded`** (the MCP `GetAgentOperation` tool returns an opaque error in practice; never rely on it). All MCP calls flow through PowerShell scripts embedded in this SKILL.md and materialized into `.vscode\u002F` during Step 4d — the skill does not depend on sibling helper files or on the VS Code MCP runtime surfacing `mcp_microsoft-dis_*` tools mid-session. Local Discovery runtime registration via `agents action=create` is optional and skipped by default. DO NOT USE FOR: running an already-deployed agent (use runSubagent), or editing a single agent's prompt (edit `agent.yaml` directly).","从公共的 microsoft\u002Fdiscovery GitHub 仓库将智能体添加到此工作区，方式可以是：(a) 本地方式，用于 Copilot 应用，为每个智能体生成一个 `.agent.md` 伴随文件（以便每个智能体都可通过 `runSubagent` 调用）；(b) 通过 `UpsertAgent` 将上游最新来源的智能体添加到 Microsoft Discovery 项目（存在时绑定已有的工具 ARM 资源，缺失时先在 Azure 中构建、推送并注册这些资源）；或 (c) 将已添加到本地 Copilot 应用的智能体（来源于其 `.github\u002Fagents\u002F\u003Cname>.agent.md` 伴随文件；带工具的智能体还带有 `discovery_catalog\u002F\u003Cname>\u002F` 文件夹以及本地构建的工具容器，而无工具的智能体仅有伴随文件）提升到指定的 Microsoft Discovery 项目 + Azure，且不再从上游重新获取或刷新。用户每次运行只能从这三个目标中精确选择一个。适用场景：'添加 discovery 智能体''下载 discovery 智能体''安装所有 Microsoft discovery 智能体''从 microsoft\u002Fdiscovery 添加智能体''从 microsoft\u002Fdiscovery 创建 copilot 智能体''将 discovery 智能体部署到 Foundry''将 discovery 智能体部署到 Azure''将本地智能体提升到 Microsoft Discovery''将本地智能体及其容器推送到 Discovery 项目''将本地应用智能体复制到 Azure'。始终将上游仓库 `agents\u002F\u003Cname>\u002F` 下每个选中的子文件夹刷新到 `discovery_catalog\u002F\u003Cname>\u002F`，使本地目录保持最新（出现新智能体、显现已移除的智能体、应用更新后的内容）。判断智能体是否\"已在本地添加\"使用 `.github\u002Fagents\u002F\u003Cname>.agent.md`（Copilot 伴随文件），而非 `discovery_catalog\u002F` 文件夹。对于本地部署，每个生成的 `.agent.md` 都带有延迟的 Docker 引导前言，使智能体仅在首次使用且工具镜像不存在时才构建该镜像。对于 Discovery + Azure 部署，会针对工作区的资源组（RG）通过 `GetDiscoveryTool` 对每个声明的工具进行预检，并**在工具已存在时完全跳过 Docker 构建 \u002F ACR 推送 \u002F AcrPull RBAC**（这在 `mdqacr` 等注册表上的共享目录镜像中很常见）；仅构建并注册实际缺失的工具。始终通过 `UpsertAgent` 在选定的 Discovery 项目中创建智能体，并轮询 `GetAgent` 直到 `provisioningState=Succeeded`（MCP 的 `GetAgentOperation` 工具在实践中会返回不透明错误；切勿依赖它）。所有 MCP 调用都通过嵌入在本 SKILL.md 中、并在步骤 4d 期间具体化为 `.vscode\u002F` 的 PowerShell 脚本进行——该技能不依赖同级的辅助文件，也不依赖 VS Code MCP 运行时在会话中途浮现 `mcp_microsoft-dis_*` 工具。通过 `agents action=create` 进行的本地 Discovery 运行时注册是可选的，默认跳过。不要用于：运行已部署的智能体（使用 runSubagent），或编辑单个智能体的提示词（直接编辑 `agent.yaml`）。","microsoft\u002Fdiscovery","microsoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6154722?v=4","01M698VYDXZ6JW5WH3CRV650R8","Microsoft","01M69BDVENS7NFPQQV19R5KA3B",289,"MIT",null,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery\u002Fblob\u002Fmain\u002Fskills\u002Fadd-example-agents\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BRZZF9D7PVFN5MXSPWWD61","AI 工程师","PROFESSION","适用职业",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BSAA4FBTWZP6X98STEHG99","智能体开发","SCENARIO","使用场景",[31,32,33,34,35,36,37,38,39,40,41,42,43,10,44,45,46,47,48,49],"add example agents","copilot","code","run","create","deployment","bootstrap","podman","azure","distributed","MCP","windows","vscode","editor","valid","docker","github","python","image","2026-11-10 10:12:30",false,"---\nname: add-example-agents\ndescription: \"Add agents from the public microsoft\u002Fdiscovery GitHub repository to this workspace, either (a) locally for the Copilot app by emitting a `.agent.md` companion per agent (so each is invocable via `runSubagent`), (b) into a Microsoft Discovery project via `UpsertAgent` sourced fresh from upstream (binding pre-existing tool ARM resources when present, or building + pushing + registering them in Azure first when missing), or (c) promoting an agent already added to the local Copilot app (sourced from its `.github\u002Fagents\u002F\u003Cname>.agent.md` companion; tool-bearing agents also carry a `discovery_catalog\u002F\u003Cname>\u002F` folder plus a locally-built tool container, while toolless agents have only the companion) up to a specific Microsoft Discovery project + Azure without re-fetching or refreshing from upstream. The user picks exactly one of the three targets per run. USE FOR: 'add the discovery agents', 'download discovery agents', 'install all Microsoft discovery agents', 'add agents from microsoft\u002Fdiscovery', 'create copilot agents from microsoft\u002Fdiscovery', 'deploy discovery agents to Foundry', 'deploy discovery agents to Azure', 'promote a local agent to Microsoft Discovery', 'push my local agent and container to a Discovery project', 'copy a local app agent to Azure'. Always refreshes every selected subfolder under `agents\u002F\u003Cname>\u002F` of the upstream repo into `discovery_catalog\u002F\u003Cname>\u002F` so the local catalog stays current (new agents appear, removed agents are surfaced, updated content is applied). The presence check for what is 'already locally added' uses `.github\u002Fagents\u002F\u003Cname>.agent.md` (the Copilot companion), not the `discovery_catalog\u002F` folder. For local deployment, each generated `.agent.md` carries a lazy Docker-bootstrap preamble so the agent builds its tool image on first use only if absent. For Discovery + Azure deployment, pre-flights every declared tool via `GetDiscoveryTool` against the workspace's RG and **skips Docker build \u002F ACR push \u002F AcrPull RBAC entirely when the tool already exists** (common for shared catalog images on registries like `mdqacr`); only builds + registers tools that are actually missing. Always creates the agent in the chosen Discovery project via `UpsertAgent` and polls **`GetAgent` for `provisioningState=Succeeded`** (the MCP `GetAgentOperation` tool returns an opaque error in practice; never rely on it). All MCP calls flow through PowerShell scripts embedded in this SKILL.md and materialized into `.vscode\u002F` during Step 4d — the skill does not depend on sibling helper files or on the VS Code MCP runtime surfacing `mcp_microsoft-dis_*` tools mid-session. Local Discovery runtime registration via `agents action=create` is optional and skipped by default. DO NOT USE FOR: running an already-deployed agent (use runSubagent), or editing a single agent's prompt (edit `agent.yaml` directly).\"\nlicense: MIT\nmetadata:\n  author: Internal\n  version: \"1.16.0\"\n  changelog:\n    - \"1.16.0: LocalToDiscovery promote now sources the agent `name` and `description` from the .github\u002Fagents\u002F\u003Cname>.agent.md companion frontmatter (same source of truth as `instructions`), NOT from discovery_catalog\u002F\u003Cname>\u002Fagent.yaml, for BOTH tool-bearing and toolless agents. Added Get-AgentMdFrontmatterValue helper (Step 4c.LTD), updated the 4c.LTD classification, Step 7e.1 field sourcing + code, Step 7e.4 description bullet, and the Step 7g guard-rail. Description is still truncated to the 512-char Foundry cap; falls back to agent.yaml#description only when the companion has none.\"\n    - \"1.15.0: Fixed a CRLF line-ending bug that produced a truncated (~369-char) instructions body on Windows companions. Get-AgentMdInstructions and Convert-PromoteInstructionsForTool now use '\\\\r?\\\\n---\\\\r?\\\\n' (not '\\\\n---\\\\n') for the bootstrap horizontal-rule delimiter — a bare '\\\\n---\\\\n' never matches a CRLF companion, so the '|\\\\z' fallback in Convert previously swallowed the whole prompt. Added a Step 7e.1 length sanity-check (throw if \u003C500 chars). Hardened Step 7e.4 description sourcing with the 512-char Foundry cap (bare Failed \u002F foundryDetails=null is a description-length problem, not tool-binding). Added Step 7c guidance: a previously-deployed tool ARM can be deleted (404) while its image survives in ACR — check 'az acr repository show-tags' and re-register the tool ARM without rebuilding when the image is present.\"\n    - \"1.14.0: LocalToDiscovery promote now rewrites tool-bearing agents' cloud instructions to reference the deployed Discovery tool instead of a local Podman\u002FDocker image. Added Convert-PromoteInstructionsForTool (Step 4c.LTD) which strips the container bootstrap preamble, scrubs residual podman\u002Fdocker build\u002Fpull\u002Fpush\u002Fimage-inspect lines and discovery_catalog\u002F...\u002Ftools\u002F... build-context references, and appends a 'Tool execution (Microsoft Discovery)' note naming the deployed tool(s). Step 7e.1 applies it for $agentHasCatalogFolder agents and requires each declared tool to be provisioningState=Succeeded with its image in the workspace ACR before UpsertAgent. Added a Step 7g guard-rail.\"\n    - \"1.13.0: LocalToDiscovery (promote) now sources the agent picker from .github\u002Fagents\u002F*.agent.md (the local-app companions) instead of requiring a discovery_catalog\u002F\u003Cname>\u002F folder. Agents are classified into tool-bearing (has discovery_catalog folder + agent.yaml + tools) vs toolless (companion only, created locally with no container tool). Toolless agents skip Step 7c\u002F7d entirely and get instructions from the .agent.md body (frontmatter for name\u002Fdescription, body minus the container-bootstrap preamble for instructions) with an empty toolIds. Added Get-AgentMdInstructions helper, $agentHasCatalogFolder classification, and relaxed the 7g 'source of truth' guard-rail so a missing discovery_catalog folder is valid for toolless promotes.\"\n    - \"1.12.0: Hardened the Discovery deploy path from a real promotion run. Tool ARM registration now requires properties.definitionContent to be a JSON object built with [ordered]@{} (raw tool.yaml string fails InvalidType) and passes the body via a temp file with --body @file. code_environments[].language must be normalized to python3 (python passes the tool PUT but breaks Foundry agent-binding with a bare Failed). Added az acr build Windows console UnicodeEncodeError guidance (set PYTHONIOENCODING=utf-8; poll az acr task list-runs instead of rebuilding). Added Step 7e recovery flow for fast tool-binding failures: isolate prompt vs tool by upserting without toolIds, fix language, wait ~30-60s for Foundry propagation before rebinding, and use GetAgentOperation (operationId) to extract the real error when GetAgent reports a bare Failed.\"\n    - \"1.11.0: Added a third deployment target (LocalToDiscovery) that promotes an agent already added to the local Copilot app — its local discovery_catalog\u002F\u003Cname>\u002F folder and locally-built tool container — up to a specific Microsoft Discovery project + Azure without re-fetching or refreshing from upstream. Source of truth is the local folder; tool images are pushed from the local build context or the locally-built image. Added $deployToCloud \u002F $sourceMode helper flags, Step 4c.LTD (local catalog index), Step 5 skip for the local source, and Step 7d.LTD (push local image).\"\n    - \"1.10.1: Hardened local generation: require temp .ps1 execution for multi-line scripts, fix .agent.md stem detection, parse YAML block-scalar descriptions correctly, and write generated .agent.md files with read\u002Fwrite sharing to avoid transient editor locks.\"\n    - \"1.10.0: Changed upstream source from private microsoft\u002Fdiscovery-catalog agents\u002Fmicrosoft\u002F to public microsoft\u002Fdiscovery agents\u002F, removing GitHub authentication requirements.\"\n    - \"1.9.0: Added Local runtime selection flow (Podman\u002FDocker detection, defaulting, optional Podman auto-install) and changed generated .agent.md bootstrap instructions to try Podman first then Docker as fallback.\"\n    - \"1.8.0: Embedded discovery-mcp-proxy.ps1 and Invoke-DiscoveryMcp.ps1 directly in SKILL.md and changed Step 4d\u002F7a to extract them into .vscode, so the skill can be distributed as one file.\"\n    - \"1.7.0: Co-located proxy + Invoke-DiscoveryMcp helper as sibling files. Made scripted stdio invocation the canonical MCP path (no longer depends on VS Code surfacing mcp_microsoft-dis_* tools mid-session). Replaced GetAgentOperation polling with GetAgent provisioningState polling. Bumped ARM api-version to 2026-06-01. Added explicit 'agents are NOT an ARM resource type' callout.\"\n---\n\n# add-example-agents\n\nAdd agents from the public `microsoft\u002Fdiscovery` repository to this\nworkspace, then deploy each selected agent to exactly one of two targets:\n\n- **Local Copilot** - emit a `.github\u002Fagents\u002F\u003Cname>.agent.md` companion for\n  every agent so it can be invoked as a Copilot subagent via `runSubagent`.\n  Tool container images are built lazily on first invocation, locally only.\n- **Microsoft Discovery + Azure** - pre-flight every tool the agent\n  declares via `GetDiscoveryTool` against the workspace's RG. When a tool\n  ARM resource already exists (common for shared catalog images on\n  registries like `mdqacr`), skip Docker build \u002F ACR push \u002F AcrPull RBAC\n  entirely and bind the existing ARM ID. When a tool is missing, build +\n  push via `az acr build`, register the tool ARM, grant AcrPull. Either\n  way, create the agent in the target Discovery project via `UpsertAgent`\n  and poll **`GetAgent`** until `provisioningState=Succeeded`. Local\n  Discovery runtime registration (`agents action=create`) is optional and\n  skipped by default.\n- **Local app → Microsoft Discovery + Azure (promote)** - take an agent\n  that is **already added to the local Copilot app** (present under\n  `discovery_catalog\u002F\u003Cname>\u002F` with a `.github\u002Fagents\u002F\u003Cname>.agent.md`\n  companion and, for tool-bearing agents, a locally-built container image)\n  and register it in a specific Discovery project. The **local** folder is\n  the source of truth - the upstream `microsoft\u002Fdiscovery` repo is **not**\n  fetched or refreshed, so any local edits are preserved. Tool container(s)\n  are pushed to ACR from the local build context \u002F locally-built image, then\n  the agent is created via `UpsertAgent` and polled with `GetAgent` exactly\n  as in the upstream-sourced Discovery path.\n\nThe user picks the deployment target **first** (Step 4c), then — only for a Discovery-class target (Discovery or LocalToDiscovery) — confirms the destination workspace + project (Step 4d), and **then** chooses which agents to add (Step 4e).\n\n## Source of truth\n\n- Upstream repo: `https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery`\n- Path of interest: `agents\u002F`\n- Each subfolder under `agents\u002F\u003CNAME>\u002F` is one Discovery agent.\n\nThe upstream layout for every agent is identical and matches what already lives\nin this workspace's `discovery_catalog\u002F`:\n\n```\nagents\u002F\u003Cname>\u002F\n├── agent.yaml          # prompt \u002F hosted agent definition (kind: prompt)\n├── metadata.yaml       # name, version, associated_tools, publisher, tags\n├── README.md           # deployment & usage guide\n└── tools\u002F\n    └── \u003CToolName>\u002F\n        ├── Dockerfile          # container image recipe\n        ├── tool.yaml           # tool definition (infra, code_environments)\n        ├── *-EnvVars.json      # optional env-var spec\n        ├── basic-description.txt\n        └── \u003Cutils>.py          # optional helper code\n```\n\nThe local target is **identical**, only the parent folder differs:\n\n```\ndiscovery_catalog\u002F\u003Cname>\u002F...    # 1:1 mirror of agents\u002F\u003Cname>\u002F...\n```\n\nSo adding an agent is a straight folder copy — no transformation required.\n\n## Prerequisites\n\nRequired for **every** run (Step 3 — fetch catalog):\n\n| Requirement | Check command | Required for |\n|---|---|---|\n| `git` on PATH | `git --version` | cloning the catalog |\n| Network access to github.com | `Test-NetConnection github.com -Port 443` | cloning |\n\nRequired **only** when `$deployToCloud` is true (`$deployTarget` is `Discovery` or `LocalToDiscovery`) (Step 7 —\nMicrosoft Discovery + Azure deployment):\n\n| Requirement | Check command | Required for |\n|---|---|---|\n| `az` CLI on PATH | `az --version` | Azure subscription \u002F ACR \u002F RBAC operations (fallback when Azure MCP is absent) |\n| Active `az login` session | `az account show` | calling any Azure resource |\n| `docker` CLI on PATH | `docker --version` | building tool images locally before push (fallback when Azure MCP \u002F `az acr build` is unavailable) |\n| Azure Container Registry write access | `az acr login -n \u003Cacr>` | pushing tool images |\n| Discovery MCP reachable via the proxy | `pwsh -NoProfile -File .vscode\u002Fdiscovery-mcp-proxy.ps1` accepts a JSON-RPC `initialize` and replies | tool pre-flight (`GetDiscoveryTool`), agent provisioning (`UpsertAgent` + `GetAgent` poll), model lookup (`ListChatModelDeployments`). Installed by Step 4d by extracting the embedded `discovery-mcp-proxy.ps1` and `Invoke-DiscoveryMcp.ps1` blocks from this `SKILL.md` into `.vscode\u002F`. **All MCP calls go through the extracted proxy via the extracted `Invoke-DiscoveryMcp` helper, not through VS Code's `mcp_microsoft-dis_*` deferred tools.** The mcp.json registration is written too, but only as a courtesy for the user's future interactive sessions — never wait for those deferred tools to surface mid-run. |\n| `microsoft-foundry` skill (optional) | (listed in workspace skills) | reference only — **not** invoked via `runSubagent`. Catalog agents are not azd projects, so the foundry skill's `.foundry\u002F` overlay flow does not apply. Use the direct Discovery MCP path documented in Steps 7c–7e. |\n\nThe upstream repository is public. Do not require `gh`, `GH_TOKEN`,\n`GITHUB_TOKEN`, GitHub device-flow login, or any other GitHub authentication\nfor the catalog fetch. Anonymous `git clone` and GitHub contents API requests\nare expected to work.\n\nWhen `$deployTarget == 'Local'`, neither Docker Desktop nor Podman is a hard\nprerequisite for running this skill itself. The skill never invokes local\nimage builds directly; image bootstrap is delegated to each generated agent at\ninvocation time (see Step 6). Runtime readiness is handled by Step 4f.\n\n## Scripted MCP invocation (canonical fast path)\n\n> **This is the only MCP path the skill should use mid-run.** Do NOT wait\n> for VS Code's MCP runtime to surface `mcp_microsoft-dis_*` deferred\n> tools — in practice they often do not appear in the same session that\n> registered them. Invoke the proxy directly via stdio instead. It works\n> first-try every time once `az login` is set up.\n\nTwo PowerShell files are embedded at the bottom of this skill and materialized\ninto `.vscode\u002F` during Step 4d:\n\n| Embedded block | Role |\n|---|---|\n| `embedded-discovery-mcp-proxy.ps1` | Local PowerShell stdio ↔ HTTPS proxy. Mints `https:\u002F\u002Fdiscovery.azure.com` tokens via `az`, forwards JSON-RPC frames to `https:\u002F\u002Fmcp.discovery.azure.com\u002Fmcp`, refreshes on 401, preserves `Mcp-Session-Id`. |\n| `embedded-Invoke-DiscoveryMcp.ps1` | PowerShell helpers: `Invoke-DiscoveryMcp` (spawn proxy, send initialize + N `tools\u002Fcall`, return responses keyed by JSON-RPC id), `Get-DiscoveryMcpText` (extract \u002F parse the text payload), `Wait-DiscoveryAgentReady` (poll `GetAgent` for `provisioningState=Succeeded`). |\n\n**Install ritual (run once per workspace, in Step 4d):**\n\n```pwsh\n$skillDir = \"\u003Cabsolute path to this skill folder>\"   # contains SKILL.md\nNew-Item -ItemType Directory -Force -Path \"$workspaceRoot\\.vscode\" | Out-Null\n$skillPath = Join-Path $skillDir 'SKILL.md'\n$skillText = Get-Content $skillPath -Raw\nfunction Write-EmbeddedSkillScript([string]$BlockId, [string]$Destination) {\n  $begin = \"\u003C!-- BEGIN:$BlockId -->\"\n  $end = \"\u003C!-- END:$BlockId -->\"\n  $start = $skillText.IndexOf($begin)\n  if ($start -lt 0) { throw \"Embedded script block '$BlockId' not found in $skillPath\" }\n  $contentStart = $start + $begin.Length\n  $stop = $skillText.IndexOf($end, $contentStart)\n  if ($stop -lt 0) { throw \"Embedded script block '$BlockId' has no end marker in $skillPath\" }\n  $block = $skillText.Substring($contentStart, $stop - $contentStart).Trim()\n  $lines = @($block -split \"`r?`n\")\n  if ($lines.Count -lt 3 -or $lines[0] -notmatch '^```powershell\\s*$' -or $lines[-1] -notmatch '^```\\s*$') {\n      throw \"Embedded script block '$BlockId' must be wrapped in a powershell fenced code block.\"\n  }\n  $content = (($lines[1..($lines.Count - 2)]) -join \"`r`n\") + \"`r`n\"\n  Set-Content -Path $Destination -Value $content -Encoding UTF8\n}\nWrite-EmbeddedSkillScript 'embedded-discovery-mcp-proxy.ps1' \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\"\nWrite-EmbeddedSkillScript 'embedded-Invoke-DiscoveryMcp.ps1' \"$workspaceRoot\\.vscode\\Invoke-DiscoveryMcp.ps1\"\n\n# (Optional, for the user's future interactive sessions only) write .vscode\u002Fmcp.json\n# — see Step 7a.2 for the merge-safe writer. Do NOT block on the MCP runtime\n# actually loading those tools mid-run.\n```\n\n**Canonical call pattern (use this for ListWorkspaces \u002F ListProjects \u002F\nListAgents \u002F GetDiscoveryTool \u002F ListChatModelDeployments \u002F UpsertAgent \u002F\nGetAgent — every MCP call this skill makes):**\n\n```pwsh\n. \"$workspaceRoot\\.vscode\\Invoke-DiscoveryMcp.ps1\"\n$proxy = \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\"\n\n$results = Invoke-DiscoveryMcp -ProxyPath $proxy -Calls @(\n    @{ name='ListAgents'; args=@{\n        subscriptionId    = $sub\n        resourceGroupName = $rg\n        workspaceName     = $ws\n        projectName       = $proj\n    } }\n)\n$obj = Get-DiscoveryMcpText -Response $results['2'] -AsJson\n# $obj is the parsed payload (varies by tool — array, {value:[]}, single object, …)\n```\n\n**Polling pattern for `UpsertAgent` completion** — for the happy path,\nprefer `GetAgent` provisioningState polling over `GetAgentOperation`\n(historically `GetAgentOperation` has sometimes returned an opaque\n`\"An error occurred invoking 'GetAgentOperation'.\"`). Use the provided\nhelper. When `GetAgent` reports a bare `Failed` with no error text,\n`GetAgentOperation` (called with the `UpsertAgent` operationId) *can*\nreturn the real `{status, error, result}` — see Step 7e.5:\n\n```pwsh\nWait-DiscoveryAgentReady -ProxyPath $proxy `\n    -SubscriptionId $sub -ResourceGroupName $rg `\n    -WorkspaceName $ws -ProjectName $proj `\n    -AgentName 'retrochimera' -TimeoutSeconds 300\n```\n\n**Why scripts, not inline heredocs.** The VS Code agent terminal echoes\nmulti-line PowerShell commands back to stdin and frequently truncates\nheredocs. **Always** write multi-line PowerShell to a temp `.ps1` file\n(`\"$env:TEMP\\dc-\u003Ctask>.ps1\"`) and invoke with\n`pwsh -NoProfile -File \"\u003Cpath>\"`. One-liners are fine. This applies to\nthe Step 6 local companion-generation script as well as MCP scripts. Do\nnot paste a long function-heavy PowerShell block directly into the shared\nterminal; if a prompt is left inside a partial function or here-doc, close\nthat syntax first and rerun from a `.ps1` file.\n\n**Operational guarantees:**\n\n- Agents are **not** an ARM resource type. There is no\n  `Microsoft.Discovery\u002Fworkspaces\u002Fprojects\u002Fagents` resource provider.\n  Never call `az rest ...\u002Fprojects\u002F\u003Cp>\u002Fagents?...` — it always returns\n  `ResourceTypeRegistrationNotFound`. Agents only exist behind the MCP\n  server's `ListAgents` \u002F `GetAgent` \u002F `UpsertAgent` \u002F `DeleteAgent`.\n- Workspaces and projects **are** ARM resources but use the\n  `Microsoft.Discovery` provider — current api-version `2026-06-01`\n  (older `2024-10-01-preview` is rejected with\n  `InvalidResourceType`). Prefer the MCP `ListWorkspaces` \u002F\n  `ListProjects` calls anyway — they return the same data without\n  api-version drift.\n- `Microsoft-dis_*` deferred tool names are **not** required. If a\n  later VS Code release surfaces them automatically, the skill may use\n  them in addition to the proxy — but never instead of it (the proxy\n  is the always-available baseline).\n\n## Workflow\n\n### Step 1 — Discover workspace layout\n\n1. Locate the workspace root by searching for a top-level `discovery_catalog\u002F`\n   folder (the user's prompt may not say where it is).\n2. Enumerate **`.github\u002Fagents\u002F*.agent.md`** — these are the Copilot companion\n   files and are the **authoritative source of truth for which agents are\n   already locally added**. Strip the `.agent.md` suffix to get the agent\n   folder name. Use this set (call it `$existingLocalAgents`) for both the\n   Step 4e Local collision hint and the Step 8 \"already had companion\"\n   summary bucket. **Do not** infer \"already added\" from the presence of a\n   `discovery_catalog\u002F\u003Cname>\u002F` folder — that folder is always refreshed from\n   upstream in Step 5 and would mislabel every entry as \"already present\".\n     In PowerShell, do **not** use `$_.BaseName` for this; for\n     `pubchem.agent.md`, `.BaseName` is `pubchem.agent`, not `pubchem`.\n     Use an explicit suffix removal:\n     ```pwsh\n     $existingLocalAgents = @{}\n     Get-ChildItem $agentsDir -Filter '*.agent.md' -File -ErrorAction SilentlyContinue | ForEach-Object {\n       $stem = $_.Name -replace '\\.agent\\.md$', ''\n       $existingLocalAgents[$stem] = $true\n     }\n     ```\n3. Also list the `discovery_catalog\u002F\u003Cname>\u002F` folders so Step 5 can report\n   which folders were **created fresh** vs **refreshed in place** vs\n   **removed from upstream** (no longer present in `agents\u002F`).\n\n### Step 2 — Confirm public GitHub access\n\n> **Skip Steps 2 and 3 when `$deployTarget == 'LocalToDiscovery'`**\n> (`$sourceMode == 'Local'`). Promotion never touches the upstream repo — the\n> agent already lives in `discovery_catalog\u002F`. When the user's request clearly\n> asks to promote a local agent, ask the Step 4c deployment-target question\n> **before** these steps so the fetch is avoided; otherwise a fetch that\n> already ran is simply ignored (the clone is discarded in Step 8). Build the\n> catalog index from the local workspace instead (Step 4c.LTD).\n\nThe `microsoft\u002Fdiscovery` repo is public. Do **not** run `gh auth status`,\n`gh auth login`, token setup, or authenticated REST probes for the catalog.\nOnly verify ordinary network access to GitHub before cloning:\n\n```pwsh\ngit --version\nTest-NetConnection github.com -Port 443\n```\n\nIf the public fetch returns 404 or another HTTP error, report the exact\ncommand + status \u002F git error. Treat it as a network, URL, rate-limit, or\ntemporary GitHub availability problem unless the user provides different\nevidence. **Never fabricate agent content.**\n\n### Step 3 — Fetch the upstream catalog\n\nPrefer a shallow sparse checkout to avoid pulling unrelated parts of the repo:\n\n```pwsh\n$work = Join-Path $env:TEMP (\"discovery-agents-\" + [Guid]::NewGuid().ToString('N').Substring(0,8))\ngit clone --depth 1 --filter=blob:none --sparse https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery.git $work\nPush-Location $work\ngit sparse-checkout set agents\nPop-Location\n```\n\nFallbacks (in order) if the sparse clone fails:\n\n1. `git clone --depth 1 https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery.git $work`\n2. REST API: enumerate\n   `https:\u002F\u002Fapi.github.com\u002Frepos\u002Fmicrosoft\u002Fdiscovery\u002Fcontents\u002Fagents`\n   recursively, downloading each file with\n  `Invoke-WebRequest -Headers @{ 'User-Agent' = 'add-agent-from-catalog' }`.\n\nIf all fetch strategies fail, stop and report the exact command + HTTP status \u002F\ngit error. **Never fabricate agent content.**\n\n### Step 4 — Pick deployment target, confirm workspace\u002Fproject, then choose agents\n\nAsk the user **the required prompts in this order**, via `vscode_askQuestions`.\nNever copy the entire catalog silently — many agents are heavyweight (container\ntools, large research stacks) and the user should opt in.\n\n1. **Deployment target** (Step 4c) — Local Copilot only \u002F Microsoft Discovery + Azure (from upstream) \u002F Local app -> Microsoft Discovery + Azure (promote).\n2. **Discovery workspace + project** (Step 4d, conditional on a Discovery-class target — `Discovery` or `LocalToDiscovery`) —\n   ensure the user is signed in to Azure, install the Discovery MCP if missing,\n   list available workspaces and projects, list existing agents in the chosen\n   project, and confirm the destination. This MUST happen **before** the agent\n   picker so the user can see name collisions in the target project.\n3. **Agent selection** (Step 4e) — selection mode (All \u002F Specific \u002F By group)\n   plus values.\n\nSteps 4a and 4b (build catalog index + derive groups) still run before the\nagent picker in Step 4e, but they don't require user input and can happen at\nany point after Step 3 (catalog fetch).\n\n#### 4a. Build the catalog index\n\nFor each `agents\u002F\u003Cname>\u002F` folder under the freshly-cloned `$srcRoot`,\nread `metadata.yaml` and extract:\n\n- `name` (fallback: folder name)\n- `tags` (list — may be empty)\n- `description` from `agent.yaml` (first sentence, trimmed to ~80 chars for display)\n- `associated_tools` count (from `metadata.yaml`, used to flag heavyweight agents)\n\n```pwsh\n$srcRoot = Join-Path $work 'agents'\n$catalog = @()\nGet-ChildItem $srcRoot -Directory | ForEach-Object {\n    $folder = $_.Name\n    $meta   = Join-Path $_.FullName 'metadata.yaml'\n    $ay     = Join-Path $_.FullName 'agent.yaml'\n    $tags   = @()\n    $tools  = 0\n    $desc   = ''\n    if (Test-Path $meta) {\n        $mtxt = Get-Content $meta -Raw\n        # Extract tags: lines like \"  - tagname\" under a \"tags:\" key\n        if ($mtxt -match '(?ms)^tags:\\s*\\r?\\n((?:\\s*-\\s*\\S+\\r?\\n?)+)') {\n            $tags = ($matches[1] -split \"`n\") |\n                ForEach-Object { ($_ -replace '^\\s*-\\s*', '').Trim() } |\n                Where-Object { $_ }\n        }\n        if ($mtxt -match '(?ms)^associated_tools:\\s*\\r?\\n((?:\\s*-\\s*\\S+\\r?\\n?)+)') {\n            $tools = (($matches[1] -split \"`n\") | Where-Object { $_ -match '\\S' }).Count\n        }\n    }\n    if (Test-Path $ay) {\n        $atxt = Get-Content $ay -Raw\n        if ($atxt -match '(?ms)^description:\\s*[>|]?\\s*\\r?\\n((?:\\s{2,}.+\\r?\\n?)+)') {\n            $desc = (($matches[1] -split \"`n\")[0] -replace '^\\s+', '').Trim()\n        } elseif ($atxt -match '^description:\\s*(.+)$') {\n            $desc = $matches[1].Trim().Trim('\"').Trim(\"'\")\n        }\n    }\n    $catalog += [pscustomobject]@{\n        Folder = $folder\n        Tags   = $tags\n        Tools  = $tools\n        Desc   = $desc\n    }\n}\n```\n\n#### 4b. Derive groups\n\nGroup agents by their tags. An agent with multiple tags appears in each\nmatching group. Always include two synthetic groups at the top:\n\n- **All agents** — every folder under upstream `agents\u002F`.\n- **Lightweight (no container tools)** — agents whose `tools\u002F` folder is empty or\n  contains no `Dockerfile`. These install fastest and don't require local\n  container runtimes.\n\n```pwsh\n$groups = [ordered]@{}\n$groups['All agents']                = $catalog.Folder\n$groups['Lightweight (no container tools)'] = ($catalog | Where-Object { $_.Tools -eq 0 }).Folder\nforeach ($a in $catalog) {\n    foreach ($t in $a.Tags) {\n        if (-not $groups.Contains($t)) { $groups[$t] = @() }\n        $groups[$t] += $a.Folder\n    }\n}\n# Deduplicate\nforeach ($k in @($groups.Keys)) { $groups[$k] = $groups[$k] | Select-Object -Unique }\n```\n\n#### 4c. Ask deployment target (FIRST user-facing prompt)\n\nSingle `vscode_askQuestions` call with one question. This MUST be asked\nbefore workspace\u002Fproject (4d) or agent selection (4e) - the answer\ndetermines whether 4d runs at all and changes what 4e shows.\n\n```\nheader: \"deployment-target\"\nquestion: \"Where do you want these agents deployed?\"\noptions:\n  - \"Microsoft Discovery local app only\" (recommended default - requires a GitHub Copilot license, no Azure subscription needed)\n  - \"Microsoft Discovery service (from upstream)\" (Azure subscription required, fetches each agent fresh from microsoft\u002Fdiscovery and registers it in a specific Discovery workspace project that you select)\n  - \"Promote a local app agent to Microsoft Discovery service\" (Azure subscription required, takes an agent already added to the local app plus its locally-built tool container and registers it in a specific Discovery workspace project that you select, without re-fetching upstream)\n```\n\nPersist as `$deployTarget` (`Local` | `Discovery` | `LocalToDiscovery`):\n\n- `Local`            - refresh `discovery_catalog\u002F` from upstream and emit\n                     `.github\u002Fagents\u002F*.agent.md` (Steps 5 + 6). Local tool\n                     images are built lazily on first invocation only, via\n                     Podman-first then Docker fallback.\n- `Discovery`        - refresh `discovery_catalog\u002F` from upstream, build + push\n                     any missing tool images to ACR, register each agent in the\n                     Microsoft Discovery project via `UpsertAgent` (Steps 5 + 7).\n- `LocalToDiscovery` - **do not fetch or refresh from upstream**; use the\n                     agent's existing local `discovery_catalog\u002F\u003Cname>\u002F` folder\n                     as the source of truth. Build + push any missing tool\n                     images to ACR from the local build context \u002F locally-built\n                     image, then register the agent in the Microsoft Discovery\n                     project via `UpsertAgent` (Step 7; local-source deltas in\n                     Steps 4c.LTD and 7d.LTD).\n\nDerive two helper flags used throughout the rest of the workflow:\n\n- `$deployToCloud = $deployTarget -in @('Discovery','LocalToDiscovery')` -\n  true for both Discovery-class targets. **Wherever a later step gates on\n  `$deployTarget == 'Discovery'` for Azure\u002FDiscovery work (Steps 4d, 7 and\n  all its sub-steps, and the Discovery branches of Step 8), read it as\n  `$deployToCloud`** so the promote target runs the same cloud machinery.\n- `$sourceMode = if ($deployTarget -eq 'LocalToDiscovery') { 'Local' } else { 'Upstream' }` -\n  `Upstream` fetches + refreshes from `microsoft\u002Fdiscovery` (Steps 2, 3, 5);\n  `Local` skips all upstream fetch\u002Frefresh and treats\n  `discovery_catalog\u002F\u003Cname>\u002F` as authoritative.\n\nStep 5 runs for `Upstream` source mode only. For `LocalToDiscovery`\n(`$sourceMode == 'Local'`) it is **skipped** - overwriting the local folder\nwith upstream would discard the local edits the user is promoting.\n\nDownstream branch:\n\n- `Local`     \\u2192 skip 4d. Run 4e (agent picker), then 4f (local runtime\n          readiness), then Step 6.\n- `Discovery` \\u2192 run 4d **immediately** (workspace + project picker, before\n              the agent picker). Then run 4e, then Step 7.\n- `LocalToDiscovery` -> skip the upstream fetch (Steps 2 + 3); build the catalog\n              index from the local `.github\u002Fagents\u002F` companions (Step 4c.LTD),\n              classifying each into tool-bearing (has `discovery_catalog\u002F\u003Cname>\u002F`)\n              vs toolless; run 4d **immediately** (workspace + project picker);\n              then run 4e (agent picker scoped to the local-app companions in\n              `$localAgents`); **skip Step 5**; then run Step 7.\n\n#### 4c.LTD. Build the catalog index from the local app (LocalToDiscovery only)\n\nRun this **instead of** the upstream fetch (Steps 2 + 3) and the upstream\ncatalog index (Step 4a) when `$deployTarget == 'LocalToDiscovery'`. The\nsource of truth is the workspace, not `microsoft\u002Fdiscovery`.\n\n**The authoritative list of what can be promoted is\n`.github\u002Fagents\u002F*.agent.md` (the `$existingLocalAgents` set from Step 1),\nNOT the `discovery_catalog\u002F` folders.** A locally-created agent may have\n**no** `discovery_catalog\u002F\u003Cname>\u002F` folder at all — that folder only exists\nfor agents that carry a container-based tool. A toolless prompt agent lives\nentirely in its `.github\u002Fagents\u002F\u003Cname>.agent.md` companion. Both kinds are\npromotable; only the source of `agent.yaml`-equivalent fields differs.\n\nClassify each companion in `$existingLocalAgents` into one of two buckets:\n\n- **Tool-bearing** — a `discovery_catalog\u002F\u003Cname>\u002F` folder exists with an\n  `agent.yaml`. Read `metadata.yaml#associated_tools` and the\n  `tools\u002F\u003CTool>\u002F` subtree from there. Source **both** `instructions` **and**\n  `name` \u002F `description` from the `.github\u002Fagents\u002F\u003Cname>.agent.md` companion\n  (via `Get-AgentMdInstructions` and `Get-AgentMdFrontmatterValue`),\n  **not** from `agent.yaml` — the companion is the source of truth for the\n  prompt body *and* the display name\u002Fdescription the user tuned locally\n  (see Step 7e.1). These go through the full Step 7 tool\n  pre-flight \u002F build \u002F bind path.\n- **Toolless** — no `discovery_catalog\u002F\u003Cname>\u002F` folder (or the folder has\n  no `agent.yaml`). Source the agent fields from the `.agent.md` companion\n  instead: `name` and `description` from its YAML frontmatter (via\n  `Get-AgentMdFrontmatterValue`), and the `instructions` from its markdown\n  body (strip any auto-generated \"Container image bootstrap\" preamble and\n  the leading `---` frontmatter block; what remains is the Discovery\n  prompt). These skip all of Step 7c\u002F7d (no tools) and go straight to\n  `UpsertAgent` in Step 7e with an empty `toolIds`.\n\nSteps:\n\n1. Enumerate promotable agents = every stem in `$existingLocalAgents`\n   (the `.github\u002Fagents\u002F\u003Cname>.agent.md` companions). Persist as\n   `$localAgents`. For each, record `$agentHasCatalogFolder[$name]` =\n   `Test-Path discovery_catalog\u002F\u003Cname>\u002Fagent.yaml`. Do **not** require a\n   `discovery_catalog\u002F` folder — its absence just means \"toolless\".\n   **Exclude the hand-authored, non-Discovery Copilot agents** that ship\n   with the workspace and are not catalog\u002FDiscovery agents — at minimum\n   `batteries-included`, `bookshelf-researcher`, `project-setup-orchestrator`,\n   and `agentic-grader`. A companion qualifies as promotable only if it was\n   produced by this skill (Local target, Step 6) or otherwise represents a\n   Discovery agent; if unsure, prefer companions whose body contains the\n   generated container-bootstrap preamble or that have a matching\n   `discovery_catalog\u002F\u003Cname>\u002F` folder, and skip the rest.\n2. If `$localAgents` is empty, stop and tell the user there are no\n   locally-added agents to promote — they must first add one via the\n   **Local Copilot** target, then re-run for promotion.\n3. Build the same `$catalog` \u002F `$groups` structures Steps 4a\u002F4b produce.\n   For **tool-bearing** agents read `metadata.yaml` \u002F `agent.yaml` from\n   `discovery_catalog\u002F\u003Cname>\u002F`; for **toolless** agents read `name` \u002F\n   `description` from the `.agent.md` frontmatter and set the tool count to\n   `0` (they always land in the *Lightweight (no container tools)* group).\n   Do not set a single `$srcRoot` for tool enumeration — resolve each\n   agent's source per-bucket via `$agentHasCatalogFolder` so Step 7 reads\n   from the right place.\n4. In Step 4e, scope the agent picker to `$localAgents` only (label each\n   `[agent] \u003Cname>`), and drop the \"upstream refresh\" framing — nothing is\n   fetched or overwritten. Optionally annotate toolless entries in the\n   option `description` with `(no container tool)` so the user can tell them\n   apart from tool-bearing ones.\n\n   ```pwsh\n   # Extract the promotable instructions from a toolless .agent.md companion.\n   #\n   # CRLF-SAFE: generated .agent.md companions are written with CRLF line\n   # endings on Windows. A naive `\\n---\\n` horizontal-rule match FAILS to\n   # match (the real bytes are `\\r\\n---\\r\\n`), so the bootstrap strip below\n   # would silently no-op and leave the whole preamble in the body. ALWAYS\n   # use `\\r?\\n---\\r?\\n` for the horizontal-rule delimiter.\n   function Get-AgentMdInstructions([string]$AgentMdPath) {\n     $raw = Get-Content $AgentMdPath -Raw\n     # Drop the leading YAML frontmatter block ( --- ... --- ).\n     $body = $raw -replace '(?s)^\\s*---.*?---\\s*', ''\n     # Drop an auto-generated container-bootstrap preamble, if present:\n     # everything up to and including the first '---' horizontal rule that\n     # the generator emits after the preamble table.\n     if ($body -match '(?s)^\\s*#\\s*Container image bootstrap.*?\\r?\\n---\\r?\\n') {\n       $body = $body -replace '(?s)^\\s*#\\s*Container image bootstrap.*?\\r?\\n---\\r?\\n', ''\n     }\n     return $body.Trim()\n   }\n   ```\n\n   > **CRLF gotcha (verified in a real run).** If you write these regexes\n   > with a bare `\\n---\\n` instead of `\\r?\\n---\\r?\\n`, a CRLF-terminated\n   > companion produces a **tiny** instructions body — in one run just the\n   > appended \"## Tool execution\" note (~369 chars) instead of the real\n   > ~13k-char prompt. After extraction, **sanity-check the length**: a\n   > tool-bearing agent's instructions should be thousands of characters.\n   > If `Get-AgentMdInstructions` returns only a few hundred chars, the\n   > CRLF bug bit you — fix the regex and re-extract before `UpsertAgent`.\n\n   **The `.agent.md` companion is also the source of truth for `name` and\n   `description`** — not just `instructions`. Use this helper to read a\n   scalar value from the companion's YAML frontmatter (the block between the\n   leading `---` fences). It handles both inline (`description: \"...\"`) and\n   the escaped double-quoted form the Step 6 generator emits. Apply it for\n   **both** tool-bearing and toolless promotes so the deployed Discovery\n   agent's `name` \u002F `description` match exactly what the user tuned locally.\n\n   ```pwsh\n   # Read a single scalar key from the .agent.md YAML frontmatter block.\n   # CRLF-safe. Returns '' if the key is absent.\n   function Get-AgentMdFrontmatterValue([string]$AgentMdPath, [string]$Key) {\n     $raw = Get-Content $AgentMdPath -Raw\n     # Isolate the leading frontmatter block ( --- ... --- ).\n     if ($raw -notmatch '(?s)^\\s*---\\r?\\n(.*?)\\r?\\n---\\r?\\n') { return '' }\n     $fm = $matches[1]\n     foreach ($line in ($fm -split \"`r?`n\")) {\n       if ($line -match (\"^\" + [regex]::Escape($Key) + \":\\s*(.+)$\")) {\n         $v = $matches[1].Trim()\n         # Strip surrounding quotes and unescape \\\" and \\\\ from the\n         # double-quoted frontmatter the generator writes.\n         if ($v.StartsWith('\"') -and $v.EndsWith('\"') -and $v.Length -ge 2) {\n           $v = $v.Substring(1, $v.Length - 2) -replace '\\\\\"', '\"' -replace '\\\\\\\\', '\\'\n         } elseif ($v.StartsWith(\"'\") -and $v.EndsWith(\"'\") -and $v.Length -ge 2) {\n           $v = $v.Substring(1, $v.Length - 2)\n         }\n         return $v.Trim()\n       }\n     }\n     return ''\n   }\n   ```\n\n##### Rewriting local container references for tool-bearing promotes\n\nA **tool-bearing** local agent's `.agent.md` companion (and, in rare\nhand-edited cases, its `agent.yaml#instructions`) can reference the tool as\na **local** Podman\u002FDocker container image — e.g. \"build `\u003Ctool>:latest` from\n`discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>`\", \"`podman image inspect`\",\n\"`docker build -t ...`\". Those references are **local-only** and are\nmeaningless in the cloud, where the tool runs as a deployed\n`Microsoft.Discovery\u002Ftools` ARM resource backed by an image in the\nworkspace's Azure Container Registry.\n\nWhen promoting a tool-bearing agent (Step 7), **do not** deploy the local\ncontainer-runtime wording. Instead:\n\n1. Strip the auto-generated bootstrap preamble (already done by\n   `Get-AgentMdInstructions`).\n2. Scrub any **residual** local-runtime references that survive in the body\n   (stray `podman`\u002F`docker` `build|pull|push|image inspect` lines, or lines\n   that point at a `discovery_catalog\u002F...\u002Ftools\u002F...` build context).\n3. Rewrite the tool reference so the cloud instructions point at the\n   **Discovery tool** by name — the one found under\n   `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002F` and registered as an ARM\n   resource in Step 7c\u002F7d — not at any local image tag or build context.\n\nUse this helper (defined alongside `Get-AgentMdInstructions`) to produce\nthe cloud instructions for tool-bearing agents:\n\n```pwsh\n# Rewrite local Podman\u002FDocker container references in a tool-bearing agent's\n# promoted instructions so the cloud prompt references the deployed Discovery\n# tool(s) instead of a local image tag \u002F build context.\nfunction Convert-PromoteInstructionsForTool {\n  param(\n    [Parameter(Mandatory)][string]$Instructions,\n    [Parameter(Mandatory)][string[]]$ToolNames\n  )\n  $text = $Instructions\n\n  # 1. Remove any lingering container-runtime bootstrap section (defense in\n  #    depth — Get-AgentMdInstructions normally already removed it).\n  #    CRLF-SAFE: use `\\r?\\n---\\r?\\n` for the horizontal-rule delimiter.\n  #    A bare `\\n---\\n` never matches a CRLF companion, so the `|\\z`\n  #    fallback would then swallow the ENTIRE body (deleting the real\n  #    prompt and leaving only the appended note). Never use `\\n---\\n` here.\n  $text = $text -replace '(?s)#\\s*Container image bootstrap.*?(\\r?\\n---\\r?\\n|\\z)', ''\n\n  # 2. Drop stray local-runtime instruction lines that reference building \u002F\n  #    inspecting \u002F pulling \u002F pushing a local image or a local build context.\n  $lines = $text -split \"`r?`n\"\n  $kept = foreach ($ln in $lines) {\n    if ($ln -match '(?i)\\b(podman|docker)\\b.*\\b(build|pull|push|image\\s+inspect|info)\\b') { continue }\n    if ($ln -match '(?i)discovery_catalog\u002F[^`\\s]+\u002Ftools\u002F') { continue }\n    if ($ln -match '(?i)\u003Ctool>:latest|:latest\\b.*build\\s+context') { continue }\n    $ln\n  }\n  $text = ($kept -join \"`n\")\n\n  # 3. Ensure the cloud prompt explicitly references the Discovery tool(s) by\n  #    name rather than any local image. Appended once, only if not already\n  #    present.\n  $toolList = ($ToolNames | Sort-Object -Unique) -join ', '\n  if ($ToolNames.Count -gt 0 -and $text -notmatch '(?i)Discovery tool\\b') {\n    $note = @(\n      ''\n      '## Tool execution (Microsoft Discovery)'\n      ''\n      \"This agent runs in Microsoft Discovery. Its tool(s) ($toolList) are provided as deployed Discovery tools whose container images live in the workspace's Azure Container Registry — invoke them as bound Discovery tools. Do NOT build, pull, or inspect any local Podman\u002FDocker image; there is no local container runtime in the cloud.\"\n    ) -join \"`n\"\n    $text = $text.TrimEnd() + \"`n\" + $note\n  }\n\n  # Collapse any 3+ blank lines left by the scrub down to a single blank line.\n  $text = $text -replace \"(\\r?\\n){3,}\", \"`n`n\"\n  return $text.Trim()\n}\n```\n\n#### 4f. Local runtime readiness (conditional)\n\nRun this sub-step **only when `$deployTarget == 'Local'`** and only after the\nagent selection in 4e has resolved to at least one agent in `$selected`.\n\nGoal: determine whether Podman and\u002For Docker are available for local,\nlazy image bootstrap done later by generated `.agent.md` companions.\n\nDetection commands:\n\n```pwsh\n$hasPodman = $false\n$hasDocker = $false\ntry { & podman --version *> $null; if ($LASTEXITCODE -eq 0) { $hasPodman = $true } } catch {}\ntry { & docker --version *> $null; if ($LASTEXITCODE -eq 0) { $hasDocker = $true } } catch {}\n```\n\nDecision flow:\n\n1. If **both** are installed, ask once which runtime the user prefers for\n  local container workflows (`podman` or `docker`). Recommended default:\n  `podman`.\n2. If only one is installed, set that as `$localContainerRuntimePreference`\n  automatically (no prompt).\n3. If neither is installed, ask once whether to install Podman automatically.\n  - If **yes**, install Podman, then re-check `podman --version`:\n\n    ```pwsh\n    winget install --id RedHat.Podman --accept-source-agreements --accept-package-agreements\n    ```\n\n    If install succeeds, set `$localContainerRuntimePreference = 'podman'`.\n  - If **no**, continue, but print a clear notice that agents with\n    container-based tools cannot run until Podman or Docker is installed.\n\nThis step must **not** run any image builds; it only selects\u002Finstalls runtime\nprerequisites for future lazy bootstrap.\n\n#### 4d. Discovery workspace + project selection (conditional)\n\nRun this sub-step whenever `$deployToCloud` is true (`$deployTarget` is\n`Discovery` or `LocalToDiscovery`). Skip entirely for the `Local` target.\n\nExecute the full login \u002F MCP install \u002F tenant + subscription pick \u002F\nworkspace pick \u002F project pick \u002F existing-agent listing \u002F confirmation\nworkflow documented in **Step 7a** (sub-steps 1 through 9). All of Step 7a\nruns here in Step 4d - it has been moved up so the destination is locked\nin before the user is asked which agents to add.\n\nAfter 4d completes you have:\n\n- A working proxy at `.vscode\u002Fdiscovery-mcp-proxy.ps1` (sanity-checked via `Invoke-DiscoveryMcp` — not via VS Code's MCP runtime).\n- An active `az` CLI session pointed at the correct tenant + subscription.\n- `$discoveryTenantId`, `$discoverySubscriptionId`, `$discoveryRg`,\n  `$discoveryWorkspace`, and `$discoveryProject` persisted for Steps 7c\\u20137e.\n- `$existingAgentNames` - the set of agent names already in\n  `$discoveryProject`, printed to chat so the user can spot collisions\n  **before** picking what to add in 4e.\n\nIf the user cancels at the 7a.9 confirmation prompt, stop the workflow\ncleanly - do **not** proceed to 4e, do **not** touch ACR or Foundry, and\ndo **not** copy any agent folders.\n\nWhen Step 7 runs later, **do not** re-prompt for workspace\u002Fproject. Skip\nstraight to Step 7b (Azure MCP probe) and Step 7c (tool ARM pre-flight)\nusing the values persisted here.\n\n#### 4e. Ask which agents to add\n\nTwo-phase prompt flow (`vscode_askQuestions` called up to twice). This is\nthe agent-selection question batch; deployment target and (when applicable)\nworkspace\u002Fproject are already resolved.\n\n**Phase 1 - selection mode** (one question):\n\n```\nheader: \"selection-mode\"\nquestion: \"How do you want to choose which agents to add?\"\noptions:\n  - \"All agents\"      (recommended)\n  - \"Specific agents\" (user picks individual agents in phase 2)\n  - \"By group\"        (user picks one or more tag groups in phase 2)\n```\n\n**Phase 2 - selection value** (skip when `selection-mode == 'All agents'`).\nThe options list is **scoped to the phase-1 answer**:\n\n| selection-mode    | Phase 2 options                                                                  |\n|-------------------|----------------------------------------------------------------------------------|\n| `All agents`      | (skip phase 2)                                                                   |\n| `Specific agents` | Individual agents only - `[agent] \u003Cfolder>` entries, sorted alphabetically.   |\n| `By group`        | Groups only - `[group] \u003Cname> (N)` and `[lightweight] no-container-tools (N)` entries. |\n\n```\nheader: \"selection-value\"\nquestion: \"Pick one or more \u003Cagents | groups>.\"\nmultiSelect: true\noptions: \u003Cscoped to the phase-1 mode>\n```\n\n**Specific agents mode:** every entry in `$catalog`, label formatted as\n`\"[agent] \u003Cfolder>\"` with the agent's short description in the option's\n`description` field. **Do not include any `[group]` or `[lightweight]`\nentries** in this mode.\n\n**By group mode:** every key in `$groups` plus the synthetic\n`[lightweight] no-container-tools` entry, label formatted as\n`\"[group] \u003Cname> (N agents)\"`. **The option's `description` field MUST\nlist the member agents.** Do not include individual `[agent]` entries\nin this mode.\n\n**Discovery collision hint (only when `$deployToCloud` is true — `$deployTarget` is `Discovery` or `LocalToDiscovery`).**\nFor each option whose folder name appears in `$existingAgentNames` (from\n4d), prepend `[ALREADY IN PROJECT] ` to the option's `description` field\nso the user knows re-selecting it will trigger an `UpsertAgent` update in\nthe chosen project. Do not block the choice - just surface it.\n\n**Local collision hint (only when `$deployTarget == 'Local'`).** For each\noption whose folder name appears in `$existingLocalAgents` (the set of\n`.github\u002Fagents\u002F\u003Cname>.agent.md` stems from Step 1), prepend\n`[ALREADY ADDED LOCALLY] ` to the option's `description` field so the user\nknows re-selecting it will overwrite the existing `.agent.md` companion in\nplace. Do not block the choice - just surface it. Always derive this hint\nfrom `.github\u002Fagents\u002F`, never from `discovery_catalog\u002F` (the latter is\nrefreshed unconditionally in Step 5 and therefore can't distinguish new vs\nalready-installed agents).\n\n#### Group member display rule\n\nEvery group option presented in phase 2 **must include the names of the\nagents in that group** in the option's `description` field. This is how the\nuser knows what's actually in `drug-discovery`, `cheminformatics`, etc.\nwithout needing to ask back.\n\nFormatting rules for the description:\n\n- Comma-separated, alphabetically sorted folder names.\n- Truncate to ~120 characters and append `, \\u2026(+N more)` if the full list is\n  longer. Example: `\"aizynthfinder, autodock, bindingdb, boltztwo, retrochimera, tamgen\"`.\n- For **Lightweight (no container tools)**, always list the full member set - it's\n  small by definition.\n\nFilter the group list shown to the user to **tags with \\u2265 2 agents** plus the\nsynthetic `Lightweight (no container tools)` entry. Singleton tags add noise and the\nagent itself is already pickable in `Specific agents` mode.\n\nSort the group options by member count (descending), so the broadest groups\nappear first.\n\n#### Resolve the final selection\n\nThen resolve the final set of folders to add:\n\n- Mode = **All agents** \\u2192 `$selected = $catalog.Folder`\n- Mode = **Specific agents** \\u2192 for each phase-2 answer starting with\n  `[agent] `, strip the prefix and look it up in `$catalog.Folder`.\n- Mode = **By group** \\u2192 for each phase-2 answer starting with `[group] ` or\n  `[lightweight] `, strip the prefix and union the folders in `$groups[$name]`\n  (or the lightweight set).\n\nUnknown phase-2 entries (typos, freeform): treat as agent folder names and\nwarn if they don't resolve. If `$selected` is empty after resolution, ask\nphase 2 again once; if still empty, stop and report.\n\nPrint the resolved selection back to chat before proceeding:\n\n```\nWill add 7 agent(s): pubchem, rdkit, online-researcher, ...\n```\n\n### Step 5 — Refresh selected agents in `discovery_catalog\u002F`\n\n> **Skip this entire step when `$deployTarget == 'LocalToDiscovery'`**\n> (`$sourceMode == 'Local'`). The promote target treats the existing local\n> `discovery_catalog\u002F\u003Cname>\u002F` folder as the source of truth; overwriting it\n> with upstream would discard the local edits being promoted. Jump straight\n> to Step 7.\n\n**Always refresh from upstream (Upstream source mode only).** For every folder\nin `$selected`, replace `discovery_catalog\u002F\u003Cname>\u002F` with the upstream copy from\n`agents\u002F\u003Cname>\u002F`. This guarantees the local catalog reflects the\nlatest upstream content (bug fixes, new tools, updated prompts) and that\nany change to the agent list is surfaced. **Do not prompt the user before\noverwriting** — the `discovery_catalog\u002F` tree is a managed mirror, not\nuser-authored content.\n\n```pwsh\n$srcRoot = Join-Path $work 'agents'\n$dstRoot = Join-Path $workspaceRoot 'discovery_catalog'\n\n$createdFolders   = @()   # folder did not exist locally — created fresh\n$refreshedFolders = @()   # folder existed locally — overwritten with upstream\n$skipped          = @()   # name not in upstream (folder may have been removed)\n\n$selected | ForEach-Object {\n    $name = $_\n    $src  = Join-Path $srcRoot $name\n    $dst  = Join-Path $dstRoot $name\n    if (-not (Test-Path $src)) { $skipped += \"$name (not in upstream)\"; return }\n    $existed = Test-Path $dst\n    if ($existed) {\n        # Always replace in full so renamed\u002Fremoved files don't linger.\n        Remove-Item -Recurse -Force $dst\n    }\n    Copy-Item -Recurse -Force $src $dst\n    if ($existed) { $refreshedFolders += $name } else { $createdFolders += $name }\n}\n```\n\n**Rules:**\n\n- Always refresh `discovery_catalog\u002F\u003Cname>\u002F` from upstream — no overwrite\n  prompt. Stale folders silently mask upstream changes.\n- Replace each refreshed folder in full (delete then copy) so files removed\n  upstream don't linger locally.\n- Never touch `discovery_catalog\u002F\u003Cname>\u002F` folders that are **not** in\n  `$selected` — leave them as-is. Removal of unselected agents is out of\n  scope for this step.\n- Preserve file casing exactly as upstream (Windows is case-insensitive but the\n  repo metadata is case-sensitive on Linux containers).\n- Do **not** rename `tools\u002F\u003CTool>\u002F` — the directory name is referenced by\n  `metadata.yaml#associated_tools` and `agent.yaml#discoveryExtensions.tools`.\n- The \"already added locally\" determination for the summary (Step 8) and\n  for the Step 4e Local collision hint comes from\n  `.github\u002Fagents\u002F\u003Cname>.agent.md` presence (captured in Step 1 as\n  `$existingLocalAgents`), **not** from this folder. Two distinct concepts:\n  - `$createdFolders` \u002F `$refreshedFolders` — state of `discovery_catalog\u002F`\n  - `$existingLocalAgents`               — state of `.github\u002Fagents\u002F`\n\n### Step 6 — Generate Copilot agent companions\n\nFor every folder in `$selected` (that successfully copied or was already\npresent locally), emit a sibling Copilot agent file at\n`.github\u002Fagents\u002F\u003Cname>.agent.md`. This is what makes each Discovery agent\ninvocable as a Copilot subagent via `runSubagent`.\n\nDo **not** regenerate `.agent.md` files for agents the user did not select in\nStep 4 — leaving those files untouched preserves prior selections and avoids\nsurprising the user.\n\nThe Copilot agent file is a markdown file with YAML frontmatter, distinct from\nthe Discovery `agent.yaml`. Map fields as follows:\n\n| Copilot frontmatter | Source |\n|---|---|\n| `name` | `discovery_catalog\u002F\u003Cname>\u002Fagent.yaml#name` (fallback: folder name) |\n| `description` | `agent.yaml#description` — first paragraph, collapsed to one line, quoted |\n| `argument-hint` | `\"Query or input for the \u003Cname> agent\"` |\n| `user-invocable` | `true` |\n\nThe **body** of the `.agent.md` file is composed of two parts, in this order:\n\n1. A **container runtime bootstrap preamble** (generated by this skill, see\n  template\n   below) listing the exact image tags and Dockerfile paths for every tool\n   under `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F`. The preamble instructs the agent\n  to verify each image exists locally before invoking the tool, and to build\n  it from the matching Dockerfile only if missing. Runtime order is fixed:\n  try Podman first, then Docker if Podman is unavailable or fails.\n2. The verbatim contents of `agent.yaml#instructions` (the Discovery prompt\n   block). Do NOT translate, summarize, or re-wrap it — Discovery agents are\n   tuned against that exact text.\n\nDo NOT include a `tools:` frontmatter key. Discovery tool IDs (the `toolId`\nplaceholders inside `discoveryExtensions.tools`) don't map to Copilot tool\nnames, and adding the wrong list silently disables tools.\n\n#### Container runtime bootstrap preamble template\n\nFor an agent whose folder is `discovery_catalog\u002F\u003Cname>\u002F` with tool\nsubdirectories `tools\u002F\u003CTool1>\u002F`, `tools\u002F\u003CTool2>\u002F`, etc., the preamble looks\nlike this (substitute the agent name and the actual tool rows):\n\n```markdown\n# Container image bootstrap (auto-generated by add-agent-from-catalog)\n\nThis agent depends on local container images. **Before invoking any\ntool, you MUST verify each image exists and build it only if it is missing.**\nDo not rebuild images that are already present — builds are expensive.\n\n| Image tag | Build context |\n|---|---|\n| `\u003Ctool1>:latest` | `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool1>` |\n| `\u003Ctool2>:latest` | `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool2>` |\n\nProcedure for each image (Podman first, Docker fallback):\n\n1. Try Podman first:\n  - `podman image inspect \u003Ctag>`; if exit code is `0`, the image exists —\n    **skip the build**.\n  - If missing, confirm `podman info` succeeds, then run\n    `podman build -t \u003Ctag> \u003Cbuild-context>`.\n2. If Podman is unavailable or fails, fall back to Docker:\n  - `docker image inspect \u003Ctag>`; if exit code is `0`, the image exists —\n    **skip the build**.\n  - If missing, confirm `docker info` succeeds, then run\n    `docker build -t \u003Ctag> \u003Cbuild-context>`.\n3. If neither runtime is available, stop and report that Podman or Docker\n  must be installed before container-based tools can run.\n4. Never `podman push` \u002F `docker push` and never touch any registry — this bootstrap is\n   strictly local.\n\nDo this lazily — only when a tool is actually about to be invoked, not on\nevery turn. After a successful build, the image will satisfy the\ninspect check on subsequent runs.\n```\n\nWhen an agent has **no** `tools\u002F*\u002FDockerfile` (rare — e.g. pure LLM agents like\n`bookshelf-researcher`, `online-researcher`), omit the preamble entirely.\n\n#### Generation script\n\nUse the `powershell-yaml` module if available, otherwise parse with a\nregex-lite reader that extracts only the three fields we need (`name`,\n`description`, `instructions`). Always overwrite existing `.agent.md` files —\nthey are derived artifacts, not user-edited.\n\n**Mandatory hardening from observed local runs:**\n\n- Materialize the generation logic into a temp `.ps1` file and run it with\n  `pwsh -NoProfile -File`; do not paste this multi-line script directly into\n  the shared terminal.\n- For `.github\u002Fagents\u002F*.agent.md` collision detection, strip the full\n  `.agent.md` suffix. Never use `.BaseName`, because `pubchem.agent.md`\n  becomes `pubchem.agent`.\n- Treat YAML block-scalar markers (`|`, `|-`, `>`, `>-`) as \"no inline value\"\n  and then read the indented block. Otherwise generated frontmatter can become\n  `description: \"|\"` instead of the real description.\n- Write generated `.agent.md` files with a `FileStream` opened with\n  `FileShare.ReadWrite`. VS Code and the extension host may briefly read these\n  files during generation; plain `Set-Content` can fail with \"file is being\n  used by another process\". A rerun is safe, but the shared writer avoids most\n  transient locks.\n\n```pwsh\n$agentsDir = Join-Path $workspaceRoot '.github\u002Fagents'\nNew-Item -ItemType Directory -Force -Path $agentsDir | Out-Null\n\nfunction Get-SimpleYamlValue([string[]]$Lines, [string]$Key) {\n  foreach ($line in $Lines) {\n    if ($line -match (\"^\" + [regex]::Escape($Key) + \":\\s*(.+)$\")) {\n      $value = $matches[1].Trim().Trim('\"').Trim(\"'\")\n      if ($value -match '^[>|][-+]?$') { return '' }\n      return $value\n    }\n  }\n  return ''\n}\n\nfunction Get-YamlBlock([string[]]$Lines, [string]$Key) {\n  $start = -1\n  for ($i = 0; $i -lt $Lines.Count; $i++) {\n    if ($Lines[$i] -match (\"^\" + [regex]::Escape($Key) + \":\\s*[>|][-+]?\\s*$\")) {\n      $start = $i + 1\n      break\n    }\n  }\n  if ($start -lt 0) { return '' }\n\n  $end = $Lines.Count - 1\n  for ($i = $start; $i -lt $Lines.Count; $i++) {\n    if ($Lines[$i] -match '^[A-Za-z0-9_-]+:\\s*') {\n      $end = $i - 1\n      break\n    }\n  }\n  if ($end -lt $start) { return '' }\n\n  $block = @($Lines[$start..$end])\n  $nonBlank = $block | Where-Object { $_ -match '\\S' }\n  $minIndent = 0\n  if ($nonBlank.Count -gt 0) {\n    $minIndent = ($nonBlank | ForEach-Object {\n      if ($_ -match '^(\\s*)') { $matches[1].Length }\n    } | Measure-Object -Minimum).Minimum\n  }\n  $out = $block | ForEach-Object {\n    if ($_.Length -ge $minIndent) { $_.Substring($minIndent) } else { $_ }\n  }\n  return (($out -join \"`n\").TrimEnd())\n}\n\nfunction Escape-FrontmatterDoubleQuoted([string]$Value) {\n  if ($null -eq $Value) { return '' }\n  return (($Value.Replace('\\', '\\\\').Replace('\"', '\\\"')) -replace \"`r?`n\", ' ')\n}\n\nfunction Write-GeneratedText([string]$Path, [string]$Text) {\n  $encoding = [System.Text.UTF8Encoding]::new($false)\n  $stream = [System.IO.File]::Open(\n    $Path,\n    [System.IO.FileMode]::Create,\n    [System.IO.FileAccess]::Write,\n    [System.IO.FileShare]::ReadWrite)\n  try {\n    $writer = [System.IO.StreamWriter]::new($stream, $encoding)\n    try { $writer.Write($Text) } finally { $writer.Dispose() }\n  } finally {\n    $stream.Dispose()\n  }\n}\n\n$existingLocalAgents = @{}\nGet-ChildItem $agentsDir -Filter '*.agent.md' -File -ErrorAction SilentlyContinue | ForEach-Object {\n  $stem = $_.Name -replace '\\.agent\\.md$', ''\n  $existingLocalAgents[$stem] = $true\n}\n\n$generated = @(); $skipped = @()\n$selected | ForEach-Object {\n    $folder    = $_\n    $agentDir  = Join-Path $workspaceRoot \"discovery_catalog\u002F$folder\"\n    if (-not (Test-Path $agentDir)) { $skipped += \"$folder (folder missing)\"; return }\n    $agentYaml = Join-Path $agentDir 'agent.yaml'\n    if (-not (Test-Path $agentYaml)) { $skipped += \"$folder (no agent.yaml)\"; return }\n\n    $lines = @(Get-Content $agentYaml)\n\n    $name = Get-SimpleYamlValue $lines 'name'\n    if ([string]::IsNullOrWhiteSpace($name)) { $name = $folder }\n\n    $desc = Get-SimpleYamlValue $lines 'description'\n    if ([string]::IsNullOrWhiteSpace($desc)) {\n      $descBlock = Get-YamlBlock $lines 'description'\n      $desc = ($descBlock -split \"`n\" | Where-Object { $_.Trim() } | Select-Object -First 1).Trim()\n    }\n    if ([string]::IsNullOrWhiteSpace($desc)) { $desc = \"Discovery agent: $folder\" }\n    $descEsc = Escape-FrontmatterDoubleQuoted $desc\n\n    $instructions = Get-YamlBlock $lines 'instructions'\n    if ([string]::IsNullOrWhiteSpace($instructions)) {\n      $instructions = '(No instructions defined in agent.yaml.)'\n      $skipped += \"$folder (empty instructions)\"\n    }\n\n    # Enumerate tool images for the container-runtime bootstrap preamble.\n    $toolRows = @()\n    $toolsRoot = Join-Path $agentDir 'tools'\n    if (Test-Path $toolsRoot) {\n        Get-ChildItem $toolsRoot -Directory | ForEach-Object {\n            if (Test-Path (Join-Path $_.FullName 'Dockerfile')) {\n                $tag = ($_.Name).ToLower() + ':latest'\n                $ctx = \"discovery_catalog\u002F$folder\u002Ftools\u002F$($_.Name)\"\n                $toolRows += \"| ``$tag`` | ``$ctx`` |\"\n            }\n        }\n    }\n\n    $preamble = ''\n    if ($toolRows.Count -gt 0) {\n        $preamble = @(\n            '# Container image bootstrap (auto-generated by add-agent-from-catalog)'\n            ''\n            'This agent depends on local container images. **Before invoking any tool, you MUST verify each image exists and build it only if it is missing.** Do not rebuild images that are already present.'\n            ''\n            '| Image tag | Build context |'\n            '|---|---|'\n        ) + $toolRows + @(\n            ''\n            'For each image (Podman first, Docker fallback):'\n            ''\n            '1. Try Podman first: run `podman image inspect \u003Ctag>`. If exit code is `0`, the image exists — **skip the build**. If missing, confirm `podman info` succeeds, then run `podman build -t \u003Ctag> \u003Cbuild-context>`.'\n            '2. If Podman is unavailable or fails, fall back to Docker: run `docker image inspect \u003Ctag>`. If exit code is `0`, the image exists — **skip the build**. If missing, confirm `docker info` succeeds, then run `docker build -t \u003Ctag> \u003Cbuild-context>`.'\n            '3. If neither runtime is available, stop and report that Podman or Docker must be installed before container-based tools can run.'\n            '4. Never `podman push` \u002F `docker push` and never touch a registry — bootstrap is strictly local.'\n            ''\n            'Do this lazily — only when a tool is actually about to be invoked.'\n            ''\n            '---'\n            ''\n        ) -join \"`n\"\n    }\n\n    $frontmatter = @(\n        '---'\n        \"name: $name\"\n        \"description: `\"$descEsc`\"\"\n        \"argument-hint: `\"Query or input for the $name agent`\"\"\n        'user-invocable: true'\n        '---'\n        ''\n    ) -join \"`n\"\n\n    $out = Join-Path $agentsDir \"$folder.agent.md\"\n    Write-GeneratedText -Path $out -Text ($frontmatter + $preamble + $instructions + \"`n\")\n    $generated += $folder\n}\n```\n\nRules:\n\n- Use the **folder name** as the `.agent.md` filename (e.g.\n  `discovery_catalog\u002Fpubchem\u002F` → `.github\u002Fagents\u002Fpubchem.agent.md`). This\n  guarantees no collisions even if two `agent.yaml` files share a `name:` field.\n- Always **overwrite** existing `.agent.md` files. They are derived, not\n  hand-authored. Do NOT prompt the user about overwrites in `.github\u002Fagents\u002F`.\n- Preserve hand-authored Copilot agents (`batteries-included.agent.md`,\n  `bookshelf-researcher.agent.md`, `project-setup-orchestrator.agent.md`) by\n  only writing files whose stem matches a `discovery_catalog\u002F\u003Cname>\u002F` folder.\n- If `agent.yaml#instructions` is missing or empty, still emit the frontmatter\n  with a body of `(No instructions defined in agent.yaml.)` and record the\n  agent in the summary's `skipped`\u002F`degraded` list.\n- Omit the container-runtime bootstrap preamble entirely for agents that have no\n  `tools\u002F*\u002FDockerfile` upstream.\n- Do not embed any local `podman build` \u002F `docker build` calls in this skill\n  itself — the skill must never invoke local image builds.\n\n### Step 7 — Deploy to Microsoft Discovery + Azure (conditional)\n\nRun this step when `$deployToCloud` is true — i.e. `$deployTarget` from\nStep 4c is either `Discovery` (upstream-sourced) or `LocalToDiscovery`\n(promoted from the local app). For each folder in `$selected`, this step\npushes the agent's tool container image(s) to Azure Container Registry and\nregisters the agent in the Microsoft Discovery agent registry as a hosted\nprompt agent.\n\n**Source difference for `LocalToDiscovery`:** the local workspace is the\nsource — nothing is re-fetched from upstream. Each selected agent falls into\none of two buckets (classified in Step 4c.LTD via\n`$agentHasCatalogFolder`):\n\n- **Tool-bearing** (`discovery_catalog\u002F\u003Cname>\u002F` exists) — the tool subtree\n  files (`metadata.yaml`, `tools\u002F\u003CTool>\u002FDockerfile`, `tool.yaml`) and the\n  `name` \u002F `description` fields come from that local folder. The\n  **`instructions`** come from the `.github\u002Fagents\u002F\u003Cname>.agent.md`\n  companion (via `Get-AgentMdInstructions`), **not** from `agent.yaml`\n  (see Step 7e.1). Tool images are pushed from the local build context \u002F\n  locally-built image (see Step 7d.LTD). Runs the full 7c → 7d → 7e path.\n- **Toolless** (no `discovery_catalog\u002F\u003Cname>\u002F` folder) — the agent has **no\n  container tool**. Skip 7c and 7d entirely (nothing to pre-flight, build,\n  or bind). Source `name` \u002F `description` \u002F `instructions` from the\n  `.github\u002Fagents\u002F\u003Cname>.agent.md` companion (see the\n  `Get-AgentMdInstructions` helper in Step 4c.LTD) and go straight to 7e\n  with an empty `toolIds`.\n\nEverything else — workspace\u002Fproject pick (7a), MCP probe (7b),\n`UpsertAgent` + `GetAgent` poll (7e) — is identical for both buckets.\n\n**Workspace + project were already chosen in Step 4d.** Do **not** re-prompt\nfor tenant, subscription, workspace, or project here. Reuse\n`$discoveryTenantId`, `$discoverySubscriptionId`, `$discoveryRg`,\n`$discoveryWorkspace`, `$discoveryProject`, and `$existingAgentNames`\npersisted by 4d. Step 7a below documents the workspace\u002Fproject picker\n**only** so 4d has something concrete to invoke; in normal flow, 7a never\nruns from inside Step 7 — it has already run as part of 4d.\n\n**Prefer MCP servers over raw CLI commands.** Use the Discovery MCP and Azure\nMCP whenever they are available; only fall back to terminal commands when the\nrequired MCP capability is not present.\n\n#### 7a. Discovery login, workspace + project selection, existing-agent listing\n\n> **Where this runs.** In the normal flow, 7a is invoked **from Step 4d**\n> (before the agent picker), not from inside Step 7. The sub-section\n> remains under Step 7 because it is part of the Discovery deploy machinery;\n> Step 4d explicitly delegates to it. If you find yourself entering Step 7\n> without `$discoveryWorkspace` \u002F `$discoveryProject` set, you skipped 4d —\n> go back and run it before continuing.\n\nBefore asking for Azure resource names, the user must be signed in to\nMicrosoft Discovery and must pick the Discovery **workspace** and **project**\nthe new agents will be deployed into. Always show the currently-registered\nagents in the chosen project **before** Step 7c pre-flights the tool ARMs\nand (if needed) Step 7c.2 prompts for ACR\u002FRG, so the user can spot\nduplicates and abort early.\n\n1. **Install the proxy (single extraction, no probe).** The Discovery MCP\n  server is the Microsoft-hosted remote streamable-HTTP endpoint at\n  `https:\u002F\u002Fmcp.discovery.azure.com\u002Fmcp`. The skill embeds the PowerShell\n  stdio proxy and invocation helper at the end of this `SKILL.md`; the\n  bootstrap below extracts them into `.vscode\u002F` so PowerShell and VS Code\n  can execute normal `.ps1` files. **Always materialize** the scripts into\n  `.vscode\u002F` at the start of Step 4d — do NOT probe for it first, do NOT depend on VS Code's MCP\n   runtime ever surfacing `mcp_microsoft-dis_*` deferred tools in this\n   session:\n\n   ```pwsh\n   $skillDir = '\u003Cabsolute path to add-agent-from catalog folder>'\n   New-Item -ItemType Directory -Force -Path \"$workspaceRoot\\.vscode\" | Out-Null\n  $skillPath = Join-Path $skillDir 'SKILL.md'\n  $skillText = Get-Content $skillPath -Raw\n  function Write-EmbeddedSkillScript([string]$BlockId, [string]$Destination) {\n       $begin = \"\u003C!-- BEGIN:$BlockId -->\"\n       $end = \"\u003C!-- END:$BlockId -->\"\n       $start = $skillText.IndexOf($begin)\n       if ($start -lt 0) { throw \"Embedded script block '$BlockId' not found in $skillPath\" }\n       $contentStart = $start + $begin.Length\n       $stop = $skillText.IndexOf($end, $contentStart)\n       if ($stop -lt 0) { throw \"Embedded script block '$BlockId' has no end marker in $skillPath\" }\n       $block = $skillText.Substring($contentStart, $stop - $contentStart).Trim()\n       $lines = @($block -split \"`r?`n\")\n       if ($lines.Count -lt 3 -or $lines[0] -notmatch '^```powershell\\s*$' -or $lines[-1] -notmatch '^```\\s*$') {\n           throw \"Embedded script block '$BlockId' must be wrapped in a powershell fenced code block.\"\n       }\n       $content = (($lines[1..($lines.Count - 2)]) -join \"`r`n\") + \"`r`n\"\n       Set-Content -Path $Destination -Value $content -Encoding UTF8\n   }\n   Write-EmbeddedSkillScript 'embedded-discovery-mcp-proxy.ps1' \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\"\n   Write-EmbeddedSkillScript 'embedded-Invoke-DiscoveryMcp.ps1' \"$workspaceRoot\\.vscode\\Invoke-DiscoveryMcp.ps1\"\n   ```\n\n   That is the entire MCP install. From here on, **every** MCP call goes\n  through `Invoke-DiscoveryMcp` (extracted helper) → proxy → HTTPS. See\n   the \"Scripted MCP invocation\" section near the top of this skill for\n   the canonical call pattern.\n\n   The legacy `agents action=registry.list` probe, the mcp.json HTTP\n   server entry, the `workbench.action.mcp.restart` ritual, and the\n   `workbench.action.mcp.listServers` fallback are **all optional** and\n   only benefit the user's future interactive VS Code sessions. They do\n   nothing for this skill's run — do not waste turns on them. If you\n   still want to write `.vscode\u002Fmcp.json` for the user's convenience,\n   do it once with the merge-safe script in 7a.2 below and **do not**\n   block on the restart or any tool surfacing.\n\n   Sanity-check the proxy is reachable in one quick call:\n\n   ```pwsh\n  . \"$workspaceRoot\\.vscode\\Invoke-DiscoveryMcp.ps1\"\n   $r = Invoke-DiscoveryMcp -ProxyPath \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\" -Calls @(@{ name='Ping'; args=@{} })\n   if (-not $r['2']) { throw 'Proxy not responding — check az login and PowerShell 7+.' }\n   ```\n\n2. **(Optional, courtesy)** Register the proxy in `.vscode\u002Fmcp.json` so\n   it shows up in the user's MCP server list for future interactive\n   sessions. This is a write-once, fire-and-forget step — the rest of\n   the skill does NOT depend on VS Code loading those tools.\n\n      **`.vscode\u002Fdiscovery-mcp-proxy.ps1`** is the canonical proxy\n      implementation generated from this `SKILL.md`. The embedded block\n      below is authoritative — extract it verbatim into new workspaces; do\n      not reimplement it inline. Requirements: PowerShell 7+ (uses\n      `Invoke-WebRequest -SkipHttpErrorCheck`) and `az` CLI on PATH with\n      an active session.\n\n      **`.vscode\u002Fmcp.json`** — register the proxy as a stdio server:\n      ```json\n      {\n        \"servers\": {\n          \"microsoft-discovery\": {\n            \"type\": \"stdio\",\n            \"command\": \"pwsh\",\n            \"args\": [\n              \"-NoProfile\",\n              \"-File\",\n              \"${workspaceFolder}\u002F.vscode\u002Fdiscovery-mcp-proxy.ps1\"\n            ]\n          }\n        }\n      }\n      ```\n\n      **Idempotent merge script** — read existing `.vscode\u002Fmcp.json` (if\n      any), drop any legacy `discovery-token` promptString input and any\n      legacy `type: \"http\"` microsoft-discovery server from earlier\n      versions of this skill, then insert the canonical stdio entry.\n      Preserve every other server and input untouched.\n\n      ```pwsh\n      $mcpPath = Join-Path $workspaceRoot '.vscode\u002Fmcp.json'\n      $mcpDir  = Split-Path $mcpPath -Parent\n      if (-not (Test-Path $mcpDir)) { New-Item -ItemType Directory -Force -Path $mcpDir | Out-Null }\n\n      if (Test-Path $mcpPath) {\n          $cfg = Get-Content $mcpPath -Raw | ConvertFrom-Json -Depth 10\n      } else {\n          $cfg = [pscustomobject]@{ servers = [pscustomobject]@{} }\n      }\n      if (-not $cfg.PSObject.Properties['servers']) {\n          $cfg | Add-Member -NotePropertyName servers -NotePropertyValue ([pscustomobject]@{})\n      }\n\n      # Drop the legacy promptString-based discovery-token input.\n      if ($cfg.PSObject.Properties['inputs']) {\n          $remaining = @($cfg.inputs | Where-Object { $_.id -ne 'discovery-token' })\n          if ($remaining.Count -eq 0) {\n              $cfg.PSObject.Properties.Remove('inputs')\n          } else {\n              $cfg.inputs = $remaining\n          }\n      }\n\n      # Canonical stdio-proxy server entry.\n      $serverEntry = [pscustomobject]@{\n          type    = 'stdio'\n          command = 'pwsh'\n          args    = @('-NoProfile', '-File', '${workspaceFolder}\u002F.vscode\u002Fdiscovery-mcp-proxy.ps1')\n      }\n      if ($cfg.servers.PSObject.Properties['microsoft-discovery']) {\n          $cfg.servers.'microsoft-discovery' = $serverEntry\n      } else {\n          $cfg.servers | Add-Member -NotePropertyName 'microsoft-discovery' -NotePropertyValue $serverEntry\n      }\n\n      $cfg | ConvertTo-Json -Depth 10 | Set-Content -Path $mcpPath -Encoding UTF8\n      ```\n\n      Guard-rails:\n      - Never blow away the file — always merge. Other servers (GitHub\n        MCP, Azure MCP, etc.) under `servers` and other entries under\n        `inputs` must remain byte-for-byte.\n      - **Always overwrite** any pre-existing `microsoft-discovery`\n        entry — including legacy `type: \"http\"` configs with the\n        `promptString` bearer header. The stdio proxy is the only\n        supported config for this skill.\n      - Do **not** write tokens, tenant IDs, or subscription IDs into\n        `mcp.json`. The proxy reads the active `az` session at runtime,\n        which is configured by Step 7a.2.5 below.\n\n  2.6. **(Optional) Restart the VS Code MCP server** - only useful for\n       the user's future interactive sessions; the skill itself does\n       NOT use the surfaced `mcp_microsoft-dis_*` tools. Skipping this\n       step is **fine** - the proxy + `Invoke-DiscoveryMcp` work\n       without any restart.\n\n       If you do want to be polite to the user:\n       1. Try `run_vscode_command commandId='workbench.action.mcp.restart'`\n          (no window reload). If the command id isn't found, stop - do\n          NOT escalate to a window reload mid-run.\n       2. **Do not** smoke-test by waiting for `mcp_microsoft-dis_*`\n          tools to appear via `tool_search`. They frequently do not\n          appear in the same session. Smoke-test via the proxy instead:\n\n       ```pwsh\n         . \"$workspaceRoot\\.vscode\\Invoke-DiscoveryMcp.ps1\"\n       $r = Invoke-DiscoveryMcp -ProxyPath \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\" -Calls @(\n           @{ name='ListWorkspaces'; args=@{ subscriptionId=$discoverySubscriptionId } }\n       )\n       (Get-DiscoveryMcpText -Response $r['2'] -AsJson).value.Count   # > 0 means healthy\n       ```\n\n       Common failure \\u2192 fix:\n\n       | Symptom from proxy                              | Cause                                                              | Fix                                                                                              |\n       |-------------------------------------------------|--------------------------------------------------------------------|--------------------------------------------------------------------------------------------------|\n       | `pwsh: command not found` from terminal        | PowerShell 7+ is not on PATH                                       | Install with `winget install Microsoft.PowerShell` - Windows PowerShell 5.1 is too old           |\n       | `az: command not found` on proxy stderr         | Azure CLI is not on PATH for the proxy's shell                     | Install Azure CLI and reopen the terminal so the new PATH is inherited                            |\n       | `401 InvalidAuthenticationTokenTenant`          | `az` is signed into the wrong tenant for the chosen subscription   | Re-run Step 7a.2.5 (`az login --tenant \u003Cid>`); the proxy auto-refreshes on the next request      |\n       | `AADSTS500011` (resource principal not found)   | Tenant has never consented to the Discovery first-party app        | Admin consent required - surface the error and stop; the skill cannot fix this                  |\n       | `mcp_microsoft-dis_*` tools never appear        | VS Code MCP runtime hasn't surfaced them (common, often permanent) | **Ignore** - use the proxy via `Invoke-DiscoveryMcp` instead. Do NOT poll `tool_search` for them. |\n       | Proxy exits with non-zero on launch             | `az account get-access-token` failed at startup                     | Re-run Step 7a.2.5 to fix the `az` session, then try again                                       |\n\n  2.5. **Prompt the user for tenant + subscription and run `az` on their\n       behalf.** Do this **before** starting (or restarting) the Discovery\n       MCP server so the bearer-token input resolves cleanly.\n\n       **Always prompt.** Even when `az account show` already returns a\n       valid session and `\u002Fmemories\u002Frepo\u002F` has a previously-used tenant\n       and subscription, you MUST still ask the user. Saved values are\n       used **only** to mark the matching option as `recommended: true`\n       in the picker — never to auto-select and skip the prompt. The\n       user opted into the Discovery + Azure path; that opt-in does not\n       grant permission to silently reuse a prior destination.\n\n       Workflow:\n\n       a. Run `az account list --query \"[].{name:name, id:id, tenantId:tenantId, isDefault:isDefault}\" -o json`\n          to enumerate every subscription the user has at least Reader on.\n          Group the results by `tenantId` so the picker lists each tenant\n          alongside its subscriptions.\n       b. Ask the user **once** with `vscode_askQuestions` (two questions\n          in a single call):\n          - **Question 1 — `discovery-tenant`** (single-select, required):\n            options are the distinct `tenantId` values from (a). Label\n            each with a short alias derived from the most common\n            subscription suffix (e.g. `\"corp (72f988bf-…)\"`) and put the\n            full GUID + member-subscription count in the `description`\n            field. If `\u002Fmemories\u002Frepo\u002F` has a previously-used tenant,\n            mark that option as `recommended: true` so it appears as the\n            default — but the prompt must still be shown.\n          - **Question 2 — `discovery-subscription`** (single-select,\n            required, freeform allowed): options are the subscriptions in\n            the tenant chosen in Q1. Label `\"\u003Cname> (\u003Csub-id-prefix>…)\"`,\n            full GUID in `description`. Mark the previously-used\n            subscription (if any in `\u002Fmemories\u002Frepo\u002F`) as\n            `recommended: true`; otherwise mark the `isDefault: true`\n            subscription that way.\n\n          The picker is a **single `vscode_askQuestions` call with two\n          questions** — do **not** call it twice. Because Q2's option list\n          depends on Q1's answer, build Q2 with **all** subscriptions\n          across all tenants and let the user filter — or, if you want a\n          two-phase flow, ask Q1 first, then make a second call for Q2\n          scoped to the chosen tenant. Either is acceptable; the two-phase\n          flow keeps the option list short.\n\n       c. Persist the chosen values as `$discoveryTenantId` and\n          `$discoverySubscriptionId` and write them to `\u002Fmemories\u002Frepo\u002F`\n          so future runs can pre-select (not auto-select) them as the\n          recommended option.\n       d. Run, in this order, in a **foreground** terminal so the user can\n          complete device-flow auth if prompted:\n          ```pwsh\n          az login --tenant $discoveryTenantId\n          az account set --subscription $discoverySubscriptionId\n          ```\n          If `az account show` already reports the chosen tenant and\n          subscription, you may skip the `az login` call and only run\n          `az account set` — the user is already signed in to the right\n          identity, so re-auth would be pointless friction. The\n          **prompt** in step (b) is still mandatory; only the underlying\n          `az login` invocation is conditional on the existing session.\n          If `az login` does run and opens the browser, wait for it to\n          finish (the terminal will return). If it falls back to device\n          code, the user types it directly into the browser — never\n          relay codes through `vscode_askQuestions`.\n       e. Verify with `az account show --query \"{sub:id, tenant:tenantId}\"\n          -o json`; both values must match the user's choices. If not,\n          stop and report — do not proceed to MCP restart with a\n          mismatched session.\n       f. Validate the resource token actually mints:\n          ```pwsh\n          az account get-access-token --resource https:\u002F\u002Fdiscovery.azure.com --query \"{tenant:tenant, expiresOn:expiresOn}\" -o json\n          ```\n          A success here means the MCP's `command`-input will resolve. A\n          failure (e.g. `AADSTS500011` \"resource principal not found\")\n          means the tenant has never consented to the Discovery first-party\n          app — surface that exact error and stop; admin consent is\n          required and cannot be granted from this skill.\n\n       Never ask the user for tokens, passwords, or device codes through\n       `vscode_askQuestions` — answers to that tool go through the model.\n       Tenant and subscription **IDs** are not secrets and are fine to\n       collect via the picker.\n   3. **None of the above worked.** Stop the workflow and report exactly\n      which probe failed (network error, sign-in declined, etc.) plus the\n      manual install instructions:\n      *Open Command Palette → \"MCP: Add Server\" → \"HTTP\" → URL\n      `https:\u002F\u002Fmcp.discovery.azure.com\u002Fmcp` → name `microsoft-discovery`*.\n      **Never** spoof a session or fabricate registry data.\n\n   Do **not** prompt for credentials, tokens, or secrets via\n   `vscode_askQuestions` at any point in the install — the MCP server's\n   own auth handshake (browser \u002F Entra) is the only safe channel.\n\n2. **Probe authentication via the proxy** (NOT via VS Code's MCP\n   runtime). With `az` already pointed at the correct\n   tenant\u002Fsubscription (Step 7a.2.5), call any cheap MCP tool through\n   `Invoke-DiscoveryMcp`:\n\n   ```pwsh\n     . \"$workspaceRoot\\.vscode\\Invoke-DiscoveryMcp.ps1\"\n   $r = Invoke-DiscoveryMcp -ProxyPath \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\" -Calls @(\n       @{ name='ListWorkspaces'; args=@{ subscriptionId=$discoverySubscriptionId } }\n   )\n   ```\n\n   - A JSON payload with `value[]` confirms the session is good.\n   - On `401 InvalidAuthenticationTokenTenant`, the `az` CLI is signed\n     into the wrong tenant. Re-run Step 7a.2.5 to pick the correct\n     tenant\u002Fsubscription. The proxy refreshes its token on the next\n     call automatically — no server restart needed.\n   - On `AADSTS500011` (resource principal not found), the tenant has\n     never consented to the Discovery first-party app. Surface the\n     error and stop — admin consent required.\n\n3. **Run interactive sign-in if needed.** If the probe in (2) fails\n   with `401`, re-run Step 7a.2.5 (re-prompts for tenant + subscription\n   and re-runs `az login --tenant \u003Cid>`). Do **not** prompt for\n   credentials, tokens, or device codes via `vscode_askQuestions` — the\n   user types them directly into the browser or terminal that `az login`\n   opens.\n\n4. **List workspaces** the signed-in user can access in\n   `$discoverySubscriptionId`:\n   - **Always via the proxy** — call `ListWorkspaces` through\n     `Invoke-DiscoveryMcp` (see step 2 above for the exact pattern).\n     The response is `{ \"value\": [ {name, id, location, …}, … ] }`.\n     Do **not** wait for VS Code to surface `mcp_microsoft-dis_ListWorkspaces`\n     as a deferred tool — it often never appears.\n     not already loaded.\n   - Fallback: `az resource list --subscription $discoverySubscriptionId\n     --resource-type Microsoft.Discovery\u002Fworkspaces --output json`.\n   - Filter out workspaces the user lacks `Contributor` (or higher) role on\n     — they can't deploy into those. If the filter would remove every entry,\n     show the full list with a warning instead.\n\n5. **ALWAYS ask the user to pick a workspace** with `vscode_askQuestions`\n   (single-select, required). The option label is the workspace display\n   name; the `description` field includes the workspace ID and region so the\n   user can disambiguate similarly-named workspaces. If\n   `\u002Fmemories\u002Frepo\u002F` has a previously-used workspace **in the chosen\n   subscription**, mark that option as `recommended: true` — but the\n   prompt is mandatory on every Discovery run. Never auto-select a\n   workspace from saved memory, environment variables, or a single-entry\n   list; always surface the picker so the user explicitly confirms the\n   destination.\n\n6. **List projects** inside the chosen workspace:\n   - **Always via the proxy**: call `ListProjects` through\n     `Invoke-DiscoveryMcp` with\n     `subscriptionId=$discoverySubscriptionId`,\n     `resourceGroupName=\u003Crg-of-chosen-workspace>`, and\n     `workspaceName=\u003Cchosen-workspace-name>`. Do not depend on\n     `mcp_microsoft-dis_ListProjects` being surfaced as a deferred tool.\n   - Fallback: `az rest --method get --uri\n     \"https:\u002F\u002Fmanagement.azure.com\u002Fsubscriptions\u002F$discoverySubscriptionId\u002FresourceGroups\u002F\u003Crg>\u002Fproviders\u002FMicrosoft.Discovery\u002Fworkspaces\u002F\u003Cws>\u002Fprojects?api-version=2026-06-01\"`.\n   - Show project display name + ID + the underlying Foundry project URI in\n     the option `description`.\n\n7. **ALWAYS ask the user to pick a project** with `vscode_askQuestions`\n   (single-select, required). Persist the result as `$discoveryWorkspace`\n   and `$discoveryProject` (full ID, not just display name). Same rule\n   as step 5: a previously-used project may be marked\n   `recommended: true`, but the prompt is mandatory on every Discovery\n   run — never auto-select.\n\n8. **List existing agents in the chosen project** and show them to the user\n   verbatim before proceeding:\n   - Prefer `agents action=list` filtered to the registry that corresponds\n     to `$discoveryProject`. Call `agents action=registry.list` first to\n     find the matching registry name.\n   - Fallback: `discovery agents list --project \u003Cproject-id>`.\n   - Print a table with: agent name, version (or last-updated timestamp),\n     tool count, and whether the name collides with any folder in\n     `$selected`. Highlight collisions clearly — they will trigger the\n     \"update vs create\" question in Step 7e.\n\n9. **Confirm before continuing.** Ask one more `vscode_askQuestions`:\n   *\"Proceed to deploy N agents to project `\u003Cproject-name>`?\"* with options\n   `Yes` (default) and `Cancel`. On `Cancel`, stop the workflow cleanly — do\n   not touch ACR or Foundry.\n\nPersist `$discoveryWorkspace`, `$discoveryProject`, `$discoverySubscriptionId`,\nand `$discoveryRg` for use in Step 7c (tool pre-flight against the\nworkspace's RG) and Step 7e (agent provisioning via `UpsertAgent`).\n\n#### 7b. Probe MCP availability for Azure\n\nDiscovery MCP — always available in a Discovery workspace as the `agents` and\n`tools` tools:\n\n| Capability | MCP call |\n|---|---|\n| List registered agents | `agents` with `action: list` |\n| Create \u002F update an agent | `agents` with `action: create` (or `update`) |\n| List available tool grants | `agents` with `action: tools.list` |\n| Assign tools to an agent | `agents` with `action: assign-tools` |\n| List \u002F refresh registries | `agents` with `action: registry.list` \u002F `registry.refresh` |\n\nAzure MCP — **probe first**, do not assume it is installed. Call:\n\n```\ntools action=search query='azure'\ntools action=search query='azure container registry'\ntools action=search query='azure subscription'\n```\n\nIf a callable Azure plugin is returned (`status: 'callable'`), use its tools\n(e.g. ACR build\u002Fpush, subscription select, role assignment) instead of `az`\nCLI. If only `metadata_only` plugins are returned, ask the user **once**\nwhether to install one of them; otherwise fall back to the `az` and `docker`\nCLIs (documented inline in Step 7d).\n\nDo **not** silently install Azure MCP plugins — installation makes them\navailable globally and the user should opt in.\n\n#### 7c. Pre-flight: detect pre-existing tool ARM resources\n\n**Skip this entire step for toolless agents** (`LocalToDiscovery` agents\nwith no `discovery_catalog\u002F\u003Cname>\u002F` folder, or any agent that declares no\n`tools\u002F\u003CTool>\u002F` subdirectories). Set `$skipImageBuild = $true`, leave\n`$preExistingToolIds` \u002F `$builtToolIds` empty, and jump straight to Step 7e.\nThere is nothing to pre-flight, build, or bind.\n\n**Many catalog agents are already partially deployed in shared Discovery\nworkspaces.** Before asking the user for ACR\u002FRG\u002Fregion (Step 7c.2) and\nbefore building any images (Step 7d.1), call\n`GetDiscoveryTool` (called via `Invoke-DiscoveryMcp`) once per tool declared under\n`discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002F` against the **workspace's resource\ngroup** (`$discoveryRg` from Step 7a — *not* the deployment ACR's RG).\n\n```\nfor $tool in (Get-ChildItem discovery_catalog\u002F\u003Cname>\u002Ftools\u002F -Directory):\n    GetDiscoveryTool subscriptionId=$discoverySubscriptionId\n                     resourceGroupName=$discoveryRg\n                     toolName=$tool.Name\n```\n\nOutcomes:\n\n| Result                                        | Interpretation                                                   | Action                                                                                                                |\n|-----------------------------------------------|------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|\n| `200` with `provisioningState=Succeeded`      | Tool already registered as ARM resource; image already pushed     | Capture the `.id` (ARM resource ID) and `.properties.definitionContent.infra[].image.acr`. **Skip build & push for this tool.** |\n| `200` with `provisioningState=Failed`         | Stale half-deployed resource                                      | Surface to user; ask whether to delete + recreate (default: leave alone, abort agent)                                |\n| `404` not found                               | Tool not registered yet                                           | Build + push + register (Step 7d). Need ACR + RG (Step 7c.2)                                                          |\n| `403` \u002F token expired                         | MCP auth issue                                                    | Re-run Step 7a.2.6 mint\u002Frestart                                                                                       |\n\nSet `$skipImageBuild = $true` only when **every** tool the agent declares\nreturns `Succeeded`. Otherwise `$skipImageBuild = $false` and you must\ncollect ACR config in Step 7c.2.\n\n**Why this matters.** The Microsoft Discovery catalog ships agents whose\ntool images are already published to a shared registry like `mdqacr`. In\nthat case there is nothing to build — the entire Docker\u002FACR\u002FRBAC pipeline\nis a no-op. Detecting this up front avoids prompting the user for an ACR\nthey don't own and avoids ~5–15 min of unnecessary build time.\n\n**A previously-deployed tool ARM may have been deleted since your last run**\n(shared dev workspaces get cleaned up), so a `404` here does **not** mean the\nimage is gone. Before falling into the full ACR-build prompt flow (Step 7c.2 \u002F\n7d), check whether the image already exists in the expected ACR\n(`az acr repository show-tags --name \u003Cacr> --repository \u003Ctool>`). If the image\nis present, **skip the build** and go straight to re-registering the tool ARM\nfrom the local `tool.yaml` (Step 7d.4: PUT `definitionContent` as an object,\n`language: python3`), poll `GetDiscoveryTool` to `Succeeded`, ensure AcrPull\n(idempotent), then bind it in Step 7e. Only build when the image is genuinely\nabsent from the ACR.\n\nAlso list existing agents in the target project so the user can see whether\nthe agent name is already taken — this is the data behind the\n\"update vs create\" question in Step 7e:\n\n```\nListAgents subscriptionId=$discoverySubscriptionId\n           resourceGroupName=$discoveryRg\n           workspaceName=$discoveryWorkspace\n           projectName=$discoveryProject\n```\n\nPersist `$preExistingToolIds` (map of `toolName → ARM resource ID`),\n`$skipImageBuild`, and `$existingAgentNames` for downstream steps.\n\n#### 7c.2. Collect Azure deployment configuration (only if $skipImageBuild == $false)\n\nSkip this entire sub-step when `$skipImageBuild == $true` — there's no\nimage to push, no ACR to choose, no RG to provision. Jump straight to Step\n7d.\n\nOtherwise ask the user **once** (single `vscode_askQuestions` call with\nmultiple questions) for the Azure targets. Pre-fill defaults from the\nenvironment when possible (`az account show`, `$env:AZURE_SUBSCRIPTION_ID`,\nprior session memory under `\u002Fmemories\u002Frepo\u002F`).\n\nThe **Foundry project name** is already known from Step 7a\n(`$discoveryProject`); use it as the default for the Foundry project field\nand allow the user to override it only if they explicitly need a different\ntarget.\n\nRequired values:\n\n- **Azure subscription** (id or name) — default `$discoverySubscriptionId`\n- **Resource group** (existing or to-create) — default `$discoveryRg`\n- **Azure Container Registry** name (the image registry — must be reachable\n  from the Foundry project that will host the agent). Pre-populate by\n  calling `az acr list --subscription \u003Csub> -o json` and surfacing\n  registries in the same region as `$discoveryWorkspace.location` first.\n- **Foundry project** name (defaults to `$discoveryProject`)\n- **Region** (only if the resource group or ACR needs to be created) —\n  default `$discoveryWorkspace.location`\n\nNever prompt for secrets via `vscode_askQuestions` (it ships answers through\nthe model). If a token or key is needed, instruct the user to type it\ndirectly into the terminal.\n\n#### 7d. Build + push tool images (only if $skipImageBuild == $false)\n\nIf every tool in the agent already exists as an ARM resource (Step 7c set\n`$skipImageBuild = $true`), skip this entire step and jump to Step 7e.\n\n**7d.LTD — pushing a locally-built image (`$deployTarget == 'LocalToDiscovery'`).**\nWhen promoting from the local app, the tool image may already be built locally\n(via Podman\u002FDocker from a prior local invocation). Two acceptable paths, in\norder of preference:\n\n1. **Cloud build from the local Dockerfile (preferred, reproducible).** Run\n   `az acr build` exactly as in the numbered steps below, using the local\n   `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002F` build context. This ignores any\n   locally-built image and rebuilds from the local Dockerfile in ACR — the\n   image content is identical and no local Docker\u002FPodman daemon is required.\n2. **Push the existing local image** (when the user wants the exact local build,\n   or `az acr build` is unavailable). Tag and push the locally-built image\n   directly, matching the local bootstrap tag convention `\u003Ctool>:latest`:\n   ```pwsh\n   az acr login --name \u003Cacr-name>\n   docker tag \u003Ctool>:latest \u003Cacr>.azurecr.io\u002F\u003Ctool>:latest\n   docker push \u003Cacr>.azurecr.io\u002F\u003Ctool>:latest\n   # Podman equivalent: podman tag \u003Ctool>:latest \u003Cacr>.azurecr.io\u002F\u003Ctool>:latest; podman push \u003Cacr>.azurecr.io\u002F\u003Ctool>:latest\n   ```\n   If the expected local image is missing, fall back to path 1.\n\nEither path is followed by the same manifest rewrite, ARM registration, and\nAcrPull grant (steps 3–6 below). **Never** push to any registry other than the\nACR chosen in Step 7c.2.\n\n**Do not** use `runSubagent agentName='microsoft-foundry'`. That skill is\nnot registered as a subagent — the call fails with \"Requested agent\n'microsoft-foundry' not found\". The skill is azd-oriented and assumes a\n`.foundry\u002F` overlay that catalog agents don't have. Execute the build\npipeline directly:\n\nFor each `tools\u002F\u003CTool>\u002F` subfolder under `discovery_catalog\u002F\u003Cname>\u002F` that\nhas a `Dockerfile`:\n\n1. **Build + push in one shot** (preferred — uses ACR cloud build, no\n   local Docker required):\n   ```pwsh\n   az acr build --registry \u003Cacr-name> `\n                --image \u003Ctool>:latest `\n                --image \u003Ctool>:sha-\u003Cgitshort> `\n                discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002F\n   ```\n\n   **Windows console crash — build still succeeds (observed).** On Windows,\n   `az acr build` streams the remote build log through `colorama` and often\n   dies client-side with\n   `UnicodeEncodeError: 'charmap' codec can't encode characters ...`\n   (cp1252). **This is a log-streaming failure only — the server-side ACR\n   build keeps running and usually completes.** Do NOT treat the traceback\n   as a build failure and do NOT immediately rebuild. Instead:\n   - Set `$env:PYTHONIOENCODING = 'utf-8'` (and, when practical,\n     `[Console]::OutputEncoding = [System.Text.Encoding]::UTF8`) *before*\n     invoking `az acr build` to avoid the crash in the first place.\n   - If it already crashed, capture the queued run id from the log\n     (`Queued a build with ID: \u003Cid>`) and poll for completion instead of\n     rebuilding:\n     ```pwsh\n     $env:PYTHONIOENCODING = 'utf-8'\n     do {\n       Start-Sleep -Seconds 20\n       $run = az acr task list-runs --registry \u003Cacr-name> --top 10 -o json |\n              ConvertFrom-Json | Where-Object { $_.runId -eq '\u003Cid>' }\n       $status = $run.status\n     } while ($status -eq 'Running')\n     # $status is 'Succeeded' \u002F 'Failed'\n     ```\n     Note: `az acr task list-runs --run-id \u003Cid>` can return empty; filter the\n     `--top N` list client-side by `runId` instead.\n   - Confirm the tags landed: `az acr repository show-tags --name \u003Cacr-name>\n     --repository \u003Ctool> -o tsv`.\n\n2. **Fallback** (only when `az acr build` is unavailable or fails with a\n   clear \"use local build\" message):\n   ```pwsh\n   az acr login --name \u003Cacr-name>\n   docker build -t \u003Cacr>.azurecr.io\u002F\u003Ctool>:latest discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002F\n   docker push \u003Cacr>.azurecr.io\u002F\u003Ctool>:latest\n   ```\n\n3. **Rewrite the manifest** so future re-deployments are reproducible:\n   - `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002Ftool.yaml` → set\n     `infra[].image.acr` to the pushed reference (e.g.\n     `mdqacr.azurecr.io\u002F\u003Ctool>:latest`). Replace any `{name}` placeholder\n     with the actual ACR name.\n   - **Normalize `code_environments[].language` to `python3` (not `python`).**\n     The tool ARM PUT accepts `python`, but the Foundry agent-binding step\n     in 7e then fails with a bare `provisioningState=Failed` (no error text\n     in `GetAgent`). Every working catalog container tool (e.g. `ambertools`,\n     `crest`) uses `python3`; Foundry derives the generated function name\n     `\u003Ctool>-Executepython3Code` from it. If the local `tool.yaml` says\n     `language: python`, change it to `python3` here before registering.\n   - Preserve all other fields and YAML formatting.\n\n4. **Register the tool as a Discovery ARM resource.** The Discovery MCP\n   does not surface a `CreateDiscoveryTool` tool — register via ARM API\n   directly.\n\n   **CRITICAL: `properties.definitionContent` MUST be a JSON _object_, not a\n   YAML\u002FJSON _string_.** Passing the raw `tool.yaml` text\n   (`Get-Content ... -Raw`) fails with\n   `HttpRequestPayloadAPISpecValidationFailed` \u002F\n   `InvalidType: Expected type object but found type string. Paths in\n   payload: '$.properties.definitionContent'`. Convert the YAML into an\n   object graph first. If `powershell-yaml` is unavailable (common), build\n   the object explicitly with `[ordered]@{}` mirroring `tool.yaml`, then\n   `ConvertTo-Json` the whole payload. Also write the body to a temp file\n   and pass it with `--body \"@\u003Cfile>\"` (avoids terminal quoting\u002Fecho\n   truncation), and set `$env:PYTHONIOENCODING = 'utf-8'`.\n   ```pwsh\n   # $def mirrors tool.yaml as an object (name, description, version,\n   # category, license, infra[], code_environments[]). Example shape:\n   $def = [ordered]@{\n     name        = '\u003Ctool>'\n     description = '\u003Ctool description>'\n     version     = '\u003Ctool-version-from-tool.yaml>'\n     category    = 'Scientific Computing'\n     license     = 'MIT'\n     infra       = @(\n       [ordered]@{\n         name       = 'worker'\n         infra_type = 'container'\n         image      = [ordered]@{ acr = '\u003Cacr>.azurecr.io\u002F\u003Ctool>:latest' }\n         compute    = [ordered]@{ \u003Cmin_resources\u002Fmax_resources\u002F...> }\n       }\n     )\n     code_environments = @(\n       [ordered]@{ language = 'python3'; command = 'python \"\u002F{{scriptName}}\"'; description = '...'; infra_node = 'worker' }\n     )\n   }\n   $payload = [ordered]@{\n     location   = '\u003Cregion>'\n     tags       = [ordered]@{ category = 'Scientific Computing' }\n     properties = [ordered]@{ version = '\u003Ctool-version>'; definitionContent = $def }\n   }\n   $bodyFile = Join-Path $env:TEMP 'dc-tool-put.json'\n   $payload | ConvertTo-Json -Depth 30 | Set-Content -Path $bodyFile -Encoding UTF8\n   $env:PYTHONIOENCODING = 'utf-8'\n   az rest --method PUT `\n     --uri \"https:\u002F\u002Fmanagement.azure.com\u002Fsubscriptions\u002F\u003Csub>\u002FresourceGroups\u002F\u003Crg>\u002Fproviders\u002FMicrosoft.Discovery\u002Ftools\u002F\u003Ctool>?api-version=2026-06-01\" `\n     --headers \"Content-Type=application\u002Fjson\" `\n     --body \"@$bodyFile\"\n   ```\n   To learn the exact object schema for a tool type, call `GetDiscoveryTool`\n   on any existing working tool in the same workspace and mirror its\n   `properties.definitionContent`.\n   Poll provisioning state via `GetDiscoveryTool` until `Succeeded`.\n\n5. **Grant AcrPull** to the workspace's user-assigned managed identity (the\n   `workspaceIdentity.principalId` from `GetWorkspace`) on the ACR:\n   ```pwsh\n   az role assignment create --assignee \u003CprincipalId> `\n                             --role AcrPull `\n                             --scope \u002Fsubscriptions\u002F\u003Csub>\u002FresourceGroups\u002F\u003Cacr-rg>\u002Fproviders\u002FMicrosoft.ContainerRegistry\u002Fregistries\u002F\u003Cacr>\n   ```\n   Treat \"already exists\" as success.\n\n6. Record `$builtToolIds` (map `toolName → ARM resource ID`) and the image\n   digests for the Step 8 summary.\n\n#### 7e. Create the agent in the Discovery project via UpsertAgent\n\nThis is the single mechanism that creates the agent in the Discovery\nproject — there is no separate \"Foundry hosted prompt agent create\" step.\nThe Discovery `UpsertAgent` MCP tool does both Discovery registration and\nthe Foundry-side wiring.\n\n1. **Extract the instructions block from the\n   `.github\u002Fagents\u002F\u003Cname>.agent.md` companion.** The Copilot companion's\n   markdown body is the **source of truth for the prompt**, for **both**\n   tool-bearing and toolless agents. Source `instructions` from that file\n   via `Get-AgentMdInstructions` (defined in Step 4c.LTD), which strips the\n   YAML frontmatter and any auto-generated container-bootstrap preamble.\n   Promoting the companion body keeps the local Copilot subagent and the\n   cloud Discovery agent in lockstep — whatever the user tuned locally is\n   what gets deployed.\n\n   ```pwsh\n   # Same helper defined in Step 4c.LTD.\n   $companion    = \".github\u002Fagents\u002F$name.agent.md\"\n   $instructions = Get-AgentMdInstructions $companion\n\n   # Tool-bearing promote: the local companion may still reference the tool as\n   # a LOCAL Podman\u002FDocker image (build context, image tag, image inspect).\n   # The cloud has no local runtime — rewrite those references to point at the\n   # deployed Discovery tool(s) instead. Requires the tool ARM + its ACR image\n   # to already exist (Step 7c pre-flight \u002F Step 7d build+push).\n   if ($agentHasCatalogFolder[$name]) {\n     $toolNames = @(Get-ChildItem \"discovery_catalog\u002F$name\u002Ftools\" -Directory -ErrorAction SilentlyContinue |\n                    ForEach-Object { $_.Name })\n     if ($toolNames.Count -gt 0) {\n       $instructions = Convert-PromoteInstructionsForTool -Instructions $instructions -ToolNames $toolNames\n     }\n   }\n\n   # SANITY-CHECK the extracted body length BEFORE UpsertAgent. A tool-bearing\n   # or otherwise real prompt should be thousands of chars. A result of only a\n   # few hundred chars almost always means the CRLF regex bug (a bare\n   # `\\n---\\n` that failed to match a CRLF companion) deleted the body. Abort\n   # and fix the extraction rather than deploying a stub.\n   if ($instructions.Length -lt 500) {\n     throw \"Extracted instructions for '$name' are only $($instructions.Length) chars — likely the CRLF regex bug. Fix Get-AgentMdInstructions \u002F Convert-PromoteInstructionsForTool to use '\\r?\\n---\\r?\\n' and re-extract before UpsertAgent.\"\n   }\n\n   # name + description ALSO come from the companion frontmatter (same source\n   # of truth as instructions), NOT from discovery_catalog\u002F\u003Cname>\u002Fagent.yaml.\n   $displayName = Get-AgentMdFrontmatterValue $companion 'name'\n   if ([string]::IsNullOrWhiteSpace($displayName)) { $displayName = $name }\n   $description = Get-AgentMdFrontmatterValue $companion 'description'\n   if ([string]::IsNullOrWhiteSpace($description) -and (Test-Path \"discovery_catalog\u002F$name\u002Fagent.yaml\")) {\n     # Fallback only if the companion has no description.\n     $description = (Get-Content \"discovery_catalog\u002F$name\u002Fagent.yaml\" -Raw) # then parse agent.yaml#description\n   }\n   # Foundry caps description at 512 chars — truncate before UpsertAgent.\n   if ($description.Length -gt 512) { $description = $description.Substring(0, 512).TrimEnd() }\n   ```\n\n   For a **tool-bearing** promote, the cloud instructions **must not**\n   reference any local container image. The `Convert-PromoteInstructionsForTool`\n   helper (Step 4c.LTD) removes the auto-generated bootstrap preamble, scrubs\n   any residual `podman`\u002F`docker` `build`\u002F`pull`\u002F`push`\u002F`image inspect` lines\n   and `discovery_catalog\u002F...\u002Ftools\u002F...` build-context references, and appends\n   a short \"Tool execution (Microsoft Discovery)\" note pointing at the deployed\n   Discovery tool(s) by name. **Before** calling `UpsertAgent`, confirm the\n   tool is actually usable in the cloud: every tool the agent declares must\n   have returned `provisioningState=Succeeded` from the Step 7c\n   `GetDiscoveryTool` pre-flight (or been built + pushed + registered in Step\n   7d), with its container image present in the workspace's ACR. Do not deploy\n   a tool-bearing agent whose Discovery tool \u002F ACR image is missing — bind the\n   tool first, then promote.\n\n   Do **NOT** read `instructions` **or `description`** from\n   `discovery_catalog\u002F\u003Cname>\u002Fagent.yaml` — the `.agent.md` companion\n   supersedes both. (`agent.yaml` is still used only for the tool subtree\n   and `metadata.yaml#associated_tools`.)\n\n   Field sourcing summary:\n\n   - **`instructions`** — always the `.github\u002Fagents\u002F\u003Cname>.agent.md`\n     companion body via `Get-AgentMdInstructions` (both buckets). For a\n     **tool-bearing** agent, additionally pass the result through\n     `Convert-PromoteInstructionsForTool` so the cloud prompt references the\n     deployed Discovery tool(s) instead of any local Podman\u002FDocker image.\n   - **`name` \u002F `description`** — for **both** buckets, read from the\n     `.github\u002Fagents\u002F\u003Cname>.agent.md` companion's YAML frontmatter via\n     `Get-AgentMdFrontmatterValue` (`name` \u002F `description`), **not** from\n     `discovery_catalog\u002F\u003Cname>\u002Fagent.yaml`. This keeps the deployed\n     Discovery agent's display name and description in lockstep with the\n     locally-tuned companion. Apply the 512-char truncation to\n     `description` (see Step 7e.4). If the companion frontmatter has no\n     `description`, fall back to `agent.yaml#description` (then still\n     truncate).\n   - **`toolIds`** — the pre-existing \u002F built tool ARM IDs for a\n     tool-bearing agent; empty for a toolless agent.\n\n   **Fallback (upstream `Discovery` target only).** The upstream-sourced\n   `Discovery` path does not generate a `.github\u002Fagents\u002F\u003Cname>.agent.md`\n   companion (Step 6 runs for `Local` only). If the companion file does\n   **not** exist, fall back to reading the YAML block scalar\n   (`instructions: |-`) from `discovery_catalog\u002F\u003Cname>\u002Fagent.yaml`: read the\n   full file, slice the lines between `instructions: |-` and the next\n   top-level key (e.g. `discoveryExtensions:`), and strip the 2-space\n   indent. PowerShell's `ConvertFrom-Yaml` (PSYaml module) is fine if\n   available; otherwise the line-slice + indent-strip approach works:\n   ```pwsh\n   $companion = \".github\u002Fagents\u002F$name.agent.md\"\n   if (Test-Path $companion) {\n     $instructions = Get-AgentMdInstructions $companion\n   } else {\n     $lines = Get-Content discovery_catalog\u002F$name\u002Fagent.yaml\n     # find indices of 'instructions: |-' and the next top-level key\n     $body = $lines[$start..$end] | ForEach-Object {\n         if ($_.Length -ge 2 -and $_.Substring(0,2) -eq '  ') { $_.Substring(2) } else { $_ }\n     }\n     $instructions = $body -join \"`n\"\n   }\n   ```\n\n   **Preserve all `{{templateVariables}}`** (`{{workflowContext}}`,\n   `{{agentTeam}}`, `{{nodePoolContext}}`, `{{dataHandlingContext}}`,\n   tool-id placeholders like `{{alphafoldToolId}}`, model placeholder\n   `{{CHAT-MODEL}}`). These are filled in by the Discovery engine at\n   invocation time.\n\n2. **Pick a chat model deployment.** Call `ListChatModelDeployments`\n   (via `Invoke-DiscoveryMcp`) against the workspace and apply this\n   decision tree — **prefer auto-pick over asking**, every prompt costs\n   a round-trip:\n   - Filter to deployments with `provisioningState == 'Succeeded'`\n     whose `modelName` starts with `gpt-5` (preferred) or equals `gpt-4o`\n     (fallback). Sort by `systemData.lastModifiedAt` descending.\n   - **Auto-pick the top candidate without asking** when:\n     - The filtered list has exactly one entry, OR\n     - The top candidate's `lastModifiedAt` is strictly newer than every\n       other candidate's. (No tie at the top.)\n   - **Only ask the user via `vscode_askQuestions`** when there are 2+\n     candidates with the same most-recent `lastModifiedAt`, OR when no\n     deployment matches the `gpt-5* \u002F gpt-4o` filter (rare — fall back\n     to all `Succeeded` deployments and ask).\n   - Announce the auto-picked choice in the Step 8 summary so the user\n     can see what was selected.\n\n3. **Assemble `toolIds`.** Merge `$preExistingToolIds` (Step 7c) with\n   `$builtToolIds` (Step 7d) into a comma-separated list of ARM resource\n   IDs. For **toolless** agents this is empty — pass an empty string (or\n   omit `toolIds`); do not fabricate a tool binding.\n\n4. **Call `UpsertAgent`** (via `Invoke-DiscoveryMcp`). Required values:\n   - `subscriptionId`, `resourceGroupName`, `workspaceName`, `projectName`\n   - `agentName` (= agent folder name, kebab-case)\n   - `kind`: `prompt` (default for catalog agents — they're all prompt\n     agents) or `workflow` if `agent.yaml#kind == 'workflow'`\n   - `description`: the companion frontmatter `description` (via\n     `Get-AgentMdFrontmatterValue \".github\u002Fagents\u002F$name.agent.md\" 'description'`),\n     falling back to `agent.yaml#description` only if the companion has none.\n     **Truncate to 512 chars max.** Foundry caps the agent `description` at\n     512 characters; a longer value causes a fast bare\n     `provisioningState=Failed` (with `foundryDetails=null` and no error text\n     in `GetAgent`). This is NOT a tool-binding failure. Trim to \u003C=512 before\n     calling `UpsertAgent` (e.g. drop a trailing scope sentence).\n     `GetAgentOperation(operationId)` returns the real error\n     (`maxLength: Value should be at most 512 characters` on `\u002Fdescription`)\n     if you need to confirm.\n   - `instructions`: the extracted string from step 1\n   - `model`: the chat model deployment name from step 2\n   - `temperature`: `agent.yaml#model.options.temperature` (default 0)\n   - `topP`: `agent.yaml#model.options.topP` (default 0)\n   - `toolIds`: comma-separated ARM IDs from step 3\n   - `humanInTheLoop`: from `agent.yaml#discoveryExtensions.humanInTheLoop`\n     (default `Disabled`)\n   - `discoveryExtensions`: JSON string of any extensions\n     (`{\"disableDataHandlingTools\": false}` is a safe default)\n\n5. **Poll `GetAgent` for `provisioningState=Succeeded`.** `UpsertAgent`\n   returns `{id, status, agentName}` where `id` is an operationId. Prefer\n   `GetAgent` provisioningState polling for the happy path (the\n   `GetAgentOperation` MCP tool has historically been flaky, though it can\n   still return the real error — see the recovery notes below). Use the\n   extracted `Wait-DiscoveryAgentReady` helper, which polls `GetAgent` and\n   watches `provisioningState`:\n\n   ```pwsh\n   Wait-DiscoveryAgentReady -ProxyPath $proxy `\n       -SubscriptionId $sub -ResourceGroupName $rg `\n       -WorkspaceName $ws -ProjectName $proj `\n       -AgentName $agentName -TimeoutSeconds 300\n   ```\n\n   States to handle:\n   - `Creating` \u002F `Updating` \u002F `Accepted` → helper keeps polling.\n   - `Succeeded` → helper returns the parsed agent object; record\n     `$createdAgentId` for Step 8 summary.\n   - `Failed` → helper throws with the full payload; surface verbatim\n     and do not retry blindly.\n\n   **When a tool is bound and `GetAgent` reports `Failed` fast (~5–10 s)\n   with `foundryDetails=null` and no error text**, the failure is almost\n   always the tool binding, not the prompt. Diagnose and recover as follows\n   (this exact sequence recovered a real run):\n   1. **Confirm it's the tool, not the instructions.** Re-`UpsertAgent`\n      once *without* `toolIds` (same model + instructions). If that\n      Succeeds, the prompt is fine and the tool binding is the culprit.\n   2. **Check the tool's `language`.** Call `GetDiscoveryTool` and compare\n      `code_environments[].language` against a working container tool in the\n      same workspace. If it's `python` (or anything other than `python3`),\n      re-register the tool ARM with `language: python3` (Step 7d.3–7d.4) and\n      wait for `GetDiscoveryTool` to report `Succeeded` again.\n   3. **Allow propagation before rebinding.** After the tool ARM flips to\n      `Succeeded`, the Foundry-side tool definition can still be stale for\n      ~30–60 s. An immediate `UpsertAgent` with the tool may still `Fail`.\n      Wait ~30–60 s, then re-`UpsertAgent` with `toolIds` and re-poll. A\n      second attempt typically Succeeds.\n   4. **Get the real error when you need it.** Contrary to older guidance,\n      `GetAgentOperation` *can* return the actual result\u002Ferror. After an\n      `UpsertAgent`, capture the returned `id` (operationId) and call\n      `GetAgentOperation` with `operationId=\u003Cid>` (plus the sub\u002Frg\u002Fws\u002Fproj\u002F\n      agentName args). It returns `{status, error, result}` — use `error`\n      for the failure detail and `result` for the provisioned agent. Still\n      prefer `Wait-DiscoveryAgentReady` (GetAgent polling) for the happy\n      path; reach for `GetAgentOperation` only when GetAgent gives a bare\n      `Failed`.\n\n   Typical provisioning takes 10–60 s. If `Wait-DiscoveryAgentReady`\n   times out at 300 s, the agent almost certainly did succeed — verify\n   with one `ListAgents` call before declaring failure.\n\n6. **Verify** with `ListAgents` (or `GetAgent`) to confirm the agent\n   appears in the project with `provisioningState=Succeeded` and the\n   expected `toolIds`.\n\n#### 7f. (Optional) Local Discovery agent runtime registration\n\nThe cloud-side agent created in Step 7e is **fully usable** via the\nDiscovery web studio and the Discovery MCP `CreateResponse` tool (called via `Invoke-DiscoveryMcp`) without this\nstep. Only proceed if the user explicitly wants the agent to appear in the\nlocal Discovery extension's agent picker (different scope from the cloud\nproject).\n\nIf proceeding:\n\n1. Call `agents` with `action: tools.list` to discover which catalog tools\n   match the agent's `discoveryExtensions.tools` references.\n2. Call `agents` with `action: create`, passing:\n   - `name`: the agent folder name (kebab-case)\n   - `description`: from `agent.yaml#description`\n   - `systemPrompt`: from `agent.yaml#instructions`\n   - `toolGrants`: declarative grants assembled from step 1\n3. Optionally call `agents` with `action: registry.refresh` so the new entry\n   appears in `agents list` immediately.\n\n**Do not** call `agents` with `action: run.start` from this skill —\nregistration is the goal; running the agent is a separate user action.\n\nAsk the user once (default: skip) before performing this step.\n\n#### 7g. Rules and guard-rails\n\n- **Local files are the source of truth.** For a **tool-bearing** agent,\n  never deploy one whose `discovery_catalog\u002F\u003Cname>\u002F` folder is missing or\n  only partially copied. A **toolless** promote agent legitimately has **no**\n  `discovery_catalog\u002F\u003Cname>\u002F` folder — its source of truth is the\n  `.github\u002Fagents\u002F\u003Cname>.agent.md` companion; require that companion to\n  exist and to yield a non-empty instructions body before deploying.\n- **Instructions AND description come from the\n  `.github\u002Fagents\u002F\u003Cname>.agent.md` companion.** For **both** buckets in the\n  `LocalToDiscovery` (promote) path, the prompt body deployed to Discovery is\n  the companion's markdown body (via `Get-AgentMdInstructions`) and the\n  agent `name` \u002F `description` are the companion frontmatter values (via\n  `Get-AgentMdFrontmatterValue`), never `discovery_catalog\u002F\u003Cname>\u002Fagent.yaml`.\n  Require a non-empty instructions body from the companion before deploying,\n  and truncate `description` to 512 chars (Foundry cap). Only the upstream\n  `Discovery` target (no companion) falls back to `agent.yaml#instructions` \u002F\n  `agent.yaml#description` (Step 7e.1).\n- **Cloud instructions for tool-bearing promotes must reference the\n  Discovery tool, not a local image.** When a promoted agent has a\n  `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002F` folder, pass its instructions\n  through `Convert-PromoteInstructionsForTool` (Step 4c.LTD) so the deployed\n  prompt drops every local Podman\u002FDocker build\u002Finspect\u002Fpull\u002Fpush reference\n  and points at the deployed Discovery tool(s) by name. The cloud has no\n  local container runtime — never deploy local image tags or build contexts.\n  Confirm each declared tool is `provisioningState=Succeeded` with its image\n  present in the workspace's ACR (Step 7c\u002F7d) **before** `UpsertAgent`.\n- **Tool detection is mandatory for tool-bearing agents.** Always run Step\n  7c `GetDiscoveryTool` pre-flight before asking ACR\u002FRG questions or\n  building images. If you prompt the user for an ACR that turns out to be\n  irrelevant because the tool already exists, you've wasted their time.\n  Toolless agents skip 7c\u002F7d entirely.\n- **Idempotency.** If an image tag already exists in ACR with the same\n  digest, do not rebuild. If a hosted agent with the same name already\n  exists in the Foundry project, prefer `update` over `create` and ask the\n  user once before overwriting.\n- **Never push to public registries.** Only the ACR named in step 7c.2 is a\n  valid push target. Reject any attempt to push to `docker.io`, `ghcr.io`,\n  or any other registry.\n- **No secrets through `vscode_askQuestions`.** If the Foundry deployment\n  requires a token the user has not already configured via `az login`, stop\n  and ask them to authenticate in the terminal.\n- **Bail on RBAC failures.** If the Foundry-managed identity cannot be\n  granted `AcrPull` on the registry, stop and report the missing\n  permission. Do not retry by escalating privileges.\n- **Always preserve `discovery_catalog\u002F\u003Cname>\u002F` after deployment.** Step 7\n  may rewrite `tool.yaml#infra.image.acr` in place — that's fine — but it\n  must not delete the local folder or its `tools\u002F` subtree.\n- **`microsoft-foundry` is a skill, not a subagent.** Do not call\n  `runSubagent agentName='microsoft-foundry'`. Execute the deploy\n  pipeline directly using Discovery MCP + `az` CLI as described above.\n- **Tool ARM `definitionContent` is an object, not a string.** Build it\n  with `[ordered]@{}` (or `ConvertFrom-Yaml`) and `ConvertTo-Json`; never\n  pass raw `tool.yaml` text. A string payload fails with\n  `InvalidType: Expected type object but found type string`.\n- **Container tools must declare `language: python3`.** `python` passes the\n  tool ARM PUT but breaks Foundry agent-binding (bare `Failed`, no error).\n- **Give tool changes ~30–60 s to propagate** before binding them to an\n  agent; an immediate `UpsertAgent` after a tool re-register can still\n  `Fail` even though the tool shows `Succeeded`.\n- **`az acr build` may crash the Windows console but still build.** Set\n  `$env:PYTHONIOENCODING='utf-8'` before calling it; if it crashed, poll\n  `az acr task list-runs` for the queued run id instead of rebuilding.\n\n### Step 8 — Cleanup and summary\n\n1. Remove the temp clone directory: `Remove-Item -Recurse -Force $work`.\n2. Print a structured summary to chat:\n   - **Selection mode** (All \u002F Specific \u002F By group) and **resolved selection** (N agents)\n   - **Deployment target** (Local \u002F Discovery \u002F LocalToDiscovery)\n   - **Catalog folders created** (N — `discovery_catalog\u002F\u003Cname>\u002F` did not exist locally before this run; list names)\n   - **Catalog folders refreshed** (N — `discovery_catalog\u002F\u003Cname>\u002F` was overwritten with the latest upstream copy; list names)\n   - **Catalog folders skipped** (N — name not present in `agents\u002F` upstream; e.g. removed from the catalog)\n   - **Companions already present** (N — `.github\u002Fagents\u002F\u003Cname>.agent.md` existed before this run; from `$existingLocalAgents`. These were re-generated, not skipped.)\n   - **Copilot agents generated** (N `.github\u002Fagents\u002F*.agent.md` files written — only when target == `Local`. Includes both fresh files and re-generations.)\n   - **Copilot agents skipped** (N, with reason — missing `agent.yaml`, empty `instructions`, etc.)\n  - **Container bootstrap preambles emitted** (N agents that had at least one `tools\u002F*\u002FDockerfile` upstream)\n   - **Pre-existing tool ARMs detected** (N, list `toolName → ARM ID` — image build skipped for these — only when target is a Discovery-class target)\n   - **Tool images built and pushed** (N images pushed to `\u003Cacr>.azurecr.io` — only when target == `Discovery` and at least one tool was missing)\n   - **Tool ARMs registered** (N new `Microsoft.Discovery\u002Ftools` resources created — only when target is a Discovery-class target)\n   - **Discovery agents provisioned** (N agents created\u002Fupdated in the Discovery project via `UpsertAgent` — only when target is a Discovery-class target)\n   - **Local Discovery runtime entries created** (N agents registered via `agents action=create` — only when user opted into Step 7f)\n   - **Deployment failures** (N, with the failing agent name and error message — never silently drop)\n\nWhen `$deployTarget == 'Local'`, this skill does NOT build or pull local\ncontainer images. Image builds are deferred to each generated `.agent.md` at\ninvocation time and are conditional on the image being absent.\n\nWhen `$deployToCloud` is true (`$deployTarget` is `Discovery` or\n`LocalToDiscovery`), Step 7c pre-flights each tool against\nthe workspace's RG via `GetDiscoveryTool`. If every tool already exists\n(`provisioningState=Succeeded`), Step 7d is skipped entirely — no ACR\nprompts, no image builds, no RBAC. Step 7e then provisions the agent in\nthe Discovery project via `UpsertAgent` + `GetAgent` provisioningState\npolling (the `GetAgentOperation` MCP tool is broken in practice — see the\nScripted MCP invocation section above). Step\n7f (local runtime registration) is optional and skipped by default.\n\n## Verification checklist\n\nAfter adding the agents, for at least one newly-created agent, confirm:\n\n- [ ] `discovery_catalog\u002F\u003Cname>\u002Fagent.yaml` exists and starts with `kind: prompt`\n- [ ] `discovery_catalog\u002F\u003Cname>\u002Fmetadata.yaml` lists `associated_tools` pointing at `agents\u002F\u003Cname>\u002Ftools\u002F\u003CTool>`\n- [ ] `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002FDockerfile` exists\n- [ ] `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002Ftool.yaml` parses as YAML and contains an `infra:` block with `image.acr`\n\nWhen `$deployTarget == 'Local'`:\n\n- [ ] `.github\u002Fagents\u002F\u003Cname>.agent.md` exists, starts with `---`, and its frontmatter `name:` matches `agent.yaml#name`\n- [ ] The body of `.github\u002Fagents\u002F\u003Cname>.agent.md` is the (de-indented) contents of `agent.yaml#instructions`, preceded by the container bootstrap preamble when at least one `tools\u002F*\u002FDockerfile` exists\n- [ ] The hand-authored Copilot agents (`batteries-included`, `bookshelf-researcher`, `project-setup-orchestrator`) are untouched\n\nWhen `$deployToCloud` is true (`$deployTarget` is `Discovery` or `LocalToDiscovery`):\n\n- [ ] Every `tools\u002F\u003CTool>\u002FDockerfile` in `$selected` has produced an image at `\u003Cacr>.azurecr.io\u002F\u003Ctool>:latest` (verify with the Azure MCP or `az acr repository show-tags`)\n- [ ] The corresponding `tool.yaml#infra.image.acr` field has been updated to point at the pushed tag\n- [ ] Each agent appears in `agents action=list` with the expected name and tool grants\n- [ ] A hosted prompt agent with the same name exists in the configured Foundry project\n\n## Things this skill must NOT do\n\n- Do not edit `agent.yaml` or `metadata.yaml` contents during the local copy step — copy verbatim. (Step 7 may rewrite `tool.yaml#infra.image.acr` after a successful ACR push; that is allowed.)\n- Do not generate placeholder Dockerfiles for tools that lack one upstream.\n- **Do not run local `podman build|pull|push` or `docker build|pull|push` directly from this skill when `$deployTarget == 'Local'`.** Local image bootstrap is delegated to the generated agents and must happen lazily at invocation time only when the image is missing.\n- When `$deployTarget == 'Local'`, do not touch Azure Container Registry, Microsoft Foundry, or the Discovery agent registry.\n- Do not delete existing local agents that aren't in upstream.\n- Do not create `.md` documentation of the add operation — print the summary to chat.\n- Do not overwrite or delete `.github\u002Fagents\u002F*.agent.md` files whose stem does **not** correspond to a `discovery_catalog\u002F\u003Cname>\u002F` folder (those are hand-authored Copilot agents).\n\n## Embedded Discovery MCP scripts\n\nThese embedded scripts are the authoritative source for the generated\n`.vscode\u002Fdiscovery-mcp-proxy.ps1` and `.vscode\u002FInvoke-DiscoveryMcp.ps1` files.\nDo not require sibling `.ps1` files next to this skill. Extract these blocks\nverbatim with the Step 4d bootstrap before making Discovery MCP calls.\n\n\u003C!-- BEGIN:embedded-discovery-mcp-proxy.ps1 -->\n```powershell\n#Requires -Version 7\n\u003C#\n.SYNOPSIS\n  Local stdio\u003C->HTTP proxy for the Microsoft Discovery remote MCP server.\n\n.DESCRIPTION\n  VS Code launches this script as a stdio MCP server. It transparently:\n  1. Mints an Entra access token for https:\u002F\u002Fdiscovery.azure.com via\n     `az account get-access-token`, using whatever tenant + subscription\n     the active `az` session is signed into.\n  2. Forwards every newline-delimited JSON-RPC message from stdin to\n     https:\u002F\u002Fmcp.discovery.azure.com\u002Fmcp via HTTPS POST, attaching the\n     bearer token and the Mcp-Session-Id header.\n  3. Streams the response back to stdout. Handles both `application\u002Fjson`\n     (single response) and `text\u002Fevent-stream` (SSE) responses.\n  4. On HTTP 401 (token expired or wrong tenant), automatically mints a\n     fresh token from `az` and retries the request once. No user\n     interaction, no clipboard, no command-palette prompt.\n\n  Replaces the legacy `inputs[type=promptString]` flow that required the\n  user to paste a token into a command-palette input every time the MCP\n  server restarted.\n\n.NOTES\n  - Requires PowerShell 7+ (uses Invoke-WebRequest -SkipHttpErrorCheck).\n  - Requires `az` CLI on PATH with an active session (`az login`).\n  - All diagnostic output goes to STDERR so it does not corrupt the MCP\n  stdio JSON-RPC channel on STDOUT.\n#>\n\n[CmdletBinding()]\nparam(\n  [string]$Endpoint = 'https:\u002F\u002Fmcp.discovery.azure.com\u002Fmcp',\n  [string]$Resource = 'https:\u002F\u002Fdiscovery.azure.com'\n)\n\n$ErrorActionPreference = 'Stop'\n$ProgressPreference = 'SilentlyContinue'\n\nfunction Write-Diag([string]$Message) {\n  [Console]::Error.WriteLine(\"[discovery-mcp-proxy] $Message\")\n}\n\nfunction New-DiscoveryToken {\n  $azPath = (Get-Command az -ErrorAction SilentlyContinue)?.Source\n  if (-not $azPath) {\n    throw \"az CLI not found on PATH. Install Azure CLI and run 'az login'.\"\n  }\n  $tok = & az account get-access-token --resource $Resource --query accessToken -o tsv 2>$null\n  if ([string]::IsNullOrWhiteSpace($tok) -or $tok -match '^(ERROR|AADSTS)') {\n    throw \"Failed to mint Discovery access token via az. Run 'az login --tenant \u003Ctenant>' and try again.\"\n  }\n  return $tok.Trim()\n}\n\n$script:Token = $null\n$script:SessionId = $null\n\ntry {\n  $script:Token = New-DiscoveryToken\n  Write-Diag \"Initial token minted (len=$($script:Token.Length)).\"\n} catch {\n  Write-Diag \"FATAL: $($_.Exception.Message)\"\n  exit 1\n}\n\nfunction Invoke-McpRequest {\n  param([string]$Body)\n\n  $headers = @{\n    'Authorization' = \"Bearer $script:Token\"\n    'Accept'        = 'application\u002Fjson, text\u002Fevent-stream'\n  }\n  if ($script:SessionId) {\n    $headers['Mcp-Session-Id'] = $script:SessionId\n  }\n\n  $attempt = 0\n  while ($true) {\n    $attempt++\n    try {\n      $resp = Invoke-WebRequest -Uri $Endpoint `\n                     -Method Post `\n                     -Body $Body `\n                     -ContentType 'application\u002Fjson' `\n                     -Headers $headers `\n                     -SkipHttpErrorCheck `\n                     -ErrorAction Stop\n    } catch {\n      Write-Diag \"POST exception: $($_.Exception.Message)\"\n      return $null\n    }\n\n    if ($resp.StatusCode -eq 401 -and $attempt -eq 1) {\n      Write-Diag \"401 from Discovery MCP; refreshing token and retrying.\"\n      try {\n        $script:Token = New-DiscoveryToken\n        $headers['Authorization'] = \"Bearer $script:Token\"\n        continue\n      } catch {\n        Write-Diag \"Token refresh failed: $($_.Exception.Message)\"\n        return $null\n      }\n    }\n\n    foreach ($k in $resp.Headers.Keys) {\n      if ($k -ieq 'Mcp-Session-Id') {\n        $val = $resp.Headers[$k]\n        if ($val -is [array]) { $val = $val[0] }\n        if ($val) { $script:SessionId = $val }\n        break\n      }\n    }\n\n    if ($resp.StatusCode -ge 400) {\n      Write-Diag \"HTTP $($resp.StatusCode) from Discovery MCP: $($resp.Content)\"\n    }\n    return $resp\n  }\n}\n\nfunction Write-McpLine([string]$Line) {\n  if ([string]::IsNullOrWhiteSpace($Line)) { return }\n  [Console]::Out.WriteLine($Line)\n  [Console]::Out.Flush()\n}\n\nfunction Emit-Response($Resp) {\n  if (-not $Resp) { return }\n  if ($Resp.StatusCode -eq 202) { return }\n  if ([string]::IsNullOrEmpty($Resp.Content)) { return }\n\n  $ctype = ''\n  foreach ($k in $Resp.Headers.Keys) {\n    if ($k -ieq 'Content-Type') {\n      $v = $Resp.Headers[$k]\n      if ($v -is [array]) { $v = $v[0] }\n      $ctype = [string]$v\n      break\n    }\n  }\n\n  if ($ctype -like 'text\u002Fevent-stream*') {\n    foreach ($block in ($Resp.Content -split \"(?:`r?`n){2,}\")) {\n      $dataLines = @()\n      foreach ($line in ($block -split \"`r?`n\")) {\n        if ($line -match '^data:\\s?(.*)$') { $dataLines += $matches[1] }\n      }\n      if ($dataLines.Count -gt 0) {\n        Write-McpLine (($dataLines -join \"`n\").Trim())\n      }\n    }\n  } else {\n    $compact = ($Resp.Content -replace \"`r?`n\", '').Trim()\n    Write-McpLine $compact\n  }\n}\n\nWrite-Diag \"Proxy ready. Endpoint=$Endpoint\"\n\ntry {\n  while ($null -ne ($line = [Console]::In.ReadLine())) {\n    if ([string]::IsNullOrWhiteSpace($line)) { continue }\n    $resp = Invoke-McpRequest -Body $line\n    Emit-Response $resp\n  }\n} catch {\n  Write-Diag \"Main loop exception: $($_.Exception.Message)\"\n  exit 2\n}\n\nWrite-Diag \"stdin closed; exiting cleanly.\"\n```\n\u003C!-- END:embedded-discovery-mcp-proxy.ps1 -->\n\n\u003C!-- BEGIN:embedded-Invoke-DiscoveryMcp.ps1 -->\n```powershell\n#Requires -Version 7\n\u003C#\n.SYNOPSIS\n  Canonical helper to invoke any Microsoft Discovery MCP tool from scripted\n  PowerShell, without depending on the VS Code MCP runtime surfacing the\n  `mcp_microsoft-dis_*` tools mid-session.\n\n.DESCRIPTION\n  Spawns `discovery-mcp-proxy.ps1` as a stdio process, sends an MCP\n  `initialize` + one `tools\u002Fcall` per call in $Calls, and returns a hash\n  keyed by JSON-RPC id (`'2'`, `'3'`, ...) whose values are the parsed\n  response objects.\n\n  This is the PREFERRED path for any MCP work this skill performs. The\n  VS Code mcp.json registration is a nice-to-have for the user's future\n  interactive sessions - do not block on it for scripted runs.\n\n.EXAMPLE\n  . \"$PSScriptRoot\\Invoke-DiscoveryMcp.ps1\"\n  $results = Invoke-DiscoveryMcp -ProxyPath \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\" -Calls @(\n    @{ name='ListAgents'; args=@{ subscriptionId=$sub; resourceGroupName=$rg; workspaceName=$ws; projectName=$proj } }\n  )\n  $r = $results['2']\n  $txt = ($r.result.content | Where-Object { $_.type -eq 'text' } | Select-Object -ExpandProperty text) -join \"`n\"\n  $obj = $txt | ConvertFrom-Json -Depth 50\n\n.NOTES\n  - Requires PowerShell 7+.\n  - Each call is a single `tools\u002Fcall`; results are returned as parsed\n  JSON-RPC objects keyed by id. Inspect `$r.result.isError` for\n  server-side tool errors (the JSON-RPC frame still succeeds in that\n  case).\n  - On HTTP 401, the proxy refreshes the `az` token automatically.\n#>\n\nfunction Invoke-DiscoveryMcp {\n  [CmdletBinding()]\n  param(\n    [Parameter(Mandatory)][string]$ProxyPath,\n    [Parameter(Mandatory)][object[]]$Calls\n  )\n\n  if (-not (Test-Path $ProxyPath)) {\n    throw \"Discovery MCP proxy not found at $ProxyPath\"\n  }\n\n  $msgs = @()\n  $msgs += '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"add-agent-from-catalog\",\"version\":\"1.0.0\"}}}'\n  $msgs += '{\"jsonrpc\":\"2.0\",\"method\":\"notifications\u002Finitialized\",\"params\":{}}'\n\n  $id = 2\n  foreach ($c in $Calls) {\n    $payload = @{\n      jsonrpc = '2.0'\n      id      = $id\n      method  = 'tools\u002Fcall'\n      params  = @{ name = $c.name; arguments = ($c.args ?? @{}) }\n    } | ConvertTo-Json -Depth 30 -Compress\n    $msgs += $payload\n    $id++\n  }\n\n  $tmp = New-TemporaryFile\n  try {\n    ($msgs -join \"`n\") | Set-Content -Path $tmp.FullName -Encoding ascii\n    $raw = Get-Content $tmp.FullName | pwsh -NoProfile -File $ProxyPath 2>$null\n  } finally {\n    Remove-Item $tmp.FullName -ErrorAction SilentlyContinue\n  }\n\n  $results = [ordered]@{}\n  foreach ($line in $raw) {\n    if ([string]::IsNullOrWhiteSpace($line)) { continue }\n    try {\n      $obj = $line | ConvertFrom-Json -Depth 50\n    } catch { continue }\n    if ($null -eq $obj.id) { continue }\n    $results[[string]$obj.id] = $obj\n  }\n  return $results\n}\n\nfunction Get-DiscoveryMcpText {\n  \u003C#\n  .SYNOPSIS\n    Extract the text payload from a single MCP tool\u002Fcall response object\n    and parse it as JSON when possible.\n  .DESCRIPTION\n    Most Discovery MCP tools return their payload inside\n    $r.result.content[].text as a JSON string. This helper concatenates\n    those text blocks and (optionally) parses the result.\n  #>\n  [CmdletBinding()]\n  param(\n    [Parameter(Mandatory)][object]$Response,\n    [switch]$AsJson\n  )\n  if (-not $Response) { return $null }\n  $texts = @()\n  foreach ($c in $Response.result.content) {\n    if ($c.type -eq 'text') { $texts += $c.text }\n  }\n  $blob = $texts -join \"`n\"\n  if ($AsJson) {\n    try { return $blob | ConvertFrom-Json -Depth 50 } catch { return $blob }\n  }\n  return $blob\n}\n\nfunction Wait-DiscoveryAgentReady {\n  \u003C#\n  .SYNOPSIS\n    Poll GetAgent until provisioningState == 'Succeeded' (or 'Failed').\n  .DESCRIPTION\n    Replaces the unreliable GetAgentOperation polling. The MCP server's\n    GetAgentOperation often returns an opaque \"An error occurred invoking\n    'GetAgentOperation'.\" text even when UpsertAgent has succeeded - but\n    GetAgent reliably reports provisioningState.\n  #>\n  [CmdletBinding()]\n  param(\n    [Parameter(Mandatory)][string]$ProxyPath,\n    [Parameter(Mandatory)][string]$SubscriptionId,\n    [Parameter(Mandatory)][string]$ResourceGroupName,\n    [Parameter(Mandatory)][string]$WorkspaceName,\n    [Parameter(Mandatory)][string]$ProjectName,\n    [Parameter(Mandatory)][string]$AgentName,\n    [int]$TimeoutSeconds = 300,\n    [int]$IntervalSeconds = 5\n  )\n  $deadline = (Get-Date).AddSeconds($TimeoutSeconds)\n  while ((Get-Date) -lt $deadline) {\n    $results = Invoke-DiscoveryMcp -ProxyPath $ProxyPath -Calls @(\n      @{ name='GetAgent'; args=@{ subscriptionId=$SubscriptionId; resourceGroupName=$ResourceGroupName; workspaceName=$WorkspaceName; projectName=$ProjectName; agentName=$AgentName } }\n    )\n    $r = $results['2']\n    $obj = Get-DiscoveryMcpText -Response $r -AsJson\n    if ($obj -and $obj.provisioningState) {\n      if ($obj.provisioningState -eq 'Succeeded') { return $obj }\n      if ($obj.provisioningState -eq 'Failed')    { throw \"Agent '$AgentName' provisioning Failed: $($obj | ConvertTo-Json -Depth 10 -Compress)\" }\n    }\n    Start-Sleep -Seconds $IntervalSeconds\n  }\n  throw \"Timed out after ${TimeoutSeconds}s waiting for agent '$AgentName' to reach Succeeded.\"\n}\n```\n\u003C!-- END:embedded-Invoke-DiscoveryMcp.ps1 -->\n- Do not add `tools:` frontmatter to generated `.agent.md` files — Discovery tool IDs don't map to Copilot tool names, and a wrong list silently disables tools.\n- **Do not call `runSubagent agentName='microsoft-foundry'`.** That skill is not registered as a subagent in this workspace, and even when invoked directly it assumes an azd `.foundry\u002F` overlay that catalog agents don't have. Execute the deploy pipeline inline via Discovery MCP (`GetDiscoveryTool`, `UpsertAgent`, `GetAgent` provisioningState polling) + `az` CLI, as documented in Steps 7c–7e.\n- Do not push tool images to any registry other than the ACR named in Step 7c.2.\n- Do not request secrets through `vscode_askQuestions`; require the user to authenticate to Azure with `az login` directly in the terminal when needed. Do not ask for GitHub authentication for the public `microsoft\u002Fdiscovery` catalog fetch.\n\n## When to ask the user\n\nAsk **once, up front**, in **this order** (the order matters — each answer\nshapes the next prompt):\n\n1. **Deployment target** (Step 4c) — Local Copilot only \u002F Microsoft Discovery + Azure (from upstream) \u002F\n   Local app -> Microsoft Discovery + Azure (promote). Default =\n   `Local Copilot only` (cheapest, fastest, fully local).\n   This is the **first** user-facing prompt; everything else is scoped to\n   the answer here.\n2. **Discovery tenant + subscription + workspace + project** (Step 4d,\n   only when target is `Discovery` or `LocalToDiscovery`) — install the Microsoft Discovery\n   MCP server **without asking** if `agents action=registry.list` doesn't\n   already succeed (the user opted into the Discovery + Azure path; the\n   MCP is a hard prerequisite). Before starting the MCP server, prompt\n   the user **once** (single `vscode_askQuestions` call, two questions)\n   for the Azure **tenant ID** and **subscription ID** (Step 7a.2.5),\n   then run `az login --tenant \u003Cid>` and `az account set --subscription\n   \u003Cid>` on their behalf in a foreground terminal. Persist the choices to\n   `\u002Fmemories\u002Frepo\u002F`. After `az` is ready, restart the MCP server, then\n   present single-select prompts for workspace and project (sourced via\n   `ListWorkspaces` \u002F\n   `ListProjects` calls (always via `Invoke-DiscoveryMcp`; never depend on the\n   VS Code deferred `mcp_microsoft-dis_*` tools surfacing). Always list the existing agents in\n   the chosen project before continuing, and confirm before moving on to\n   the agent picker. **These four prompts (tenant, subscription,\n   workspace, project) are mandatory on every Discovery run — never\n   skip them based on saved values in `\u002Fmemories\u002Frepo\u002F`. Saved values\n   are used only to mark the corresponding option as `recommended` in\n   the picker.**\n3. **Agent selection** (Step 4e) — present the All \u002F Specific \u002F By group\n   prompt via `vscode_askQuestions`. This is mandatory; never default to\n   adding the whole catalog without confirmation. When target ==\n   `Discovery`, annotate options whose folder name matches an existing\n   agent in the project (from step 2) with `[ALREADY IN PROJECT]` so the\n   user knows what will be updated by `UpsertAgent`.\n4. **Local runtime readiness** (Step 4f, only when target == `Local`) —\n  detect Podman\u002FDocker availability. If both are installed, ask once which\n  runtime the user prefers (default `podman`). If only one is installed,\n  auto-select it. If neither is installed, ask once whether to install\n  Podman automatically; on yes run `winget install --id RedHat.Podman --accept-source-agreements --accept-package-agreements`, on no continue with a clear warning that container-based tools cannot run until Podman or Docker is installed.\n5. **Overwrite conflicts** — if any folder in `$selected` already exists\n   locally, ask once whether to overwrite. Default = no.\n6. **Azure deployment configuration** (Step 7c.2, only when target == `Discovery`\n   **and** Step 7c found at least one tool that needs building) —\n   subscription, resource group, ACR, region. Foundry project is pre-filled\n   from Step 4d; the user only overrides it if they explicitly need a\n   different target. Ask all in a single `vscode_askQuestions` call. Pre-fill\n   defaults from `az account show` and any prior values stored in\n   `\u002Fmemories\u002Frepo\u002F`. **Skip entirely when every declared tool already\n   exists as an ARM resource** (the common case for shared catalog images).\n7. **Azure MCP install** (Step 7b, only when target is `Discovery` or `LocalToDiscovery`) — if a\n   relevant Azure plugin is `metadata_only`, ask once whether to install it.\n   Default = no (fall back to `az` CLI).\n8. **Agent overwrite** (Step 7e) — if an agent with the same name already\n   exists in the target Discovery project (visible from `ListAgents` in\n   Step 4d), ask once before calling `UpsertAgent` (which will update the\n   existing definition in place). Default = no.\n\nDo NOT ask whether to pre-build local images when `$deployTarget == 'Local'` —\nthat step never builds images. Ask runtime readiness only (Step 4f).\nEach generated agent will build its own image lazily on first invocation,\ntrying Podman first and Docker second, only if the image is not already present.\n\nDo not launch a GitHub device-flow prompt in Step 2. The upstream\n`microsoft\u002Fdiscovery` repository is public, so GitHub authentication is not\npart of this workflow. `az login` in Step 7a.2.5 is still launched on the\nuser's behalf as soon as tenant + subscription are picked.\n\nOtherwise run end-to-end without further prompting.\n\n\n\n\n\n","# add-example-agents\n\nAdd agents from the public `microsoft\u002Fdiscovery` repository to this\nworkspace, then deploy each selected agent to exactly one of two targets:\n\n- **Local Copilot** - emit a `.github\u002Fagents\u002F\u003Cname>.agent.md` companion for\n  every agent so it can be invoked as a Copilot subagent via `runSubagent`.\n  Tool container images are built lazily on first invocation, locally only.\n- **Microsoft Discovery + Azure** - pre-flight every tool the agent\n  declares via `GetDiscoveryTool` against the workspace's RG. When a tool\n  ARM resource already exists (common for shared catalog images on\n  registries like `mdqacr`), skip Docker build \u002F ACR push \u002F AcrPull RBAC\n  entirely and bind the existing ARM ID. When a tool is missing, build +\n  push via `az acr build`, register the tool ARM, grant AcrPull. Either\n  way, create the agent in the target Discovery project via `UpsertAgent`\n  and poll **`GetAgent`** until `provisioningState=Succeeded`. Local\n  Discovery runtime registration (`agents action=create`) is optional and\n  skipped by default.\n- **Local app → Microsoft Discovery + Azure (promote)** - take an agent\n  that is **already added to the local Copilot app** (present under\n  `discovery_catalog\u002F\u003Cname>\u002F` with a `.github\u002Fagents\u002F\u003Cname>.agent.md`\n  companion and, for tool-bearing agents, a locally-built container image)\n  and register it in a specific Discovery project. The **local** folder is\n  the source of truth - the upstream `microsoft\u002Fdiscovery` repo is **not**\n  fetched or refreshed, so any local edits are preserved. Tool container(s)\n  are pushed to ACR from the local build context \u002F locally-built image, then\n  the agent is created via `UpsertAgent` and polled with `GetAgent` exactly\n  as in the upstream-sourced Discovery path.\n\nThe user picks the deployment target **first** (Step 4c), then — only for a Discovery-class target (Discovery or LocalToDiscovery) — confirms the destination workspace + project (Step 4d), and **then** chooses which agents to add (Step 4e).\n\n## Source of truth\n\n- Upstream repo: `https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery`\n- Path of interest: `agents\u002F`\n- Each subfolder under `agents\u002F\u003CNAME>\u002F` is one Discovery agent.\n\nThe upstream layout for every agent is identical and matches what already lives\nin this workspace's `discovery_catalog\u002F`:\n\n```\nagents\u002F\u003Cname>\u002F\n├── agent.yaml          # prompt \u002F hosted agent definition (kind: prompt)\n├── metadata.yaml       # name, version, associated_tools, publisher, tags\n├── README.md           # deployment & usage guide\n└── tools\u002F\n    └── \u003CToolName>\u002F\n        ├── Dockerfile          # container image recipe\n        ├── tool.yaml           # tool definition (infra, code_environments)\n        ├── *-EnvVars.json      # optional env-var spec\n        ├── basic-description.txt\n        └── \u003Cutils>.py          # optional helper code\n```\n\nThe local target is **identical**, only the parent folder differs:\n\n```\ndiscovery_catalog\u002F\u003Cname>\u002F...    # 1:1 mirror of agents\u002F\u003Cname>\u002F...\n```\n\nSo adding an agent is a straight folder copy — no transformation required.\n\n## Prerequisites\n\nRequired for **every** run (Step 3 — fetch catalog):\n\n| Requirement | Check command | Required for |\n|---|---|---|\n| `git` on PATH | `git --version` | cloning the catalog |\n| Network access to github.com | `Test-NetConnection github.com -Port 443` | cloning |\n\nRequired **only** when `$deployToCloud` is true (`$deployTarget` is `Discovery` or `LocalToDiscovery`) (Step 7 —\nMicrosoft Discovery + Azure deployment):\n\n| Requirement | Check command | Required for |\n|---|---|---|\n| `az` CLI on PATH | `az --version` | Azure subscription \u002F ACR \u002F RBAC operations (fallback when Azure MCP is absent) |\n| Active `az login` session | `az account show` | calling any Azure resource |\n| `docker` CLI on PATH | `docker --version` | building tool images locally before push (fallback when Azure MCP \u002F `az acr build` is unavailable) |\n| Azure Container Registry write access | `az acr login -n \u003Cacr>` | pushing tool images |\n| Discovery MCP reachable via the proxy | `pwsh -NoProfile -File .vscode\u002Fdiscovery-mcp-proxy.ps1` accepts a JSON-RPC `initialize` and replies | tool pre-flight (`GetDiscoveryTool`), agent provisioning (`UpsertAgent` + `GetAgent` poll), model lookup (`ListChatModelDeployments`). Installed by Step 4d by extracting the embedded `discovery-mcp-proxy.ps1` and `Invoke-DiscoveryMcp.ps1` blocks from this `SKILL.md` into `.vscode\u002F`. **All MCP calls go through the extracted proxy via the extracted `Invoke-DiscoveryMcp` helper, not through VS Code's `mcp_microsoft-dis_*` deferred tools.** The mcp.json registration is written too, but only as a courtesy for the user's future interactive sessions — never wait for those deferred tools to surface mid-run. |\n| `microsoft-foundry` skill (optional) | (listed in workspace skills) | reference only — **not** invoked via `runSubagent`. Catalog agents are not azd projects, so the foundry skill's `.foundry\u002F` overlay flow does not apply. Use the direct Discovery MCP path documented in Steps 7c–7e. |\n\nThe upstream repository is public. Do not require `gh`, `GH_TOKEN`,\n`GITHUB_TOKEN`, GitHub device-flow login, or any other GitHub authentication\nfor the catalog fetch. Anonymous `git clone` and GitHub contents API requests\nare expected to work.\n\nWhen `$deployTarget == 'Local'`, neither Docker Desktop nor Podman is a hard\nprerequisite for running this skill itself. The skill never invokes local\nimage builds directly; image bootstrap is delegated to each generated agent at\ninvocation time (see Step 6). Runtime readiness is handled by Step 4f.\n\n## Scripted MCP invocation (canonical fast path)\n\n> **This is the only MCP path the skill should use mid-run.** Do NOT wait\n> for VS Code's MCP runtime to surface `mcp_microsoft-dis_*` deferred\n> tools — in practice they often do not appear in the same session that\n> registered them. Invoke the proxy directly via stdio instead. It works\n> first-try every time once `az login` is set up.\n\nTwo PowerShell files are embedded at the bottom of this skill and materialized\ninto `.vscode\u002F` during Step 4d:\n\n| Embedded block | Role |\n|---|---|\n| `embedded-discovery-mcp-proxy.ps1` | Local PowerShell stdio ↔ HTTPS proxy. Mints `https:\u002F\u002Fdiscovery.azure.com` tokens via `az`, forwards JSON-RPC frames to `https:\u002F\u002Fmcp.discovery.azure.com\u002Fmcp`, refreshes on 401, preserves `Mcp-Session-Id`. |\n| `embedded-Invoke-DiscoveryMcp.ps1` | PowerShell helpers: `Invoke-DiscoveryMcp` (spawn proxy, send initialize + N `tools\u002Fcall`, return responses keyed by JSON-RPC id), `Get-DiscoveryMcpText` (extract \u002F parse the text payload), `Wait-DiscoveryAgentReady` (poll `GetAgent` for `provisioningState=Succeeded`). |\n\n**Install ritual (run once per workspace, in Step 4d):**\n\n```pwsh\n$skillDir = \"\u003Cabsolute path to this skill folder>\"   # contains SKILL.md\nNew-Item -ItemType Directory -Force -Path \"$workspaceRoot\\.vscode\" | Out-Null\n$skillPath = Join-Path $skillDir 'SKILL.md'\n$skillText = Get-Content $skillPath -Raw\nfunction Write-EmbeddedSkillScript([string]$BlockId, [string]$Destination) {\n  $begin = \"\u003C!-- BEGIN:$BlockId -->\"\n  $end = \"\u003C!-- END:$BlockId -->\"\n  $start = $skillText.IndexOf($begin)\n  if ($start -lt 0) { throw \"Embedded script block '$BlockId' not found in $skillPath\" }\n  $contentStart = $start + $begin.Length\n  $stop = $skillText.IndexOf($end, $contentStart)\n  if ($stop -lt 0) { throw \"Embedded script block '$BlockId' has no end marker in $skillPath\" }\n  $block = $skillText.Substring($contentStart, $stop - $contentStart).Trim()\n  $lines = @($block -split \"`r?`n\")\n  if ($lines.Count -lt 3 -or $lines[0] -notmatch '^```powershell\\s*$' -or $lines[-1] -notmatch '^```\\s*$') {\n      throw \"Embedded script block '$BlockId' must be wrapped in a powershell fenced code block.\"\n  }\n  $content = (($lines[1..($lines.Count - 2)]) -join \"`r`n\") + \"`r`n\"\n  Set-Content -Path $Destination -Value $content -Encoding UTF8\n}\nWrite-EmbeddedSkillScript 'embedded-discovery-mcp-proxy.ps1' \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\"\nWrite-EmbeddedSkillScript 'embedded-Invoke-DiscoveryMcp.ps1' \"$workspaceRoot\\.vscode\\Invoke-DiscoveryMcp.ps1\"\n\n# (Optional, for the user's future interactive sessions only) write .vscode\u002Fmcp.json\n# — see Step 7a.2 for the merge-safe writer. Do NOT block on the MCP runtime\n# actually loading those tools mid-run.\n```\n\n**Canonical call pattern (use this for ListWorkspaces \u002F ListProjects \u002F\nListAgents \u002F GetDiscoveryTool \u002F ListChatModelDeployments \u002F UpsertAgent \u002F\nGetAgent — every MCP call this skill makes):**\n\n```pwsh\n. \"$workspaceRoot\\.vscode\\Invoke-DiscoveryMcp.ps1\"\n$proxy = \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\"\n\n$results = Invoke-DiscoveryMcp -ProxyPath $proxy -Calls @(\n    @{ name='ListAgents'; args=@{\n        subscriptionId    = $sub\n        resourceGroupName = $rg\n        workspaceName     = $ws\n        projectName       = $proj\n    } }\n)\n$obj = Get-DiscoveryMcpText -Response $results['2'] -AsJson\n# $obj is the parsed payload (varies by tool — array, {value:[]}, single object, …)\n```\n\n**Polling pattern for `UpsertAgent` completion** — for the happy path,\nprefer `GetAgent` provisioningState polling over `GetAgentOperation`\n(historically `GetAgentOperation` has sometimes returned an opaque\n`\"An error occurred invoking 'GetAgentOperation'.\"`). Use the provided\nhelper. When `GetAgent` reports a bare `Failed` with no error text,\n`GetAgentOperation` (called with the `UpsertAgent` operationId) *can*\nreturn the real `{status, error, result}` — see Step 7e.5:\n\n```pwsh\nWait-DiscoveryAgentReady -ProxyPath $proxy `\n    -SubscriptionId $sub -ResourceGroupName $rg `\n    -WorkspaceName $ws -ProjectName $proj `\n    -AgentName 'retrochimera' -TimeoutSeconds 300\n```\n\n**Why scripts, not inline heredocs.** The VS Code agent terminal echoes\nmulti-line PowerShell commands back to stdin and frequently truncates\nheredocs. **Always** write multi-line PowerShell to a temp `.ps1` file\n(`\"$env:TEMP\\dc-\u003Ctask>.ps1\"`) and invoke with\n`pwsh -NoProfile -File \"\u003Cpath>\"`. One-liners are fine. This applies to\nthe Step 6 local companion-generation script as well as MCP scripts. Do\nnot paste a long function-heavy PowerShell block directly into the shared\nterminal; if a prompt is left inside a partial function or here-doc, close\nthat syntax first and rerun from a `.ps1` file.\n\n**Operational guarantees:**\n\n- Agents are **not** an ARM resource type. There is no\n  `Microsoft.Discovery\u002Fworkspaces\u002Fprojects\u002Fagents` resource provider.\n  Never call `az rest ...\u002Fprojects\u002F\u003Cp>\u002Fagents?...` — it always returns\n  `ResourceTypeRegistrationNotFound`. Agents only exist behind the MCP\n  server's `ListAgents` \u002F `GetAgent` \u002F `UpsertAgent` \u002F `DeleteAgent`.\n- Workspaces and projects **are** ARM resources but use the\n  `Microsoft.Discovery` provider — current api-version `2026-06-01`\n  (older `2024-10-01-preview` is rejected with\n  `InvalidResourceType`). Prefer the MCP `ListWorkspaces` \u002F\n  `ListProjects` calls anyway — they return the same data without\n  api-version drift.\n- `Microsoft-dis_*` deferred tool names are **not** required. If a\n  later VS Code release surfaces them automatically, the skill may use\n  them in addition to the proxy — but never instead of it (the proxy\n  is the always-available baseline).\n\n## Workflow\n\n### Step 1 — Discover workspace layout\n\n1. Locate the workspace root by searching for a top-level `discovery_catalog\u002F`\n   folder (the user's prompt may not say where it is).\n2. Enumerate **`.github\u002Fagents\u002F*.agent.md`** — these are the Copilot companion\n   files and are the **authoritative source of truth for which agents are\n   already locally added**. Strip the `.agent.md` suffix to get the agent\n   folder name. Use this set (call it `$existingLocalAgents`) for both the\n   Step 4e Local collision hint and the Step 8 \"already had companion\"\n   summary bucket. **Do not** infer \"already added\" from the presence of a\n   `discovery_catalog\u002F\u003Cname>\u002F` folder — that folder is always refreshed from\n   upstream in Step 5 and would mislabel every entry as \"already present\".\n     In PowerShell, do **not** use `$_.BaseName` for this; for\n     `pubchem.agent.md`, `.BaseName` is `pubchem.agent`, not `pubchem`.\n     Use an explicit suffix removal:\n     ```pwsh\n     $existingLocalAgents = @{}\n     Get-ChildItem $agentsDir -Filter '*.agent.md' -File -ErrorAction SilentlyContinue | ForEach-Object {\n       $stem = $_.Name -replace '\\.agent\\.md$', ''\n       $existingLocalAgents[$stem] = $true\n     }\n     ```\n3. Also list the `discovery_catalog\u002F\u003Cname>\u002F` folders so Step 5 can report\n   which folders were **created fresh** vs **refreshed in place** vs\n   **removed from upstream** (no longer present in `agents\u002F`).\n\n### Step 2 — Confirm public GitHub access\n\n> **Skip Steps 2 and 3 when `$deployTarget == 'LocalToDiscovery'`**\n> (`$sourceMode == 'Local'`). Promotion never touches the upstream repo — the\n> agent already lives in `discovery_catalog\u002F`. When the user's request clearly\n> asks to promote a local agent, ask the Step 4c deployment-target question\n> **before** these steps so the fetch is avoided; otherwise a fetch that\n> already ran is simply ignored (the clone is discarded in Step 8). Build the\n> catalog index from the local workspace instead (Step 4c.LTD).\n\nThe `microsoft\u002Fdiscovery` repo is public. Do **not** run `gh auth status`,\n`gh auth login`, token setup, or authenticated REST probes for the catalog.\nOnly verify ordinary network access to GitHub before cloning:\n\n```pwsh\ngit --version\nTest-NetConnection github.com -Port 443\n```\n\nIf the public fetch returns 404 or another HTTP error, report the exact\ncommand + status \u002F git error. Treat it as a network, URL, rate-limit, or\ntemporary GitHub availability problem unless the user provides different\nevidence. **Never fabricate agent content.**\n\n### Step 3 — Fetch the upstream catalog\n\nPrefer a shallow sparse checkout to avoid pulling unrelated parts of the repo:\n\n```pwsh\n$work = Join-Path $env:TEMP (\"discovery-agents-\" + [Guid]::NewGuid().ToString('N').Substring(0,8))\ngit clone --depth 1 --filter=blob:none --sparse https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery.git $work\nPush-Location $work\ngit sparse-checkout set agents\nPop-Location\n```\n\nFallbacks (in order) if the sparse clone fails:\n\n1. `git clone --depth 1 https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery.git $work`\n2. REST API: enumerate\n   `https:\u002F\u002Fapi.github.com\u002Frepos\u002Fmicrosoft\u002Fdiscovery\u002Fcontents\u002Fagents`\n   recursively, downloading each file with\n  `Invoke-WebRequest -Headers @{ 'User-Agent' = 'add-agent-from-catalog' }`.\n\nIf all fetch strategies fail, stop and report the exact command + HTTP status \u002F\ngit error. **Never fabricate agent content.**\n\n### Step 4 — Pick deployment target, confirm workspace\u002Fproject, then choose agents\n\nAsk the user **the required prompts in this order**, via `vscode_askQuestions`.\nNever copy the entire catalog silently — many agents are heavyweight (container\ntools, large research stacks) and the user should opt in.\n\n1. **Deployment target** (Step 4c) — Local Copilot only \u002F Microsoft Discovery + Azure (from upstream) \u002F Local app -> Microsoft Discovery + Azure (promote).\n2. **Discovery workspace + project** (Step 4d, conditional on a Discovery-class target — `Discovery` or `LocalToDiscovery`) —\n   ensure the user is signed in to Azure, install the Discovery MCP if missing,\n   list available workspaces and projects, list existing agents in the chosen\n   project, and confirm the destination. This MUST happen **before** the agent\n   picker so the user can see name collisions in the target project.\n3. **Agent selection** (Step 4e) — selection mode (All \u002F Specific \u002F By group)\n   plus values.\n\nSteps 4a and 4b (build catalog index + derive groups) still run before the\nagent picker in Step 4e, but they don't require user input and can happen at\nany point after Step 3 (catalog fetch).\n\n#### 4a. Build the catalog index\n\nFor each `agents\u002F\u003Cname>\u002F` folder under the freshly-cloned `$srcRoot`,\nread `metadata.yaml` and extract:\n\n- `name` (fallback: folder name)\n- `tags` (list — may be empty)\n- `description` from `agent.yaml` (first sentence, trimmed to ~80 chars for display)\n- `associated_tools` count (from `metadata.yaml`, used to flag heavyweight agents)\n\n```pwsh\n$srcRoot = Join-Path $work 'agents'\n$catalog = @()\nGet-ChildItem $srcRoot -Directory | ForEach-Object {\n    $folder = $_.Name\n    $meta   = Join-Path $_.FullName 'metadata.yaml'\n    $ay     = Join-Path $_.FullName 'agent.yaml'\n    $tags   = @()\n    $tools  = 0\n    $desc   = ''\n    if (Test-Path $meta) {\n        $mtxt = Get-Content $meta -Raw\n        # Extract tags: lines like \"  - tagname\" under a \"tags:\" key\n        if ($mtxt -match '(?ms)^tags:\\s*\\r?\\n((?:\\s*-\\s*\\S+\\r?\\n?)+)') {\n            $tags = ($matches[1] -split \"`n\") |\n                ForEach-Object { ($_ -replace '^\\s*-\\s*', '').Trim() } |\n                Where-Object { $_ }\n        }\n        if ($mtxt -match '(?ms)^associated_tools:\\s*\\r?\\n((?:\\s*-\\s*\\S+\\r?\\n?)+)') {\n            $tools = (($matches[1] -split \"`n\") | Where-Object { $_ -match '\\S' }).Count\n        }\n    }\n    if (Test-Path $ay) {\n        $atxt = Get-Content $ay -Raw\n        if ($atxt -match '(?ms)^description:\\s*[>|]?\\s*\\r?\\n((?:\\s{2,}.+\\r?\\n?)+)') {\n            $desc = (($matches[1] -split \"`n\")[0] -replace '^\\s+', '').Trim()\n        } elseif ($atxt -match '^description:\\s*(.+)$') {\n            $desc = $matches[1].Trim().Trim('\"').Trim(\"'\")\n        }\n    }\n    $catalog += [pscustomobject]@{\n        Folder = $folder\n        Tags   = $tags\n        Tools  = $tools\n        Desc   = $desc\n    }\n}\n```\n\n#### 4b. Derive groups\n\nGroup agents by their tags. An agent with multiple tags appears in each\nmatching group. Always include two synthetic groups at the top:\n\n- **All agents** — every folder under upstream `agents\u002F`.\n- **Lightweight (no container tools)** — agents whose `tools\u002F` folder is empty or\n  contains no `Dockerfile`. These install fastest and don't require local\n  container runtimes.\n\n```pwsh\n$groups = [ordered]@{}\n$groups['All agents']                = $catalog.Folder\n$groups['Lightweight (no container tools)'] = ($catalog | Where-Object { $_.Tools -eq 0 }).Folder\nforeach ($a in $catalog) {\n    foreach ($t in $a.Tags) {\n        if (-not $groups.Contains($t)) { $groups[$t] = @() }\n        $groups[$t] += $a.Folder\n    }\n}\n# Deduplicate\nforeach ($k in @($groups.Keys)) { $groups[$k] = $groups[$k] | Select-Object -Unique }\n```\n\n#### 4c. Ask deployment target (FIRST user-facing prompt)\n\nSingle `vscode_askQuestions` call with one question. This MUST be asked\nbefore workspace\u002Fproject (4d) or agent selection (4e) - the answer\ndetermines whether 4d runs at all and changes what 4e shows.\n\n```\nheader: \"deployment-target\"\nquestion: \"Where do you want these agents deployed?\"\noptions:\n  - \"Microsoft Discovery local app only\" (recommended default - requires a GitHub Copilot license, no Azure subscription needed)\n  - \"Microsoft Discovery service (from upstream)\" (Azure subscription required, fetches each agent fresh from microsoft\u002Fdiscovery and registers it in a specific Discovery workspace project that you select)\n  - \"Promote a local app agent to Microsoft Discovery service\" (Azure subscription required, takes an agent already added to the local app plus its locally-built tool container and registers it in a specific Discovery workspace project that you select, without re-fetching upstream)\n```\n\nPersist as `$deployTarget` (`Local` | `Discovery` | `LocalToDiscovery`):\n\n- `Local`            - refresh `discovery_catalog\u002F` from upstream and emit\n                     `.github\u002Fagents\u002F*.agent.md` (Steps 5 + 6). Local tool\n                     images are built lazily on first invocation only, via\n                     Podman-first then Docker fallback.\n- `Discovery`        - refresh `discovery_catalog\u002F` from upstream, build + push\n                     any missing tool images to ACR, register each agent in the\n                     Microsoft Discovery project via `UpsertAgent` (Steps 5 + 7).\n- `LocalToDiscovery` - **do not fetch or refresh from upstream**; use the\n                     agent's existing local `discovery_catalog\u002F\u003Cname>\u002F` folder\n                     as the source of truth. Build + push any missing tool\n                     images to ACR from the local build context \u002F locally-built\n                     image, then register the agent in the Microsoft Discovery\n                     project via `UpsertAgent` (Step 7; local-source deltas in\n                     Steps 4c.LTD and 7d.LTD).\n\nDerive two helper flags used throughout the rest of the workflow:\n\n- `$deployToCloud = $deployTarget -in @('Discovery','LocalToDiscovery')` -\n  true for both Discovery-class targets. **Wherever a later step gates on\n  `$deployTarget == 'Discovery'` for Azure\u002FDiscovery work (Steps 4d, 7 and\n  all its sub-steps, and the Discovery branches of Step 8), read it as\n  `$deployToCloud`** so the promote target runs the same cloud machinery.\n- `$sourceMode = if ($deployTarget -eq 'LocalToDiscovery') { 'Local' } else { 'Upstream' }` -\n  `Upstream` fetches + refreshes from `microsoft\u002Fdiscovery` (Steps 2, 3, 5);\n  `Local` skips all upstream fetch\u002Frefresh and treats\n  `discovery_catalog\u002F\u003Cname>\u002F` as authoritative.\n\nStep 5 runs for `Upstream` source mode only. For `LocalToDiscovery`\n(`$sourceMode == 'Local'`) it is **skipped** - overwriting the local folder\nwith upstream would discard the local edits the user is promoting.\n\nDownstream branch:\n\n- `Local`     \\u2192 skip 4d. Run 4e (agent picker), then 4f (local runtime\n          readiness), then Step 6.\n- `Discovery` \\u2192 run 4d **immediately** (workspace + project picker, before\n              the agent picker). Then run 4e, then Step 7.\n- `LocalToDiscovery` -> skip the upstream fetch (Steps 2 + 3); build the catalog\n              index from the local `.github\u002Fagents\u002F` companions (Step 4c.LTD),\n              classifying each into tool-bearing (has `discovery_catalog\u002F\u003Cname>\u002F`)\n              vs toolless; run 4d **immediately** (workspace + project picker);\n              then run 4e (agent picker scoped to the local-app companions in\n              `$localAgents`); **skip Step 5**; then run Step 7.\n\n#### 4c.LTD. Build the catalog index from the local app (LocalToDiscovery only)\n\nRun this **instead of** the upstream fetch (Steps 2 + 3) and the upstream\ncatalog index (Step 4a) when `$deployTarget == 'LocalToDiscovery'`. The\nsource of truth is the workspace, not `microsoft\u002Fdiscovery`.\n\n**The authoritative list of what can be promoted is\n`.github\u002Fagents\u002F*.agent.md` (the `$existingLocalAgents` set from Step 1),\nNOT the `discovery_catalog\u002F` folders.** A locally-created agent may have\n**no** `discovery_catalog\u002F\u003Cname>\u002F` folder at all — that folder only exists\nfor agents that carry a container-based tool. A toolless prompt agent lives\nentirely in its `.github\u002Fagents\u002F\u003Cname>.agent.md` companion. Both kinds are\npromotable; only the source of `agent.yaml`-equivalent fields differs.\n\nClassify each companion in `$existingLocalAgents` into one of two buckets:\n\n- **Tool-bearing** — a `discovery_catalog\u002F\u003Cname>\u002F` folder exists with an\n  `agent.yaml`. Read `metadata.yaml#associated_tools` and the\n  `tools\u002F\u003CTool>\u002F` subtree from there. Source **both** `instructions` **and**\n  `name` \u002F `description` from the `.github\u002Fagents\u002F\u003Cname>.agent.md` companion\n  (via `Get-AgentMdInstructions` and `Get-AgentMdFrontmatterValue`),\n  **not** from `agent.yaml` — the companion is the source of truth for the\n  prompt body *and* the display name\u002Fdescription the user tuned locally\n  (see Step 7e.1). These go through the full Step 7 tool\n  pre-flight \u002F build \u002F bind path.\n- **Toolless** — no `discovery_catalog\u002F\u003Cname>\u002F` folder (or the folder has\n  no `agent.yaml`). Source the agent fields from the `.agent.md` companion\n  instead: `name` and `description` from its YAML frontmatter (via\n  `Get-AgentMdFrontmatterValue`), and the `instructions` from its markdown\n  body (strip any auto-generated \"Container image bootstrap\" preamble and\n  the leading `---` frontmatter block; what remains is the Discovery\n  prompt). These skip all of Step 7c\u002F7d (no tools) and go straight to\n  `UpsertAgent` in Step 7e with an empty `toolIds`.\n\nSteps:\n\n1. Enumerate promotable agents = every stem in `$existingLocalAgents`\n   (the `.github\u002Fagents\u002F\u003Cname>.agent.md` companions). Persist as\n   `$localAgents`. For each, record `$agentHasCatalogFolder[$name]` =\n   `Test-Path discovery_catalog\u002F\u003Cname>\u002Fagent.yaml`. Do **not** require a\n   `discovery_catalog\u002F` folder — its absence just means \"toolless\".\n   **Exclude the hand-authored, non-Discovery Copilot agents** that ship\n   with the workspace and are not catalog\u002FDiscovery agents — at minimum\n   `batteries-included`, `bookshelf-researcher`, `project-setup-orchestrator`,\n   and `agentic-grader`. A companion qualifies as promotable only if it was\n   produced by this skill (Local target, Step 6) or otherwise represents a\n   Discovery agent; if unsure, prefer companions whose body contains the\n   generated container-bootstrap preamble or that have a matching\n   `discovery_catalog\u002F\u003Cname>\u002F` folder, and skip the rest.\n2. If `$localAgents` is empty, stop and tell the user there are no\n   locally-added agents to promote — they must first add one via the\n   **Local Copilot** target, then re-run for promotion.\n3. Build the same `$catalog` \u002F `$groups` structures Steps 4a\u002F4b produce.\n   For **tool-bearing** agents read `metadata.yaml` \u002F `agent.yaml` from\n   `discovery_catalog\u002F\u003Cname>\u002F`; for **toolless** agents read `name` \u002F\n   `description` from the `.agent.md` frontmatter and set the tool count to\n   `0` (they always land in the *Lightweight (no container tools)* group).\n   Do not set a single `$srcRoot` for tool enumeration — resolve each\n   agent's source per-bucket via `$agentHasCatalogFolder` so Step 7 reads\n   from the right place.\n4. In Step 4e, scope the agent picker to `$localAgents` only (label each\n   `[agent] \u003Cname>`), and drop the \"upstream refresh\" framing — nothing is\n   fetched or overwritten. Optionally annotate toolless entries in the\n   option `description` with `(no container tool)` so the user can tell them\n   apart from tool-bearing ones.\n\n   ```pwsh\n   # Extract the promotable instructions from a toolless .agent.md companion.\n   #\n   # CRLF-SAFE: generated .agent.md companions are written with CRLF line\n   # endings on Windows. A naive `\\n---\\n` horizontal-rule match FAILS to\n   # match (the real bytes are `\\r\\n---\\r\\n`), so the bootstrap strip below\n   # would silently no-op and leave the whole preamble in the body. ALWAYS\n   # use `\\r?\\n---\\r?\\n` for the horizontal-rule delimiter.\n   function Get-AgentMdInstructions([string]$AgentMdPath) {\n     $raw = Get-Content $AgentMdPath -Raw\n     # Drop the leading YAML frontmatter block ( --- ... --- ).\n     $body = $raw -replace '(?s)^\\s*---.*?---\\s*', ''\n     # Drop an auto-generated container-bootstrap preamble, if present:\n     # everything up to and including the first '---' horizontal rule that\n     # the generator emits after the preamble table.\n     if ($body -match '(?s)^\\s*#\\s*Container image bootstrap.*?\\r?\\n---\\r?\\n') {\n       $body = $body -replace '(?s)^\\s*#\\s*Container image bootstrap.*?\\r?\\n---\\r?\\n', ''\n     }\n     return $body.Trim()\n   }\n   ```\n\n   > **CRLF gotcha (verified in a real run).** If you write these regexes\n   > with a bare `\\n---\\n` instead of `\\r?\\n---\\r?\\n`, a CRLF-terminated\n   > companion produces a **tiny** instructions body — in one run just the\n   > appended \"## Tool execution\" note (~369 chars) instead of the real\n   > ~13k-char prompt. After extraction, **sanity-check the length**: a\n   > tool-bearing agent's instructions should be thousands of characters.\n   > If `Get-AgentMdInstructions` returns only a few hundred chars, the\n   > CRLF bug bit you — fix the regex and re-extract before `UpsertAgent`.\n\n   **The `.agent.md` companion is also the source of truth for `name` and\n   `description`** — not just `instructions`. Use this helper to read a\n   scalar value from the companion's YAML frontmatter (the block between the\n   leading `---` fences). It handles both inline (`description: \"...\"`) and\n   the escaped double-quoted form the Step 6 generator emits. Apply it for\n   **both** tool-bearing and toolless promotes so the deployed Discovery\n   agent's `name` \u002F `description` match exactly what the user tuned locally.\n\n   ```pwsh\n   # Read a single scalar key from the .agent.md YAML frontmatter block.\n   # CRLF-safe. Returns '' if the key is absent.\n   function Get-AgentMdFrontmatterValue([string]$AgentMdPath, [string]$Key) {\n     $raw = Get-Content $AgentMdPath -Raw\n     # Isolate the leading frontmatter block ( --- ... --- ).\n     if ($raw -notmatch '(?s)^\\s*---\\r?\\n(.*?)\\r?\\n---\\r?\\n') { return '' }\n     $fm = $matches[1]\n     foreach ($line in ($fm -split \"`r?`n\")) {\n       if ($line -match (\"^\" + [regex]::Escape($Key) + \":\\s*(.+)$\")) {\n         $v = $matches[1].Trim()\n         # Strip surrounding quotes and unescape \\\" and \\\\ from the\n         # double-quoted frontmatter the generator writes.\n         if ($v.StartsWith('\"') -and $v.EndsWith('\"') -and $v.Length -ge 2) {\n           $v = $v.Substring(1, $v.Length - 2) -replace '\\\\\"', '\"' -replace '\\\\\\\\', '\\'\n         } elseif ($v.StartsWith(\"'\") -and $v.EndsWith(\"'\") -and $v.Length -ge 2) {\n           $v = $v.Substring(1, $v.Length - 2)\n         }\n         return $v.Trim()\n       }\n     }\n     return ''\n   }\n   ```\n\n##### Rewriting local container references for tool-bearing promotes\n\nA **tool-bearing** local agent's `.agent.md` companion (and, in rare\nhand-edited cases, its `agent.yaml#instructions`) can reference the tool as\na **local** Podman\u002FDocker container image — e.g. \"build `\u003Ctool>:latest` from\n`discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>`\", \"`podman image inspect`\",\n\"`docker build -t ...`\". Those references are **local-only** and are\nmeaningless in the cloud, where the tool runs as a deployed\n`Microsoft.Discovery\u002Ftools` ARM resource backed by an image in the\nworkspace's Azure Container Registry.\n\nWhen promoting a tool-bearing agent (Step 7), **do not** deploy the local\ncontainer-runtime wording. Instead:\n\n1. Strip the auto-generated bootstrap preamble (already done by\n   `Get-AgentMdInstructions`).\n2. Scrub any **residual** local-runtime references that survive in the body\n   (stray `podman`\u002F`docker` `build|pull|push|image inspect` lines, or lines\n   that point at a `discovery_catalog\u002F...\u002Ftools\u002F...` build context).\n3. Rewrite the tool reference so the cloud instructions point at the\n   **Discovery tool** by name — the one found under\n   `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002F` and registered as an ARM\n   resource in Step 7c\u002F7d — not at any local image tag or build context.\n\nUse this helper (defined alongside `Get-AgentMdInstructions`) to produce\nthe cloud instructions for tool-bearing agents:\n\n```pwsh\n# Rewrite local Podman\u002FDocker container references in a tool-bearing agent's\n# promoted instructions so the cloud prompt references the deployed Discovery\n# tool(s) instead of a local image tag \u002F build context.\nfunction Convert-PromoteInstructionsForTool {\n  param(\n    [Parameter(Mandatory)][string]$Instructions,\n    [Parameter(Mandatory)][string[]]$ToolNames\n  )\n  $text = $Instructions\n\n  # 1. Remove any lingering container-runtime bootstrap section (defense in\n  #    depth — Get-AgentMdInstructions normally already removed it).\n  #    CRLF-SAFE: use `\\r?\\n---\\r?\\n` for the horizontal-rule delimiter.\n  #    A bare `\\n---\\n` never matches a CRLF companion, so the `|\\z`\n  #    fallback would then swallow the ENTIRE body (deleting the real\n  #    prompt and leaving only the appended note). Never use `\\n---\\n` here.\n  $text = $text -replace '(?s)#\\s*Container image bootstrap.*?(\\r?\\n---\\r?\\n|\\z)', ''\n\n  # 2. Drop stray local-runtime instruction lines that reference building \u002F\n  #    inspecting \u002F pulling \u002F pushing a local image or a local build context.\n  $lines = $text -split \"`r?`n\"\n  $kept = foreach ($ln in $lines) {\n    if ($ln -match '(?i)\\b(podman|docker)\\b.*\\b(build|pull|push|image\\s+inspect|info)\\b') { continue }\n    if ($ln -match '(?i)discovery_catalog\u002F[^`\\s]+\u002Ftools\u002F') { continue }\n    if ($ln -match '(?i)\u003Ctool>:latest|:latest\\b.*build\\s+context') { continue }\n    $ln\n  }\n  $text = ($kept -join \"`n\")\n\n  # 3. Ensure the cloud prompt explicitly references the Discovery tool(s) by\n  #    name rather than any local image. Appended once, only if not already\n  #    present.\n  $toolList = ($ToolNames | Sort-Object -Unique) -join ', '\n  if ($ToolNames.Count -gt 0 -and $text -notmatch '(?i)Discovery tool\\b') {\n    $note = @(\n      ''\n      '## Tool execution (Microsoft Discovery)'\n      ''\n      \"This agent runs in Microsoft Discovery. Its tool(s) ($toolList) are provided as deployed Discovery tools whose container images live in the workspace's Azure Container Registry — invoke them as bound Discovery tools. Do NOT build, pull, or inspect any local Podman\u002FDocker image; there is no local container runtime in the cloud.\"\n    ) -join \"`n\"\n    $text = $text.TrimEnd() + \"`n\" + $note\n  }\n\n  # Collapse any 3+ blank lines left by the scrub down to a single blank line.\n  $text = $text -replace \"(\\r?\\n){3,}\", \"`n`n\"\n  return $text.Trim()\n}\n```\n\n#### 4f. Local runtime readiness (conditional)\n\nRun this sub-step **only when `$deployTarget == 'Local'`** and only after the\nagent selection in 4e has resolved to at least one agent in `$selected`.\n\nGoal: determine whether Podman and\u002For Docker are available for local,\nlazy image bootstrap done later by generated `.agent.md` companions.\n\nDetection commands:\n\n```pwsh\n$hasPodman = $false\n$hasDocker = $false\ntry { & podman --version *> $null; if ($LASTEXITCODE -eq 0) { $hasPodman = $true } } catch {}\ntry { & docker --version *> $null; if ($LASTEXITCODE -eq 0) { $hasDocker = $true } } catch {}\n```\n\nDecision flow:\n\n1. If **both** are installed, ask once which runtime the user prefers for\n  local container workflows (`podman` or `docker`). Recommended default:\n  `podman`.\n2. If only one is installed, set that as `$localContainerRuntimePreference`\n  automatically (no prompt).\n3. If neither is installed, ask once whether to install Podman automatically.\n  - If **yes**, install Podman, then re-check `podman --version`:\n\n    ```pwsh\n    winget install --id RedHat.Podman --accept-source-agreements --accept-package-agreements\n    ```\n\n    If install succeeds, set `$localContainerRuntimePreference = 'podman'`.\n  - If **no**, continue, but print a clear notice that agents with\n    container-based tools cannot run until Podman or Docker is installed.\n\nThis step must **not** run any image builds; it only selects\u002Finstalls runtime\nprerequisites for future lazy bootstrap.\n\n#### 4d. Discovery workspace + project selection (conditional)\n\nRun this sub-step whenever `$deployToCloud` is true (`$deployTarget` is\n`Discovery` or `LocalToDiscovery`). Skip entirely for the `Local` target.\n\nExecute the full login \u002F MCP install \u002F tenant + subscription pick \u002F\nworkspace pick \u002F project pick \u002F existing-agent listing \u002F confirmation\nworkflow documented in **Step 7a** (sub-steps 1 through 9). All of Step 7a\nruns here in Step 4d - it has been moved up so the destination is locked\nin before the user is asked which agents to add.\n\nAfter 4d completes you have:\n\n- A working proxy at `.vscode\u002Fdiscovery-mcp-proxy.ps1` (sanity-checked via `Invoke-DiscoveryMcp` — not via VS Code's MCP runtime).\n- An active `az` CLI session pointed at the correct tenant + subscription.\n- `$discoveryTenantId`, `$discoverySubscriptionId`, `$discoveryRg`,\n  `$discoveryWorkspace`, and `$discoveryProject` persisted for Steps 7c\\u20137e.\n- `$existingAgentNames` - the set of agent names already in\n  `$discoveryProject`, printed to chat so the user can spot collisions\n  **before** picking what to add in 4e.\n\nIf the user cancels at the 7a.9 confirmation prompt, stop the workflow\ncleanly - do **not** proceed to 4e, do **not** touch ACR or Foundry, and\ndo **not** copy any agent folders.\n\nWhen Step 7 runs later, **do not** re-prompt for workspace\u002Fproject. Skip\nstraight to Step 7b (Azure MCP probe) and Step 7c (tool ARM pre-flight)\nusing the values persisted here.\n\n#### 4e. Ask which agents to add\n\nTwo-phase prompt flow (`vscode_askQuestions` called up to twice). This is\nthe agent-selection question batch; deployment target and (when applicable)\nworkspace\u002Fproject are already resolved.\n\n**Phase 1 - selection mode** (one question):\n\n```\nheader: \"selection-mode\"\nquestion: \"How do you want to choose which agents to add?\"\noptions:\n  - \"All agents\"      (recommended)\n  - \"Specific agents\" (user picks individual agents in phase 2)\n  - \"By group\"        (user picks one or more tag groups in phase 2)\n```\n\n**Phase 2 - selection value** (skip when `selection-mode == 'All agents'`).\nThe options list is **scoped to the phase-1 answer**:\n\n| selection-mode    | Phase 2 options                                                                  |\n|-------------------|----------------------------------------------------------------------------------|\n| `All agents`      | (skip phase 2)                                                                   |\n| `Specific agents` | Individual agents only - `[agent] \u003Cfolder>` entries, sorted alphabetically.   |\n| `By group`        | Groups only - `[group] \u003Cname> (N)` and `[lightweight] no-container-tools (N)` entries. |\n\n```\nheader: \"selection-value\"\nquestion: \"Pick one or more \u003Cagents | groups>.\"\nmultiSelect: true\noptions: \u003Cscoped to the phase-1 mode>\n```\n\n**Specific agents mode:** every entry in `$catalog`, label formatted as\n`\"[agent] \u003Cfolder>\"` with the agent's short description in the option's\n`description` field. **Do not include any `[group]` or `[lightweight]`\nentries** in this mode.\n\n**By group mode:** every key in `$groups` plus the synthetic\n`[lightweight] no-container-tools` entry, label formatted as\n`\"[group] \u003Cname> (N agents)\"`. **The option's `description` field MUST\nlist the member agents.** Do not include individual `[agent]` entries\nin this mode.\n\n**Discovery collision hint (only when `$deployToCloud` is true — `$deployTarget` is `Discovery` or `LocalToDiscovery`).**\nFor each option whose folder name appears in `$existingAgentNames` (from\n4d), prepend `[ALREADY IN PROJECT] ` to the option's `description` field\nso the user knows re-selecting it will trigger an `UpsertAgent` update in\nthe chosen project. Do not block the choice - just surface it.\n\n**Local collision hint (only when `$deployTarget == 'Local'`).** For each\noption whose folder name appears in `$existingLocalAgents` (the set of\n`.github\u002Fagents\u002F\u003Cname>.agent.md` stems from Step 1), prepend\n`[ALREADY ADDED LOCALLY] ` to the option's `description` field so the user\nknows re-selecting it will overwrite the existing `.agent.md` companion in\nplace. Do not block the choice - just surface it. Always derive this hint\nfrom `.github\u002Fagents\u002F`, never from `discovery_catalog\u002F` (the latter is\nrefreshed unconditionally in Step 5 and therefore can't distinguish new vs\nalready-installed agents).\n\n#### Group member display rule\n\nEvery group option presented in phase 2 **must include the names of the\nagents in that group** in the option's `description` field. This is how the\nuser knows what's actually in `drug-discovery`, `cheminformatics`, etc.\nwithout needing to ask back.\n\nFormatting rules for the description:\n\n- Comma-separated, alphabetically sorted folder names.\n- Truncate to ~120 characters and append `, \\u2026(+N more)` if the full list is\n  longer. Example: `\"aizynthfinder, autodock, bindingdb, boltztwo, retrochimera, tamgen\"`.\n- For **Lightweight (no container tools)**, always list the full member set - it's\n  small by definition.\n\nFilter the group list shown to the user to **tags with \\u2265 2 agents** plus the\nsynthetic `Lightweight (no container tools)` entry. Singleton tags add noise and the\nagent itself is already pickable in `Specific agents` mode.\n\nSort the group options by member count (descending), so the broadest groups\nappear first.\n\n#### Resolve the final selection\n\nThen resolve the final set of folders to add:\n\n- Mode = **All agents** \\u2192 `$selected = $catalog.Folder`\n- Mode = **Specific agents** \\u2192 for each phase-2 answer starting with\n  `[agent] `, strip the prefix and look it up in `$catalog.Folder`.\n- Mode = **By group** \\u2192 for each phase-2 answer starting with `[group] ` or\n  `[lightweight] `, strip the prefix and union the folders in `$groups[$name]`\n  (or the lightweight set).\n\nUnknown phase-2 entries (typos, freeform): treat as agent folder names and\nwarn if they don't resolve. If `$selected` is empty after resolution, ask\nphase 2 again once; if still empty, stop and report.\n\nPrint the resolved selection back to chat before proceeding:\n\n```\nWill add 7 agent(s): pubchem, rdkit, online-researcher, ...\n```\n\n### Step 5 — Refresh selected agents in `discovery_catalog\u002F`\n\n> **Skip this entire step when `$deployTarget == 'LocalToDiscovery'`**\n> (`$sourceMode == 'Local'`). The promote target treats the existing local\n> `discovery_catalog\u002F\u003Cname>\u002F` folder as the source of truth; overwriting it\n> with upstream would discard the local edits being promoted. Jump straight\n> to Step 7.\n\n**Always refresh from upstream (Upstream source mode only).** For every folder\nin `$selected`, replace `discovery_catalog\u002F\u003Cname>\u002F` with the upstream copy from\n`agents\u002F\u003Cname>\u002F`. This guarantees the local catalog reflects the\nlatest upstream content (bug fixes, new tools, updated prompts) and that\nany change to the agent list is surfaced. **Do not prompt the user before\noverwriting** — the `discovery_catalog\u002F` tree is a managed mirror, not\nuser-authored content.\n\n```pwsh\n$srcRoot = Join-Path $work 'agents'\n$dstRoot = Join-Path $workspaceRoot 'discovery_catalog'\n\n$createdFolders   = @()   # folder did not exist locally — created fresh\n$refreshedFolders = @()   # folder existed locally — overwritten with upstream\n$skipped          = @()   # name not in upstream (folder may have been removed)\n\n$selected | ForEach-Object {\n    $name = $_\n    $src  = Join-Path $srcRoot $name\n    $dst  = Join-Path $dstRoot $name\n    if (-not (Test-Path $src)) { $skipped += \"$name (not in upstream)\"; return }\n    $existed = Test-Path $dst\n    if ($existed) {\n        # Always replace in full so renamed\u002Fremoved files don't linger.\n        Remove-Item -Recurse -Force $dst\n    }\n    Copy-Item -Recurse -Force $src $dst\n    if ($existed) { $refreshedFolders += $name } else { $createdFolders += $name }\n}\n```\n\n**Rules:**\n\n- Always refresh `discovery_catalog\u002F\u003Cname>\u002F` from upstream — no overwrite\n  prompt. Stale folders silently mask upstream changes.\n- Replace each refreshed folder in full (delete then copy) so files removed\n  upstream don't linger locally.\n- Never touch `discovery_catalog\u002F\u003Cname>\u002F` folders that are **not** in\n  `$selected` — leave them as-is. Removal of unselected agents is out of\n  scope for this step.\n- Preserve file casing exactly as upstream (Windows is case-insensitive but the\n  repo metadata is case-sensitive on Linux containers).\n- Do **not** rename `tools\u002F\u003CTool>\u002F` — the directory name is referenced by\n  `metadata.yaml#associated_tools` and `agent.yaml#discoveryExtensions.tools`.\n- The \"already added locally\" determination for the summary (Step 8) and\n  for the Step 4e Local collision hint comes from\n  `.github\u002Fagents\u002F\u003Cname>.agent.md` presence (captured in Step 1 as\n  `$existingLocalAgents`), **not** from this folder. Two distinct concepts:\n  - `$createdFolders` \u002F `$refreshedFolders` — state of `discovery_catalog\u002F`\n  - `$existingLocalAgents`               — state of `.github\u002Fagents\u002F`\n\n### Step 6 — Generate Copilot agent companions\n\nFor every folder in `$selected` (that successfully copied or was already\npresent locally), emit a sibling Copilot agent file at\n`.github\u002Fagents\u002F\u003Cname>.agent.md`. This is what makes each Discovery agent\ninvocable as a Copilot subagent via `runSubagent`.\n\nDo **not** regenerate `.agent.md` files for agents the user did not select in\nStep 4 — leaving those files untouched preserves prior selections and avoids\nsurprising the user.\n\nThe Copilot agent file is a markdown file with YAML frontmatter, distinct from\nthe Discovery `agent.yaml`. Map fields as follows:\n\n| Copilot frontmatter | Source |\n|---|---|\n| `name` | `discovery_catalog\u002F\u003Cname>\u002Fagent.yaml#name` (fallback: folder name) |\n| `description` | `agent.yaml#description` — first paragraph, collapsed to one line, quoted |\n| `argument-hint` | `\"Query or input for the \u003Cname> agent\"` |\n| `user-invocable` | `true` |\n\nThe **body** of the `.agent.md` file is composed of two parts, in this order:\n\n1. A **container runtime bootstrap preamble** (generated by this skill, see\n  template\n   below) listing the exact image tags and Dockerfile paths for every tool\n   under `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F`. The preamble instructs the agent\n  to verify each image exists locally before invoking the tool, and to build\n  it from the matching Dockerfile only if missing. Runtime order is fixed:\n  try Podman first, then Docker if Podman is unavailable or fails.\n2. The verbatim contents of `agent.yaml#instructions` (the Discovery prompt\n   block). Do NOT translate, summarize, or re-wrap it — Discovery agents are\n   tuned against that exact text.\n\nDo NOT include a `tools:` frontmatter key. Discovery tool IDs (the `toolId`\nplaceholders inside `discoveryExtensions.tools`) don't map to Copilot tool\nnames, and adding the wrong list silently disables tools.\n\n#### Container runtime bootstrap preamble template\n\nFor an agent whose folder is `discovery_catalog\u002F\u003Cname>\u002F` with tool\nsubdirectories `tools\u002F\u003CTool1>\u002F`, `tools\u002F\u003CTool2>\u002F`, etc., the preamble looks\nlike this (substitute the agent name and the actual tool rows):\n\n```markdown\n# Container image bootstrap (auto-generated by add-agent-from-catalog)\n\nThis agent depends on local container images. **Before invoking any\ntool, you MUST verify each image exists and build it only if it is missing.**\nDo not rebuild images that are already present — builds are expensive.\n\n| Image tag | Build context |\n|---|---|\n| `\u003Ctool1>:latest` | `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool1>` |\n| `\u003Ctool2>:latest` | `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool2>` |\n\nProcedure for each image (Podman first, Docker fallback):\n\n1. Try Podman first:\n  - `podman image inspect \u003Ctag>`; if exit code is `0`, the image exists —\n    **skip the build**.\n  - If missing, confirm `podman info` succeeds, then run\n    `podman build -t \u003Ctag> \u003Cbuild-context>`.\n2. If Podman is unavailable or fails, fall back to Docker:\n  - `docker image inspect \u003Ctag>`; if exit code is `0`, the image exists —\n    **skip the build**.\n  - If missing, confirm `docker info` succeeds, then run\n    `docker build -t \u003Ctag> \u003Cbuild-context>`.\n3. If neither runtime is available, stop and report that Podman or Docker\n  must be installed before container-based tools can run.\n4. Never `podman push` \u002F `docker push` and never touch any registry — this bootstrap is\n   strictly local.\n\nDo this lazily — only when a tool is actually about to be invoked, not on\nevery turn. After a successful build, the image will satisfy the\ninspect check on subsequent runs.\n```\n\nWhen an agent has **no** `tools\u002F*\u002FDockerfile` (rare — e.g. pure LLM agents like\n`bookshelf-researcher`, `online-researcher`), omit the preamble entirely.\n\n#### Generation script\n\nUse the `powershell-yaml` module if available, otherwise parse with a\nregex-lite reader that extracts only the three fields we need (`name`,\n`description`, `instructions`). Always overwrite existing `.agent.md` files —\nthey are derived artifacts, not user-edited.\n\n**Mandatory hardening from observed local runs:**\n\n- Materialize the generation logic into a temp `.ps1` file and run it with\n  `pwsh -NoProfile -File`; do not paste this multi-line script directly into\n  the shared terminal.\n- For `.github\u002Fagents\u002F*.agent.md` collision detection, strip the full\n  `.agent.md` suffix. Never use `.BaseName`, because `pubchem.agent.md`\n  becomes `pubchem.agent`.\n- Treat YAML block-scalar markers (`|`, `|-`, `>`, `>-`) as \"no inline value\"\n  and then read the indented block. Otherwise generated frontmatter can become\n  `description: \"|\"` instead of the real description.\n- Write generated `.agent.md` files with a `FileStream` opened with\n  `FileShare.ReadWrite`. VS Code and the extension host may briefly read these\n  files during generation; plain `Set-Content` can fail with \"file is being\n  used by another process\". A rerun is safe, but the shared writer avoids most\n  transient locks.\n\n```pwsh\n$agentsDir = Join-Path $workspaceRoot '.github\u002Fagents'\nNew-Item -ItemType Directory -Force -Path $agentsDir | Out-Null\n\nfunction Get-SimpleYamlValue([string[]]$Lines, [string]$Key) {\n  foreach ($line in $Lines) {\n    if ($line -match (\"^\" + [regex]::Escape($Key) + \":\\s*(.+)$\")) {\n      $value = $matches[1].Trim().Trim('\"').Trim(\"'\")\n      if ($value -match '^[>|][-+]?$') { return '' }\n      return $value\n    }\n  }\n  return ''\n}\n\nfunction Get-YamlBlock([string[]]$Lines, [string]$Key) {\n  $start = -1\n  for ($i = 0; $i -lt $Lines.Count; $i++) {\n    if ($Lines[$i] -match (\"^\" + [regex]::Escape($Key) + \":\\s*[>|][-+]?\\s*$\")) {\n      $start = $i + 1\n      break\n    }\n  }\n  if ($start -lt 0) { return '' }\n\n  $end = $Lines.Count - 1\n  for ($i = $start; $i -lt $Lines.Count; $i++) {\n    if ($Lines[$i] -match '^[A-Za-z0-9_-]+:\\s*') {\n      $end = $i - 1\n      break\n    }\n  }\n  if ($end -lt $start) { return '' }\n\n  $block = @($Lines[$start..$end])\n  $nonBlank = $block | Where-Object { $_ -match '\\S' }\n  $minIndent = 0\n  if ($nonBlank.Count -gt 0) {\n    $minIndent = ($nonBlank | ForEach-Object {\n      if ($_ -match '^(\\s*)') { $matches[1].Length }\n    } | Measure-Object -Minimum).Minimum\n  }\n  $out = $block | ForEach-Object {\n    if ($_.Length -ge $minIndent) { $_.Substring($minIndent) } else { $_ }\n  }\n  return (($out -join \"`n\").TrimEnd())\n}\n\nfunction Escape-FrontmatterDoubleQuoted([string]$Value) {\n  if ($null -eq $Value) { return '' }\n  return (($Value.Replace('\\', '\\\\').Replace('\"', '\\\"')) -replace \"`r?`n\", ' ')\n}\n\nfunction Write-GeneratedText([string]$Path, [string]$Text) {\n  $encoding = [System.Text.UTF8Encoding]::new($false)\n  $stream = [System.IO.File]::Open(\n    $Path,\n    [System.IO.FileMode]::Create,\n    [System.IO.FileAccess]::Write,\n    [System.IO.FileShare]::ReadWrite)\n  try {\n    $writer = [System.IO.StreamWriter]::new($stream, $encoding)\n    try { $writer.Write($Text) } finally { $writer.Dispose() }\n  } finally {\n    $stream.Dispose()\n  }\n}\n\n$existingLocalAgents = @{}\nGet-ChildItem $agentsDir -Filter '*.agent.md' -File -ErrorAction SilentlyContinue | ForEach-Object {\n  $stem = $_.Name -replace '\\.agent\\.md$', ''\n  $existingLocalAgents[$stem] = $true\n}\n\n$generated = @(); $skipped = @()\n$selected | ForEach-Object {\n    $folder    = $_\n    $agentDir  = Join-Path $workspaceRoot \"discovery_catalog\u002F$folder\"\n    if (-not (Test-Path $agentDir)) { $skipped += \"$folder (folder missing)\"; return }\n    $agentYaml = Join-Path $agentDir 'agent.yaml'\n    if (-not (Test-Path $agentYaml)) { $skipped += \"$folder (no agent.yaml)\"; return }\n\n    $lines = @(Get-Content $agentYaml)\n\n    $name = Get-SimpleYamlValue $lines 'name'\n    if ([string]::IsNullOrWhiteSpace($name)) { $name = $folder }\n\n    $desc = Get-SimpleYamlValue $lines 'description'\n    if ([string]::IsNullOrWhiteSpace($desc)) {\n      $descBlock = Get-YamlBlock $lines 'description'\n      $desc = ($descBlock -split \"`n\" | Where-Object { $_.Trim() } | Select-Object -First 1).Trim()\n    }\n    if ([string]::IsNullOrWhiteSpace($desc)) { $desc = \"Discovery agent: $folder\" }\n    $descEsc = Escape-FrontmatterDoubleQuoted $desc\n\n    $instructions = Get-YamlBlock $lines 'instructions'\n    if ([string]::IsNullOrWhiteSpace($instructions)) {\n      $instructions = '(No instructions defined in agent.yaml.)'\n      $skipped += \"$folder (empty instructions)\"\n    }\n\n    # Enumerate tool images for the container-runtime bootstrap preamble.\n    $toolRows = @()\n    $toolsRoot = Join-Path $agentDir 'tools'\n    if (Test-Path $toolsRoot) {\n        Get-ChildItem $toolsRoot -Directory | ForEach-Object {\n            if (Test-Path (Join-Path $_.FullName 'Dockerfile')) {\n                $tag = ($_.Name).ToLower() + ':latest'\n                $ctx = \"discovery_catalog\u002F$folder\u002Ftools\u002F$($_.Name)\"\n                $toolRows += \"| ``$tag`` | ``$ctx`` |\"\n            }\n        }\n    }\n\n    $preamble = ''\n    if ($toolRows.Count -gt 0) {\n        $preamble = @(\n            '# Container image bootstrap (auto-generated by add-agent-from-catalog)'\n            ''\n            'This agent depends on local container images. **Before invoking any tool, you MUST verify each image exists and build it only if it is missing.** Do not rebuild images that are already present.'\n            ''\n            '| Image tag | Build context |'\n            '|---|---|'\n        ) + $toolRows + @(\n            ''\n            'For each image (Podman first, Docker fallback):'\n            ''\n            '1. Try Podman first: run `podman image inspect \u003Ctag>`. If exit code is `0`, the image exists — **skip the build**. If missing, confirm `podman info` succeeds, then run `podman build -t \u003Ctag> \u003Cbuild-context>`.'\n            '2. If Podman is unavailable or fails, fall back to Docker: run `docker image inspect \u003Ctag>`. If exit code is `0`, the image exists — **skip the build**. If missing, confirm `docker info` succeeds, then run `docker build -t \u003Ctag> \u003Cbuild-context>`.'\n            '3. If neither runtime is available, stop and report that Podman or Docker must be installed before container-based tools can run.'\n            '4. Never `podman push` \u002F `docker push` and never touch a registry — bootstrap is strictly local.'\n            ''\n            'Do this lazily — only when a tool is actually about to be invoked.'\n            ''\n            '---'\n            ''\n        ) -join \"`n\"\n    }\n\n    $frontmatter = @(\n        '---'\n        \"name: $name\"\n        \"description: `\"$descEsc`\"\"\n        \"argument-hint: `\"Query or input for the $name agent`\"\"\n        'user-invocable: true'\n        '---'\n        ''\n    ) -join \"`n\"\n\n    $out = Join-Path $agentsDir \"$folder.agent.md\"\n    Write-GeneratedText -Path $out -Text ($frontmatter + $preamble + $instructions + \"`n\")\n    $generated += $folder\n}\n```\n\nRules:\n\n- Use the **folder name** as the `.agent.md` filename (e.g.\n  `discovery_catalog\u002Fpubchem\u002F` → `.github\u002Fagents\u002Fpubchem.agent.md`). This\n  guarantees no collisions even if two `agent.yaml` files share a `name:` field.\n- Always **overwrite** existing `.agent.md` files. They are derived, not\n  hand-authored. Do NOT prompt the user about overwrites in `.github\u002Fagents\u002F`.\n- Preserve hand-authored Copilot agents (`batteries-included.agent.md`,\n  `bookshelf-researcher.agent.md`, `project-setup-orchestrator.agent.md`) by\n  only writing files whose stem matches a `discovery_catalog\u002F\u003Cname>\u002F` folder.\n- If `agent.yaml#instructions` is missing or empty, still emit the frontmatter\n  with a body of `(No instructions defined in agent.yaml.)` and record the\n  agent in the summary's `skipped`\u002F`degraded` list.\n- Omit the container-runtime bootstrap preamble entirely for agents that have no\n  `tools\u002F*\u002FDockerfile` upstream.\n- Do not embed any local `podman build` \u002F `docker build` calls in this skill\n  itself — the skill must never invoke local image builds.\n\n### Step 7 — Deploy to Microsoft Discovery + Azure (conditional)\n\nRun this step when `$deployToCloud` is true — i.e. `$deployTarget` from\nStep 4c is either `Discovery` (upstream-sourced) or `LocalToDiscovery`\n(promoted from the local app). For each folder in `$selected`, this step\npushes the agent's tool container image(s) to Azure Container Registry and\nregisters the agent in the Microsoft Discovery agent registry as a hosted\nprompt agent.\n\n**Source difference for `LocalToDiscovery`:** the local workspace is the\nsource — nothing is re-fetched from upstream. Each selected agent falls into\none of two buckets (classified in Step 4c.LTD via\n`$agentHasCatalogFolder`):\n\n- **Tool-bearing** (`discovery_catalog\u002F\u003Cname>\u002F` exists) — the tool subtree\n  files (`metadata.yaml`, `tools\u002F\u003CTool>\u002FDockerfile`, `tool.yaml`) and the\n  `name` \u002F `description` fields come from that local folder. The\n  **`instructions`** come from the `.github\u002Fagents\u002F\u003Cname>.agent.md`\n  companion (via `Get-AgentMdInstructions`), **not** from `agent.yaml`\n  (see Step 7e.1). Tool images are pushed from the local build context \u002F\n  locally-built image (see Step 7d.LTD). Runs the full 7c → 7d → 7e path.\n- **Toolless** (no `discovery_catalog\u002F\u003Cname>\u002F` folder) — the agent has **no\n  container tool**. Skip 7c and 7d entirely (nothing to pre-flight, build,\n  or bind). Source `name` \u002F `description` \u002F `instructions` from the\n  `.github\u002Fagents\u002F\u003Cname>.agent.md` companion (see the\n  `Get-AgentMdInstructions` helper in Step 4c.LTD) and go straight to 7e\n  with an empty `toolIds`.\n\nEverything else — workspace\u002Fproject pick (7a), MCP probe (7b),\n`UpsertAgent` + `GetAgent` poll (7e) — is identical for both buckets.\n\n**Workspace + project were already chosen in Step 4d.** Do **not** re-prompt\nfor tenant, subscription, workspace, or project here. Reuse\n`$discoveryTenantId`, `$discoverySubscriptionId`, `$discoveryRg`,\n`$discoveryWorkspace`, `$discoveryProject`, and `$existingAgentNames`\npersisted by 4d. Step 7a below documents the workspace\u002Fproject picker\n**only** so 4d has something concrete to invoke; in normal flow, 7a never\nruns from inside Step 7 — it has already run as part of 4d.\n\n**Prefer MCP servers over raw CLI commands.** Use the Discovery MCP and Azure\nMCP whenever they are available; only fall back to terminal commands when the\nrequired MCP capability is not present.\n\n#### 7a. Discovery login, workspace + project selection, existing-agent listing\n\n> **Where this runs.** In the normal flow, 7a is invoked **from Step 4d**\n> (before the agent picker), not from inside Step 7. The sub-section\n> remains under Step 7 because it is part of the Discovery deploy machinery;\n> Step 4d explicitly delegates to it. If you find yourself entering Step 7\n> without `$discoveryWorkspace` \u002F `$discoveryProject` set, you skipped 4d —\n> go back and run it before continuing.\n\nBefore asking for Azure resource names, the user must be signed in to\nMicrosoft Discovery and must pick the Discovery **workspace** and **project**\nthe new agents will be deployed into. Always show the currently-registered\nagents in the chosen project **before** Step 7c pre-flights the tool ARMs\nand (if needed) Step 7c.2 prompts for ACR\u002FRG, so the user can spot\nduplicates and abort early.\n\n1. **Install the proxy (single extraction, no probe).** The Discovery MCP\n  server is the Microsoft-hosted remote streamable-HTTP endpoint at\n  `https:\u002F\u002Fmcp.discovery.azure.com\u002Fmcp`. The skill embeds the PowerShell\n  stdio proxy and invocation helper at the end of this `SKILL.md`; the\n  bootstrap below extracts them into `.vscode\u002F` so PowerShell and VS Code\n  can execute normal `.ps1` files. **Always materialize** the scripts into\n  `.vscode\u002F` at the start of Step 4d — do NOT probe for it first, do NOT depend on VS Code's MCP\n   runtime ever surfacing `mcp_microsoft-dis_*` deferred tools in this\n   session:\n\n   ```pwsh\n   $skillDir = '\u003Cabsolute path to add-agent-from catalog folder>'\n   New-Item -ItemType Directory -Force -Path \"$workspaceRoot\\.vscode\" | Out-Null\n  $skillPath = Join-Path $skillDir 'SKILL.md'\n  $skillText = Get-Content $skillPath -Raw\n  function Write-EmbeddedSkillScript([string]$BlockId, [string]$Destination) {\n       $begin = \"\u003C!-- BEGIN:$BlockId -->\"\n       $end = \"\u003C!-- END:$BlockId -->\"\n       $start = $skillText.IndexOf($begin)\n       if ($start -lt 0) { throw \"Embedded script block '$BlockId' not found in $skillPath\" }\n       $contentStart = $start + $begin.Length\n       $stop = $skillText.IndexOf($end, $contentStart)\n       if ($stop -lt 0) { throw \"Embedded script block '$BlockId' has no end marker in $skillPath\" }\n       $block = $skillText.Substring($contentStart, $stop - $contentStart).Trim()\n       $lines = @($block -split \"`r?`n\")\n       if ($lines.Count -lt 3 -or $lines[0] -notmatch '^```powershell\\s*$' -or $lines[-1] -notmatch '^```\\s*$') {\n           throw \"Embedded script block '$BlockId' must be wrapped in a powershell fenced code block.\"\n       }\n       $content = (($lines[1..($lines.Count - 2)]) -join \"`r`n\") + \"`r`n\"\n       Set-Content -Path $Destination -Value $content -Encoding UTF8\n   }\n   Write-EmbeddedSkillScript 'embedded-discovery-mcp-proxy.ps1' \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\"\n   Write-EmbeddedSkillScript 'embedded-Invoke-DiscoveryMcp.ps1' \"$workspaceRoot\\.vscode\\Invoke-DiscoveryMcp.ps1\"\n   ```\n\n   That is the entire MCP install. From here on, **every** MCP call goes\n  through `Invoke-DiscoveryMcp` (extracted helper) → proxy → HTTPS. See\n   the \"Scripted MCP invocation\" section near the top of this skill for\n   the canonical call pattern.\n\n   The legacy `agents action=registry.list` probe, the mcp.json HTTP\n   server entry, the `workbench.action.mcp.restart` ritual, and the\n   `workbench.action.mcp.listServers` fallback are **all optional** and\n   only benefit the user's future interactive VS Code sessions. They do\n   nothing for this skill's run — do not waste turns on them. If you\n   still want to write `.vscode\u002Fmcp.json` for the user's convenience,\n   do it once with the merge-safe script in 7a.2 below and **do not**\n   block on the restart or any tool surfacing.\n\n   Sanity-check the proxy is reachable in one quick call:\n\n   ```pwsh\n  . \"$workspaceRoot\\.vscode\\Invoke-DiscoveryMcp.ps1\"\n   $r = Invoke-DiscoveryMcp -ProxyPath \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\" -Calls @(@{ name='Ping'; args=@{} })\n   if (-not $r['2']) { throw 'Proxy not responding — check az login and PowerShell 7+.' }\n   ```\n\n2. **(Optional, courtesy)** Register the proxy in `.vscode\u002Fmcp.json` so\n   it shows up in the user's MCP server list for future interactive\n   sessions. This is a write-once, fire-and-forget step — the rest of\n   the skill does NOT depend on VS Code loading those tools.\n\n      **`.vscode\u002Fdiscovery-mcp-proxy.ps1`** is the canonical proxy\n      implementation generated from this `SKILL.md`. The embedded block\n      below is authoritative — extract it verbatim into new workspaces; do\n      not reimplement it inline. Requirements: PowerShell 7+ (uses\n      `Invoke-WebRequest -SkipHttpErrorCheck`) and `az` CLI on PATH with\n      an active session.\n\n      **`.vscode\u002Fmcp.json`** — register the proxy as a stdio server:\n      ```json\n      {\n        \"servers\": {\n          \"microsoft-discovery\": {\n            \"type\": \"stdio\",\n            \"command\": \"pwsh\",\n            \"args\": [\n              \"-NoProfile\",\n              \"-File\",\n              \"${workspaceFolder}\u002F.vscode\u002Fdiscovery-mcp-proxy.ps1\"\n            ]\n          }\n        }\n      }\n      ```\n\n      **Idempotent merge script** — read existing `.vscode\u002Fmcp.json` (if\n      any), drop any legacy `discovery-token` promptString input and any\n      legacy `type: \"http\"` microsoft-discovery server from earlier\n      versions of this skill, then insert the canonical stdio entry.\n      Preserve every other server and input untouched.\n\n      ```pwsh\n      $mcpPath = Join-Path $workspaceRoot '.vscode\u002Fmcp.json'\n      $mcpDir  = Split-Path $mcpPath -Parent\n      if (-not (Test-Path $mcpDir)) { New-Item -ItemType Directory -Force -Path $mcpDir | Out-Null }\n\n      if (Test-Path $mcpPath) {\n          $cfg = Get-Content $mcpPath -Raw | ConvertFrom-Json -Depth 10\n      } else {\n          $cfg = [pscustomobject]@{ servers = [pscustomobject]@{} }\n      }\n      if (-not $cfg.PSObject.Properties['servers']) {\n          $cfg | Add-Member -NotePropertyName servers -NotePropertyValue ([pscustomobject]@{})\n      }\n\n      # Drop the legacy promptString-based discovery-token input.\n      if ($cfg.PSObject.Properties['inputs']) {\n          $remaining = @($cfg.inputs | Where-Object { $_.id -ne 'discovery-token' })\n          if ($remaining.Count -eq 0) {\n              $cfg.PSObject.Properties.Remove('inputs')\n          } else {\n              $cfg.inputs = $remaining\n          }\n      }\n\n      # Canonical stdio-proxy server entry.\n      $serverEntry = [pscustomobject]@{\n          type    = 'stdio'\n          command = 'pwsh'\n          args    = @('-NoProfile', '-File', '${workspaceFolder}\u002F.vscode\u002Fdiscovery-mcp-proxy.ps1')\n      }\n      if ($cfg.servers.PSObject.Properties['microsoft-discovery']) {\n          $cfg.servers.'microsoft-discovery' = $serverEntry\n      } else {\n          $cfg.servers | Add-Member -NotePropertyName 'microsoft-discovery' -NotePropertyValue $serverEntry\n      }\n\n      $cfg | ConvertTo-Json -Depth 10 | Set-Content -Path $mcpPath -Encoding UTF8\n      ```\n\n      Guard-rails:\n      - Never blow away the file — always merge. Other servers (GitHub\n        MCP, Azure MCP, etc.) under `servers` and other entries under\n        `inputs` must remain byte-for-byte.\n      - **Always overwrite** any pre-existing `microsoft-discovery`\n        entry — including legacy `type: \"http\"` configs with the\n        `promptString` bearer header. The stdio proxy is the only\n        supported config for this skill.\n      - Do **not** write tokens, tenant IDs, or subscription IDs into\n        `mcp.json`. The proxy reads the active `az` session at runtime,\n        which is configured by Step 7a.2.5 below.\n\n  2.6. **(Optional) Restart the VS Code MCP server** - only useful for\n       the user's future interactive sessions; the skill itself does\n       NOT use the surfaced `mcp_microsoft-dis_*` tools. Skipping this\n       step is **fine** - the proxy + `Invoke-DiscoveryMcp` work\n       without any restart.\n\n       If you do want to be polite to the user:\n       1. Try `run_vscode_command commandId='workbench.action.mcp.restart'`\n          (no window reload). If the command id isn't found, stop - do\n          NOT escalate to a window reload mid-run.\n       2. **Do not** smoke-test by waiting for `mcp_microsoft-dis_*`\n          tools to appear via `tool_search`. They frequently do not\n          appear in the same session. Smoke-test via the proxy instead:\n\n       ```pwsh\n         . \"$workspaceRoot\\.vscode\\Invoke-DiscoveryMcp.ps1\"\n       $r = Invoke-DiscoveryMcp -ProxyPath \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\" -Calls @(\n           @{ name='ListWorkspaces'; args=@{ subscriptionId=$discoverySubscriptionId } }\n       )\n       (Get-DiscoveryMcpText -Response $r['2'] -AsJson).value.Count   # > 0 means healthy\n       ```\n\n       Common failure \\u2192 fix:\n\n       | Symptom from proxy                              | Cause                                                              | Fix                                                                                              |\n       |-------------------------------------------------|--------------------------------------------------------------------|--------------------------------------------------------------------------------------------------|\n       | `pwsh: command not found` from terminal        | PowerShell 7+ is not on PATH                                       | Install with `winget install Microsoft.PowerShell` - Windows PowerShell 5.1 is too old           |\n       | `az: command not found` on proxy stderr         | Azure CLI is not on PATH for the proxy's shell                     | Install Azure CLI and reopen the terminal so the new PATH is inherited                            |\n       | `401 InvalidAuthenticationTokenTenant`          | `az` is signed into the wrong tenant for the chosen subscription   | Re-run Step 7a.2.5 (`az login --tenant \u003Cid>`); the proxy auto-refreshes on the next request      |\n       | `AADSTS500011` (resource principal not found)   | Tenant has never consented to the Discovery first-party app        | Admin consent required - surface the error and stop; the skill cannot fix this                  |\n       | `mcp_microsoft-dis_*` tools never appear        | VS Code MCP runtime hasn't surfaced them (common, often permanent) | **Ignore** - use the proxy via `Invoke-DiscoveryMcp` instead. Do NOT poll `tool_search` for them. |\n       | Proxy exits with non-zero on launch             | `az account get-access-token` failed at startup                     | Re-run Step 7a.2.5 to fix the `az` session, then try again                                       |\n\n  2.5. **Prompt the user for tenant + subscription and run `az` on their\n       behalf.** Do this **before** starting (or restarting) the Discovery\n       MCP server so the bearer-token input resolves cleanly.\n\n       **Always prompt.** Even when `az account show` already returns a\n       valid session and `\u002Fmemories\u002Frepo\u002F` has a previously-used tenant\n       and subscription, you MUST still ask the user. Saved values are\n       used **only** to mark the matching option as `recommended: true`\n       in the picker — never to auto-select and skip the prompt. The\n       user opted into the Discovery + Azure path; that opt-in does not\n       grant permission to silently reuse a prior destination.\n\n       Workflow:\n\n       a. Run `az account list --query \"[].{name:name, id:id, tenantId:tenantId, isDefault:isDefault}\" -o json`\n          to enumerate every subscription the user has at least Reader on.\n          Group the results by `tenantId` so the picker lists each tenant\n          alongside its subscriptions.\n       b. Ask the user **once** with `vscode_askQuestions` (two questions\n          in a single call):\n          - **Question 1 — `discovery-tenant`** (single-select, required):\n            options are the distinct `tenantId` values from (a). Label\n            each with a short alias derived from the most common\n            subscription suffix (e.g. `\"corp (72f988bf-…)\"`) and put the\n            full GUID + member-subscription count in the `description`\n            field. If `\u002Fmemories\u002Frepo\u002F` has a previously-used tenant,\n            mark that option as `recommended: true` so it appears as the\n            default — but the prompt must still be shown.\n          - **Question 2 — `discovery-subscription`** (single-select,\n            required, freeform allowed): options are the subscriptions in\n            the tenant chosen in Q1. Label `\"\u003Cname> (\u003Csub-id-prefix>…)\"`,\n            full GUID in `description`. Mark the previously-used\n            subscription (if any in `\u002Fmemories\u002Frepo\u002F`) as\n            `recommended: true`; otherwise mark the `isDefault: true`\n            subscription that way.\n\n          The picker is a **single `vscode_askQuestions` call with two\n          questions** — do **not** call it twice. Because Q2's option list\n          depends on Q1's answer, build Q2 with **all** subscriptions\n          across all tenants and let the user filter — or, if you want a\n          two-phase flow, ask Q1 first, then make a second call for Q2\n          scoped to the chosen tenant. Either is acceptable; the two-phase\n          flow keeps the option list short.\n\n       c. Persist the chosen values as `$discoveryTenantId` and\n          `$discoverySubscriptionId` and write them to `\u002Fmemories\u002Frepo\u002F`\n          so future runs can pre-select (not auto-select) them as the\n          recommended option.\n       d. Run, in this order, in a **foreground** terminal so the user can\n          complete device-flow auth if prompted:\n          ```pwsh\n          az login --tenant $discoveryTenantId\n          az account set --subscription $discoverySubscriptionId\n          ```\n          If `az account show` already reports the chosen tenant and\n          subscription, you may skip the `az login` call and only run\n          `az account set` — the user is already signed in to the right\n          identity, so re-auth would be pointless friction. The\n          **prompt** in step (b) is still mandatory; only the underlying\n          `az login` invocation is conditional on the existing session.\n          If `az login` does run and opens the browser, wait for it to\n          finish (the terminal will return). If it falls back to device\n          code, the user types it directly into the browser — never\n          relay codes through `vscode_askQuestions`.\n       e. Verify with `az account show --query \"{sub:id, tenant:tenantId}\"\n          -o json`; both values must match the user's choices. If not,\n          stop and report — do not proceed to MCP restart with a\n          mismatched session.\n       f. Validate the resource token actually mints:\n          ```pwsh\n          az account get-access-token --resource https:\u002F\u002Fdiscovery.azure.com --query \"{tenant:tenant, expiresOn:expiresOn}\" -o json\n          ```\n          A success here means the MCP's `command`-input will resolve. A\n          failure (e.g. `AADSTS500011` \"resource principal not found\")\n          means the tenant has never consented to the Discovery first-party\n          app — surface that exact error and stop; admin consent is\n          required and cannot be granted from this skill.\n\n       Never ask the user for tokens, passwords, or device codes through\n       `vscode_askQuestions` — answers to that tool go through the model.\n       Tenant and subscription **IDs** are not secrets and are fine to\n       collect via the picker.\n   3. **None of the above worked.** Stop the workflow and report exactly\n      which probe failed (network error, sign-in declined, etc.) plus the\n      manual install instructions:\n      *Open Command Palette → \"MCP: Add Server\" → \"HTTP\" → URL\n      `https:\u002F\u002Fmcp.discovery.azure.com\u002Fmcp` → name `microsoft-discovery`*.\n      **Never** spoof a session or fabricate registry data.\n\n   Do **not** prompt for credentials, tokens, or secrets via\n   `vscode_askQuestions` at any point in the install — the MCP server's\n   own auth handshake (browser \u002F Entra) is the only safe channel.\n\n2. **Probe authentication via the proxy** (NOT via VS Code's MCP\n   runtime). With `az` already pointed at the correct\n   tenant\u002Fsubscription (Step 7a.2.5), call any cheap MCP tool through\n   `Invoke-DiscoveryMcp`:\n\n   ```pwsh\n     . \"$workspaceRoot\\.vscode\\Invoke-DiscoveryMcp.ps1\"\n   $r = Invoke-DiscoveryMcp -ProxyPath \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\" -Calls @(\n       @{ name='ListWorkspaces'; args=@{ subscriptionId=$discoverySubscriptionId } }\n   )\n   ```\n\n   - A JSON payload with `value[]` confirms the session is good.\n   - On `401 InvalidAuthenticationTokenTenant`, the `az` CLI is signed\n     into the wrong tenant. Re-run Step 7a.2.5 to pick the correct\n     tenant\u002Fsubscription. The proxy refreshes its token on the next\n     call automatically — no server restart needed.\n   - On `AADSTS500011` (resource principal not found), the tenant has\n     never consented to the Discovery first-party app. Surface the\n     error and stop — admin consent required.\n\n3. **Run interactive sign-in if needed.** If the probe in (2) fails\n   with `401`, re-run Step 7a.2.5 (re-prompts for tenant + subscription\n   and re-runs `az login --tenant \u003Cid>`). Do **not** prompt for\n   credentials, tokens, or device codes via `vscode_askQuestions` — the\n   user types them directly into the browser or terminal that `az login`\n   opens.\n\n4. **List workspaces** the signed-in user can access in\n   `$discoverySubscriptionId`:\n   - **Always via the proxy** — call `ListWorkspaces` through\n     `Invoke-DiscoveryMcp` (see step 2 above for the exact pattern).\n     The response is `{ \"value\": [ {name, id, location, …}, … ] }`.\n     Do **not** wait for VS Code to surface `mcp_microsoft-dis_ListWorkspaces`\n     as a deferred tool — it often never appears.\n     not already loaded.\n   - Fallback: `az resource list --subscription $discoverySubscriptionId\n     --resource-type Microsoft.Discovery\u002Fworkspaces --output json`.\n   - Filter out workspaces the user lacks `Contributor` (or higher) role on\n     — they can't deploy into those. If the filter would remove every entry,\n     show the full list with a warning instead.\n\n5. **ALWAYS ask the user to pick a workspace** with `vscode_askQuestions`\n   (single-select, required). The option label is the workspace display\n   name; the `description` field includes the workspace ID and region so the\n   user can disambiguate similarly-named workspaces. If\n   `\u002Fmemories\u002Frepo\u002F` has a previously-used workspace **in the chosen\n   subscription**, mark that option as `recommended: true` — but the\n   prompt is mandatory on every Discovery run. Never auto-select a\n   workspace from saved memory, environment variables, or a single-entry\n   list; always surface the picker so the user explicitly confirms the\n   destination.\n\n6. **List projects** inside the chosen workspace:\n   - **Always via the proxy**: call `ListProjects` through\n     `Invoke-DiscoveryMcp` with\n     `subscriptionId=$discoverySubscriptionId`,\n     `resourceGroupName=\u003Crg-of-chosen-workspace>`, and\n     `workspaceName=\u003Cchosen-workspace-name>`. Do not depend on\n     `mcp_microsoft-dis_ListProjects` being surfaced as a deferred tool.\n   - Fallback: `az rest --method get --uri\n     \"https:\u002F\u002Fmanagement.azure.com\u002Fsubscriptions\u002F$discoverySubscriptionId\u002FresourceGroups\u002F\u003Crg>\u002Fproviders\u002FMicrosoft.Discovery\u002Fworkspaces\u002F\u003Cws>\u002Fprojects?api-version=2026-06-01\"`.\n   - Show project display name + ID + the underlying Foundry project URI in\n     the option `description`.\n\n7. **ALWAYS ask the user to pick a project** with `vscode_askQuestions`\n   (single-select, required). Persist the result as `$discoveryWorkspace`\n   and `$discoveryProject` (full ID, not just display name). Same rule\n   as step 5: a previously-used project may be marked\n   `recommended: true`, but the prompt is mandatory on every Discovery\n   run — never auto-select.\n\n8. **List existing agents in the chosen project** and show them to the user\n   verbatim before proceeding:\n   - Prefer `agents action=list` filtered to the registry that corresponds\n     to `$discoveryProject`. Call `agents action=registry.list` first to\n     find the matching registry name.\n   - Fallback: `discovery agents list --project \u003Cproject-id>`.\n   - Print a table with: agent name, version (or last-updated timestamp),\n     tool count, and whether the name collides with any folder in\n     `$selected`. Highlight collisions clearly — they will trigger the\n     \"update vs create\" question in Step 7e.\n\n9. **Confirm before continuing.** Ask one more `vscode_askQuestions`:\n   *\"Proceed to deploy N agents to project `\u003Cproject-name>`?\"* with options\n   `Yes` (default) and `Cancel`. On `Cancel`, stop the workflow cleanly — do\n   not touch ACR or Foundry.\n\nPersist `$discoveryWorkspace`, `$discoveryProject`, `$discoverySubscriptionId`,\nand `$discoveryRg` for use in Step 7c (tool pre-flight against the\nworkspace's RG) and Step 7e (agent provisioning via `UpsertAgent`).\n\n#### 7b. Probe MCP availability for Azure\n\nDiscovery MCP — always available in a Discovery workspace as the `agents` and\n`tools` tools:\n\n| Capability | MCP call |\n|---|---|\n| List registered agents | `agents` with `action: list` |\n| Create \u002F update an agent | `agents` with `action: create` (or `update`) |\n| List available tool grants | `agents` with `action: tools.list` |\n| Assign tools to an agent | `agents` with `action: assign-tools` |\n| List \u002F refresh registries | `agents` with `action: registry.list` \u002F `registry.refresh` |\n\nAzure MCP — **probe first**, do not assume it is installed. Call:\n\n```\ntools action=search query='azure'\ntools action=search query='azure container registry'\ntools action=search query='azure subscription'\n```\n\nIf a callable Azure plugin is returned (`status: 'callable'`), use its tools\n(e.g. ACR build\u002Fpush, subscription select, role assignment) instead of `az`\nCLI. If only `metadata_only` plugins are returned, ask the user **once**\nwhether to install one of them; otherwise fall back to the `az` and `docker`\nCLIs (documented inline in Step 7d).\n\nDo **not** silently install Azure MCP plugins — installation makes them\navailable globally and the user should opt in.\n\n#### 7c. Pre-flight: detect pre-existing tool ARM resources\n\n**Skip this entire step for toolless agents** (`LocalToDiscovery` agents\nwith no `discovery_catalog\u002F\u003Cname>\u002F` folder, or any agent that declares no\n`tools\u002F\u003CTool>\u002F` subdirectories). Set `$skipImageBuild = $true`, leave\n`$preExistingToolIds` \u002F `$builtToolIds` empty, and jump straight to Step 7e.\nThere is nothing to pre-flight, build, or bind.\n\n**Many catalog agents are already partially deployed in shared Discovery\nworkspaces.** Before asking the user for ACR\u002FRG\u002Fregion (Step 7c.2) and\nbefore building any images (Step 7d.1), call\n`GetDiscoveryTool` (called via `Invoke-DiscoveryMcp`) once per tool declared under\n`discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002F` against the **workspace's resource\ngroup** (`$discoveryRg` from Step 7a — *not* the deployment ACR's RG).\n\n```\nfor $tool in (Get-ChildItem discovery_catalog\u002F\u003Cname>\u002Ftools\u002F -Directory):\n    GetDiscoveryTool subscriptionId=$discoverySubscriptionId\n                     resourceGroupName=$discoveryRg\n                     toolName=$tool.Name\n```\n\nOutcomes:\n\n| Result                                        | Interpretation                                                   | Action                                                                                                                |\n|-----------------------------------------------|------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|\n| `200` with `provisioningState=Succeeded`      | Tool already registered as ARM resource; image already pushed     | Capture the `.id` (ARM resource ID) and `.properties.definitionContent.infra[].image.acr`. **Skip build & push for this tool.** |\n| `200` with `provisioningState=Failed`         | Stale half-deployed resource                                      | Surface to user; ask whether to delete + recreate (default: leave alone, abort agent)                                |\n| `404` not found                               | Tool not registered yet                                           | Build + push + register (Step 7d). Need ACR + RG (Step 7c.2)                                                          |\n| `403` \u002F token expired                         | MCP auth issue                                                    | Re-run Step 7a.2.6 mint\u002Frestart                                                                                       |\n\nSet `$skipImageBuild = $true` only when **every** tool the agent declares\nreturns `Succeeded`. Otherwise `$skipImageBuild = $false` and you must\ncollect ACR config in Step 7c.2.\n\n**Why this matters.** The Microsoft Discovery catalog ships agents whose\ntool images are already published to a shared registry like `mdqacr`. In\nthat case there is nothing to build — the entire Docker\u002FACR\u002FRBAC pipeline\nis a no-op. Detecting this up front avoids prompting the user for an ACR\nthey don't own and avoids ~5–15 min of unnecessary build time.\n\n**A previously-deployed tool ARM may have been deleted since your last run**\n(shared dev workspaces get cleaned up), so a `404` here does **not** mean the\nimage is gone. Before falling into the full ACR-build prompt flow (Step 7c.2 \u002F\n7d), check whether the image already exists in the expected ACR\n(`az acr repository show-tags --name \u003Cacr> --repository \u003Ctool>`). If the image\nis present, **skip the build** and go straight to re-registering the tool ARM\nfrom the local `tool.yaml` (Step 7d.4: PUT `definitionContent` as an object,\n`language: python3`), poll `GetDiscoveryTool` to `Succeeded`, ensure AcrPull\n(idempotent), then bind it in Step 7e. Only build when the image is genuinely\nabsent from the ACR.\n\nAlso list existing agents in the target project so the user can see whether\nthe agent name is already taken — this is the data behind the\n\"update vs create\" question in Step 7e:\n\n```\nListAgents subscriptionId=$discoverySubscriptionId\n           resourceGroupName=$discoveryRg\n           workspaceName=$discoveryWorkspace\n           projectName=$discoveryProject\n```\n\nPersist `$preExistingToolIds` (map of `toolName → ARM resource ID`),\n`$skipImageBuild`, and `$existingAgentNames` for downstream steps.\n\n#### 7c.2. Collect Azure deployment configuration (only if $skipImageBuild == $false)\n\nSkip this entire sub-step when `$skipImageBuild == $true` — there's no\nimage to push, no ACR to choose, no RG to provision. Jump straight to Step\n7d.\n\nOtherwise ask the user **once** (single `vscode_askQuestions` call with\nmultiple questions) for the Azure targets. Pre-fill defaults from the\nenvironment when possible (`az account show`, `$env:AZURE_SUBSCRIPTION_ID`,\nprior session memory under `\u002Fmemories\u002Frepo\u002F`).\n\nThe **Foundry project name** is already known from Step 7a\n(`$discoveryProject`); use it as the default for the Foundry project field\nand allow the user to override it only if they explicitly need a different\ntarget.\n\nRequired values:\n\n- **Azure subscription** (id or name) — default `$discoverySubscriptionId`\n- **Resource group** (existing or to-create) — default `$discoveryRg`\n- **Azure Container Registry** name (the image registry — must be reachable\n  from the Foundry project that will host the agent). Pre-populate by\n  calling `az acr list --subscription \u003Csub> -o json` and surfacing\n  registries in the same region as `$discoveryWorkspace.location` first.\n- **Foundry project** name (defaults to `$discoveryProject`)\n- **Region** (only if the resource group or ACR needs to be created) —\n  default `$discoveryWorkspace.location`\n\nNever prompt for secrets via `vscode_askQuestions` (it ships answers through\nthe model). If a token or key is needed, instruct the user to type it\ndirectly into the terminal.\n\n#### 7d. Build + push tool images (only if $skipImageBuild == $false)\n\nIf every tool in the agent already exists as an ARM resource (Step 7c set\n`$skipImageBuild = $true`), skip this entire step and jump to Step 7e.\n\n**7d.LTD — pushing a locally-built image (`$deployTarget == 'LocalToDiscovery'`).**\nWhen promoting from the local app, the tool image may already be built locally\n(via Podman\u002FDocker from a prior local invocation). Two acceptable paths, in\norder of preference:\n\n1. **Cloud build from the local Dockerfile (preferred, reproducible).** Run\n   `az acr build` exactly as in the numbered steps below, using the local\n   `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002F` build context. This ignores any\n   locally-built image and rebuilds from the local Dockerfile in ACR — the\n   image content is identical and no local Docker\u002FPodman daemon is required.\n2. **Push the existing local image** (when the user wants the exact local build,\n   or `az acr build` is unavailable). Tag and push the locally-built image\n   directly, matching the local bootstrap tag convention `\u003Ctool>:latest`:\n   ```pwsh\n   az acr login --name \u003Cacr-name>\n   docker tag \u003Ctool>:latest \u003Cacr>.azurecr.io\u002F\u003Ctool>:latest\n   docker push \u003Cacr>.azurecr.io\u002F\u003Ctool>:latest\n   # Podman equivalent: podman tag \u003Ctool>:latest \u003Cacr>.azurecr.io\u002F\u003Ctool>:latest; podman push \u003Cacr>.azurecr.io\u002F\u003Ctool>:latest\n   ```\n   If the expected local image is missing, fall back to path 1.\n\nEither path is followed by the same manifest rewrite, ARM registration, and\nAcrPull grant (steps 3–6 below). **Never** push to any registry other than the\nACR chosen in Step 7c.2.\n\n**Do not** use `runSubagent agentName='microsoft-foundry'`. That skill is\nnot registered as a subagent — the call fails with \"Requested agent\n'microsoft-foundry' not found\". The skill is azd-oriented and assumes a\n`.foundry\u002F` overlay that catalog agents don't have. Execute the build\npipeline directly:\n\nFor each `tools\u002F\u003CTool>\u002F` subfolder under `discovery_catalog\u002F\u003Cname>\u002F` that\nhas a `Dockerfile`:\n\n1. **Build + push in one shot** (preferred — uses ACR cloud build, no\n   local Docker required):\n   ```pwsh\n   az acr build --registry \u003Cacr-name> `\n                --image \u003Ctool>:latest `\n                --image \u003Ctool>:sha-\u003Cgitshort> `\n                discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002F\n   ```\n\n   **Windows console crash — build still succeeds (observed).** On Windows,\n   `az acr build` streams the remote build log through `colorama` and often\n   dies client-side with\n   `UnicodeEncodeError: 'charmap' codec can't encode characters ...`\n   (cp1252). **This is a log-streaming failure only — the server-side ACR\n   build keeps running and usually completes.** Do NOT treat the traceback\n   as a build failure and do NOT immediately rebuild. Instead:\n   - Set `$env:PYTHONIOENCODING = 'utf-8'` (and, when practical,\n     `[Console]::OutputEncoding = [System.Text.Encoding]::UTF8`) *before*\n     invoking `az acr build` to avoid the crash in the first place.\n   - If it already crashed, capture the queued run id from the log\n     (`Queued a build with ID: \u003Cid>`) and poll for completion instead of\n     rebuilding:\n     ```pwsh\n     $env:PYTHONIOENCODING = 'utf-8'\n     do {\n       Start-Sleep -Seconds 20\n       $run = az acr task list-runs --registry \u003Cacr-name> --top 10 -o json |\n              ConvertFrom-Json | Where-Object { $_.runId -eq '\u003Cid>' }\n       $status = $run.status\n     } while ($status -eq 'Running')\n     # $status is 'Succeeded' \u002F 'Failed'\n     ```\n     Note: `az acr task list-runs --run-id \u003Cid>` can return empty; filter the\n     `--top N` list client-side by `runId` instead.\n   - Confirm the tags landed: `az acr repository show-tags --name \u003Cacr-name>\n     --repository \u003Ctool> -o tsv`.\n\n2. **Fallback** (only when `az acr build` is unavailable or fails with a\n   clear \"use local build\" message):\n   ```pwsh\n   az acr login --name \u003Cacr-name>\n   docker build -t \u003Cacr>.azurecr.io\u002F\u003Ctool>:latest discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002F\n   docker push \u003Cacr>.azurecr.io\u002F\u003Ctool>:latest\n   ```\n\n3. **Rewrite the manifest** so future re-deployments are reproducible:\n   - `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002Ftool.yaml` → set\n     `infra[].image.acr` to the pushed reference (e.g.\n     `mdqacr.azurecr.io\u002F\u003Ctool>:latest`). Replace any `{name}` placeholder\n     with the actual ACR name.\n   - **Normalize `code_environments[].language` to `python3` (not `python`).**\n     The tool ARM PUT accepts `python`, but the Foundry agent-binding step\n     in 7e then fails with a bare `provisioningState=Failed` (no error text\n     in `GetAgent`). Every working catalog container tool (e.g. `ambertools`,\n     `crest`) uses `python3`; Foundry derives the generated function name\n     `\u003Ctool>-Executepython3Code` from it. If the local `tool.yaml` says\n     `language: python`, change it to `python3` here before registering.\n   - Preserve all other fields and YAML formatting.\n\n4. **Register the tool as a Discovery ARM resource.** The Discovery MCP\n   does not surface a `CreateDiscoveryTool` tool — register via ARM API\n   directly.\n\n   **CRITICAL: `properties.definitionContent` MUST be a JSON _object_, not a\n   YAML\u002FJSON _string_.** Passing the raw `tool.yaml` text\n   (`Get-Content ... -Raw`) fails with\n   `HttpRequestPayloadAPISpecValidationFailed` \u002F\n   `InvalidType: Expected type object but found type string. Paths in\n   payload: '$.properties.definitionContent'`. Convert the YAML into an\n   object graph first. If `powershell-yaml` is unavailable (common), build\n   the object explicitly with `[ordered]@{}` mirroring `tool.yaml`, then\n   `ConvertTo-Json` the whole payload. Also write the body to a temp file\n   and pass it with `--body \"@\u003Cfile>\"` (avoids terminal quoting\u002Fecho\n   truncation), and set `$env:PYTHONIOENCODING = 'utf-8'`.\n   ```pwsh\n   # $def mirrors tool.yaml as an object (name, description, version,\n   # category, license, infra[], code_environments[]). Example shape:\n   $def = [ordered]@{\n     name        = '\u003Ctool>'\n     description = '\u003Ctool description>'\n     version     = '\u003Ctool-version-from-tool.yaml>'\n     category    = 'Scientific Computing'\n     license     = 'MIT'\n     infra       = @(\n       [ordered]@{\n         name       = 'worker'\n         infra_type = 'container'\n         image      = [ordered]@{ acr = '\u003Cacr>.azurecr.io\u002F\u003Ctool>:latest' }\n         compute    = [ordered]@{ \u003Cmin_resources\u002Fmax_resources\u002F...> }\n       }\n     )\n     code_environments = @(\n       [ordered]@{ language = 'python3'; command = 'python \"\u002F{{scriptName}}\"'; description = '...'; infra_node = 'worker' }\n     )\n   }\n   $payload = [ordered]@{\n     location   = '\u003Cregion>'\n     tags       = [ordered]@{ category = 'Scientific Computing' }\n     properties = [ordered]@{ version = '\u003Ctool-version>'; definitionContent = $def }\n   }\n   $bodyFile = Join-Path $env:TEMP 'dc-tool-put.json'\n   $payload | ConvertTo-Json -Depth 30 | Set-Content -Path $bodyFile -Encoding UTF8\n   $env:PYTHONIOENCODING = 'utf-8'\n   az rest --method PUT `\n     --uri \"https:\u002F\u002Fmanagement.azure.com\u002Fsubscriptions\u002F\u003Csub>\u002FresourceGroups\u002F\u003Crg>\u002Fproviders\u002FMicrosoft.Discovery\u002Ftools\u002F\u003Ctool>?api-version=2026-06-01\" `\n     --headers \"Content-Type=application\u002Fjson\" `\n     --body \"@$bodyFile\"\n   ```\n   To learn the exact object schema for a tool type, call `GetDiscoveryTool`\n   on any existing working tool in the same workspace and mirror its\n   `properties.definitionContent`.\n   Poll provisioning state via `GetDiscoveryTool` until `Succeeded`.\n\n5. **Grant AcrPull** to the workspace's user-assigned managed identity (the\n   `workspaceIdentity.principalId` from `GetWorkspace`) on the ACR:\n   ```pwsh\n   az role assignment create --assignee \u003CprincipalId> `\n                             --role AcrPull `\n                             --scope \u002Fsubscriptions\u002F\u003Csub>\u002FresourceGroups\u002F\u003Cacr-rg>\u002Fproviders\u002FMicrosoft.ContainerRegistry\u002Fregistries\u002F\u003Cacr>\n   ```\n   Treat \"already exists\" as success.\n\n6. Record `$builtToolIds` (map `toolName → ARM resource ID`) and the image\n   digests for the Step 8 summary.\n\n#### 7e. Create the agent in the Discovery project via UpsertAgent\n\nThis is the single mechanism that creates the agent in the Discovery\nproject — there is no separate \"Foundry hosted prompt agent create\" step.\nThe Discovery `UpsertAgent` MCP tool does both Discovery registration and\nthe Foundry-side wiring.\n\n1. **Extract the instructions block from the\n   `.github\u002Fagents\u002F\u003Cname>.agent.md` companion.** The Copilot companion's\n   markdown body is the **source of truth for the prompt**, for **both**\n   tool-bearing and toolless agents. Source `instructions` from that file\n   via `Get-AgentMdInstructions` (defined in Step 4c.LTD), which strips the\n   YAML frontmatter and any auto-generated container-bootstrap preamble.\n   Promoting the companion body keeps the local Copilot subagent and the\n   cloud Discovery agent in lockstep — whatever the user tuned locally is\n   what gets deployed.\n\n   ```pwsh\n   # Same helper defined in Step 4c.LTD.\n   $companion    = \".github\u002Fagents\u002F$name.agent.md\"\n   $instructions = Get-AgentMdInstructions $companion\n\n   # Tool-bearing promote: the local companion may still reference the tool as\n   # a LOCAL Podman\u002FDocker image (build context, image tag, image inspect).\n   # The cloud has no local runtime — rewrite those references to point at the\n   # deployed Discovery tool(s) instead. Requires the tool ARM + its ACR image\n   # to already exist (Step 7c pre-flight \u002F Step 7d build+push).\n   if ($agentHasCatalogFolder[$name]) {\n     $toolNames = @(Get-ChildItem \"discovery_catalog\u002F$name\u002Ftools\" -Directory -ErrorAction SilentlyContinue |\n                    ForEach-Object { $_.Name })\n     if ($toolNames.Count -gt 0) {\n       $instructions = Convert-PromoteInstructionsForTool -Instructions $instructions -ToolNames $toolNames\n     }\n   }\n\n   # SANITY-CHECK the extracted body length BEFORE UpsertAgent. A tool-bearing\n   # or otherwise real prompt should be thousands of chars. A result of only a\n   # few hundred chars almost always means the CRLF regex bug (a bare\n   # `\\n---\\n` that failed to match a CRLF companion) deleted the body. Abort\n   # and fix the extraction rather than deploying a stub.\n   if ($instructions.Length -lt 500) {\n     throw \"Extracted instructions for '$name' are only $($instructions.Length) chars — likely the CRLF regex bug. Fix Get-AgentMdInstructions \u002F Convert-PromoteInstructionsForTool to use '\\r?\\n---\\r?\\n' and re-extract before UpsertAgent.\"\n   }\n\n   # name + description ALSO come from the companion frontmatter (same source\n   # of truth as instructions), NOT from discovery_catalog\u002F\u003Cname>\u002Fagent.yaml.\n   $displayName = Get-AgentMdFrontmatterValue $companion 'name'\n   if ([string]::IsNullOrWhiteSpace($displayName)) { $displayName = $name }\n   $description = Get-AgentMdFrontmatterValue $companion 'description'\n   if ([string]::IsNullOrWhiteSpace($description) -and (Test-Path \"discovery_catalog\u002F$name\u002Fagent.yaml\")) {\n     # Fallback only if the companion has no description.\n     $description = (Get-Content \"discovery_catalog\u002F$name\u002Fagent.yaml\" -Raw) # then parse agent.yaml#description\n   }\n   # Foundry caps description at 512 chars — truncate before UpsertAgent.\n   if ($description.Length -gt 512) { $description = $description.Substring(0, 512).TrimEnd() }\n   ```\n\n   For a **tool-bearing** promote, the cloud instructions **must not**\n   reference any local container image. The `Convert-PromoteInstructionsForTool`\n   helper (Step 4c.LTD) removes the auto-generated bootstrap preamble, scrubs\n   any residual `podman`\u002F`docker` `build`\u002F`pull`\u002F`push`\u002F`image inspect` lines\n   and `discovery_catalog\u002F...\u002Ftools\u002F...` build-context references, and appends\n   a short \"Tool execution (Microsoft Discovery)\" note pointing at the deployed\n   Discovery tool(s) by name. **Before** calling `UpsertAgent`, confirm the\n   tool is actually usable in the cloud: every tool the agent declares must\n   have returned `provisioningState=Succeeded` from the Step 7c\n   `GetDiscoveryTool` pre-flight (or been built + pushed + registered in Step\n   7d), with its container image present in the workspace's ACR. Do not deploy\n   a tool-bearing agent whose Discovery tool \u002F ACR image is missing — bind the\n   tool first, then promote.\n\n   Do **NOT** read `instructions` **or `description`** from\n   `discovery_catalog\u002F\u003Cname>\u002Fagent.yaml` — the `.agent.md` companion\n   supersedes both. (`agent.yaml` is still used only for the tool subtree\n   and `metadata.yaml#associated_tools`.)\n\n   Field sourcing summary:\n\n   - **`instructions`** — always the `.github\u002Fagents\u002F\u003Cname>.agent.md`\n     companion body via `Get-AgentMdInstructions` (both buckets). For a\n     **tool-bearing** agent, additionally pass the result through\n     `Convert-PromoteInstructionsForTool` so the cloud prompt references the\n     deployed Discovery tool(s) instead of any local Podman\u002FDocker image.\n   - **`name` \u002F `description`** — for **both** buckets, read from the\n     `.github\u002Fagents\u002F\u003Cname>.agent.md` companion's YAML frontmatter via\n     `Get-AgentMdFrontmatterValue` (`name` \u002F `description`), **not** from\n     `discovery_catalog\u002F\u003Cname>\u002Fagent.yaml`. This keeps the deployed\n     Discovery agent's display name and description in lockstep with the\n     locally-tuned companion. Apply the 512-char truncation to\n     `description` (see Step 7e.4). If the companion frontmatter has no\n     `description`, fall back to `agent.yaml#description` (then still\n     truncate).\n   - **`toolIds`** — the pre-existing \u002F built tool ARM IDs for a\n     tool-bearing agent; empty for a toolless agent.\n\n   **Fallback (upstream `Discovery` target only).** The upstream-sourced\n   `Discovery` path does not generate a `.github\u002Fagents\u002F\u003Cname>.agent.md`\n   companion (Step 6 runs for `Local` only). If the companion file does\n   **not** exist, fall back to reading the YAML block scalar\n   (`instructions: |-`) from `discovery_catalog\u002F\u003Cname>\u002Fagent.yaml`: read the\n   full file, slice the lines between `instructions: |-` and the next\n   top-level key (e.g. `discoveryExtensions:`), and strip the 2-space\n   indent. PowerShell's `ConvertFrom-Yaml` (PSYaml module) is fine if\n   available; otherwise the line-slice + indent-strip approach works:\n   ```pwsh\n   $companion = \".github\u002Fagents\u002F$name.agent.md\"\n   if (Test-Path $companion) {\n     $instructions = Get-AgentMdInstructions $companion\n   } else {\n     $lines = Get-Content discovery_catalog\u002F$name\u002Fagent.yaml\n     # find indices of 'instructions: |-' and the next top-level key\n     $body = $lines[$start..$end] | ForEach-Object {\n         if ($_.Length -ge 2 -and $_.Substring(0,2) -eq '  ') { $_.Substring(2) } else { $_ }\n     }\n     $instructions = $body -join \"`n\"\n   }\n   ```\n\n   **Preserve all `{{templateVariables}}`** (`{{workflowContext}}`,\n   `{{agentTeam}}`, `{{nodePoolContext}}`, `{{dataHandlingContext}}`,\n   tool-id placeholders like `{{alphafoldToolId}}`, model placeholder\n   `{{CHAT-MODEL}}`). These are filled in by the Discovery engine at\n   invocation time.\n\n2. **Pick a chat model deployment.** Call `ListChatModelDeployments`\n   (via `Invoke-DiscoveryMcp`) against the workspace and apply this\n   decision tree — **prefer auto-pick over asking**, every prompt costs\n   a round-trip:\n   - Filter to deployments with `provisioningState == 'Succeeded'`\n     whose `modelName` starts with `gpt-5` (preferred) or equals `gpt-4o`\n     (fallback). Sort by `systemData.lastModifiedAt` descending.\n   - **Auto-pick the top candidate without asking** when:\n     - The filtered list has exactly one entry, OR\n     - The top candidate's `lastModifiedAt` is strictly newer than every\n       other candidate's. (No tie at the top.)\n   - **Only ask the user via `vscode_askQuestions`** when there are 2+\n     candidates with the same most-recent `lastModifiedAt`, OR when no\n     deployment matches the `gpt-5* \u002F gpt-4o` filter (rare — fall back\n     to all `Succeeded` deployments and ask).\n   - Announce the auto-picked choice in the Step 8 summary so the user\n     can see what was selected.\n\n3. **Assemble `toolIds`.** Merge `$preExistingToolIds` (Step 7c) with\n   `$builtToolIds` (Step 7d) into a comma-separated list of ARM resource\n   IDs. For **toolless** agents this is empty — pass an empty string (or\n   omit `toolIds`); do not fabricate a tool binding.\n\n4. **Call `UpsertAgent`** (via `Invoke-DiscoveryMcp`). Required values:\n   - `subscriptionId`, `resourceGroupName`, `workspaceName`, `projectName`\n   - `agentName` (= agent folder name, kebab-case)\n   - `kind`: `prompt` (default for catalog agents — they're all prompt\n     agents) or `workflow` if `agent.yaml#kind == 'workflow'`\n   - `description`: the companion frontmatter `description` (via\n     `Get-AgentMdFrontmatterValue \".github\u002Fagents\u002F$name.agent.md\" 'description'`),\n     falling back to `agent.yaml#description` only if the companion has none.\n     **Truncate to 512 chars max.** Foundry caps the agent `description` at\n     512 characters; a longer value causes a fast bare\n     `provisioningState=Failed` (with `foundryDetails=null` and no error text\n     in `GetAgent`). This is NOT a tool-binding failure. Trim to \u003C=512 before\n     calling `UpsertAgent` (e.g. drop a trailing scope sentence).\n     `GetAgentOperation(operationId)` returns the real error\n     (`maxLength: Value should be at most 512 characters` on `\u002Fdescription`)\n     if you need to confirm.\n   - `instructions`: the extracted string from step 1\n   - `model`: the chat model deployment name from step 2\n   - `temperature`: `agent.yaml#model.options.temperature` (default 0)\n   - `topP`: `agent.yaml#model.options.topP` (default 0)\n   - `toolIds`: comma-separated ARM IDs from step 3\n   - `humanInTheLoop`: from `agent.yaml#discoveryExtensions.humanInTheLoop`\n     (default `Disabled`)\n   - `discoveryExtensions`: JSON string of any extensions\n     (`{\"disableDataHandlingTools\": false}` is a safe default)\n\n5. **Poll `GetAgent` for `provisioningState=Succeeded`.** `UpsertAgent`\n   returns `{id, status, agentName}` where `id` is an operationId. Prefer\n   `GetAgent` provisioningState polling for the happy path (the\n   `GetAgentOperation` MCP tool has historically been flaky, though it can\n   still return the real error — see the recovery notes below). Use the\n   extracted `Wait-DiscoveryAgentReady` helper, which polls `GetAgent` and\n   watches `provisioningState`:\n\n   ```pwsh\n   Wait-DiscoveryAgentReady -ProxyPath $proxy `\n       -SubscriptionId $sub -ResourceGroupName $rg `\n       -WorkspaceName $ws -ProjectName $proj `\n       -AgentName $agentName -TimeoutSeconds 300\n   ```\n\n   States to handle:\n   - `Creating` \u002F `Updating` \u002F `Accepted` → helper keeps polling.\n   - `Succeeded` → helper returns the parsed agent object; record\n     `$createdAgentId` for Step 8 summary.\n   - `Failed` → helper throws with the full payload; surface verbatim\n     and do not retry blindly.\n\n   **When a tool is bound and `GetAgent` reports `Failed` fast (~5–10 s)\n   with `foundryDetails=null` and no error text**, the failure is almost\n   always the tool binding, not the prompt. Diagnose and recover as follows\n   (this exact sequence recovered a real run):\n   1. **Confirm it's the tool, not the instructions.** Re-`UpsertAgent`\n      once *without* `toolIds` (same model + instructions). If that\n      Succeeds, the prompt is fine and the tool binding is the culprit.\n   2. **Check the tool's `language`.** Call `GetDiscoveryTool` and compare\n      `code_environments[].language` against a working container tool in the\n      same workspace. If it's `python` (or anything other than `python3`),\n      re-register the tool ARM with `language: python3` (Step 7d.3–7d.4) and\n      wait for `GetDiscoveryTool` to report `Succeeded` again.\n   3. **Allow propagation before rebinding.** After the tool ARM flips to\n      `Succeeded`, the Foundry-side tool definition can still be stale for\n      ~30–60 s. An immediate `UpsertAgent` with the tool may still `Fail`.\n      Wait ~30–60 s, then re-`UpsertAgent` with `toolIds` and re-poll. A\n      second attempt typically Succeeds.\n   4. **Get the real error when you need it.** Contrary to older guidance,\n      `GetAgentOperation` *can* return the actual result\u002Ferror. After an\n      `UpsertAgent`, capture the returned `id` (operationId) and call\n      `GetAgentOperation` with `operationId=\u003Cid>` (plus the sub\u002Frg\u002Fws\u002Fproj\u002F\n      agentName args). It returns `{status, error, result}` — use `error`\n      for the failure detail and `result` for the provisioned agent. Still\n      prefer `Wait-DiscoveryAgentReady` (GetAgent polling) for the happy\n      path; reach for `GetAgentOperation` only when GetAgent gives a bare\n      `Failed`.\n\n   Typical provisioning takes 10–60 s. If `Wait-DiscoveryAgentReady`\n   times out at 300 s, the agent almost certainly did succeed — verify\n   with one `ListAgents` call before declaring failure.\n\n6. **Verify** with `ListAgents` (or `GetAgent`) to confirm the agent\n   appears in the project with `provisioningState=Succeeded` and the\n   expected `toolIds`.\n\n#### 7f. (Optional) Local Discovery agent runtime registration\n\nThe cloud-side agent created in Step 7e is **fully usable** via the\nDiscovery web studio and the Discovery MCP `CreateResponse` tool (called via `Invoke-DiscoveryMcp`) without this\nstep. Only proceed if the user explicitly wants the agent to appear in the\nlocal Discovery extension's agent picker (different scope from the cloud\nproject).\n\nIf proceeding:\n\n1. Call `agents` with `action: tools.list` to discover which catalog tools\n   match the agent's `discoveryExtensions.tools` references.\n2. Call `agents` with `action: create`, passing:\n   - `name`: the agent folder name (kebab-case)\n   - `description`: from `agent.yaml#description`\n   - `systemPrompt`: from `agent.yaml#instructions`\n   - `toolGrants`: declarative grants assembled from step 1\n3. Optionally call `agents` with `action: registry.refresh` so the new entry\n   appears in `agents list` immediately.\n\n**Do not** call `agents` with `action: run.start` from this skill —\nregistration is the goal; running the agent is a separate user action.\n\nAsk the user once (default: skip) before performing this step.\n\n#### 7g. Rules and guard-rails\n\n- **Local files are the source of truth.** For a **tool-bearing** agent,\n  never deploy one whose `discovery_catalog\u002F\u003Cname>\u002F` folder is missing or\n  only partially copied. A **toolless** promote agent legitimately has **no**\n  `discovery_catalog\u002F\u003Cname>\u002F` folder — its source of truth is the\n  `.github\u002Fagents\u002F\u003Cname>.agent.md` companion; require that companion to\n  exist and to yield a non-empty instructions body before deploying.\n- **Instructions AND description come from the\n  `.github\u002Fagents\u002F\u003Cname>.agent.md` companion.** For **both** buckets in the\n  `LocalToDiscovery` (promote) path, the prompt body deployed to Discovery is\n  the companion's markdown body (via `Get-AgentMdInstructions`) and the\n  agent `name` \u002F `description` are the companion frontmatter values (via\n  `Get-AgentMdFrontmatterValue`), never `discovery_catalog\u002F\u003Cname>\u002Fagent.yaml`.\n  Require a non-empty instructions body from the companion before deploying,\n  and truncate `description` to 512 chars (Foundry cap). Only the upstream\n  `Discovery` target (no companion) falls back to `agent.yaml#instructions` \u002F\n  `agent.yaml#description` (Step 7e.1).\n- **Cloud instructions for tool-bearing promotes must reference the\n  Discovery tool, not a local image.** When a promoted agent has a\n  `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002F` folder, pass its instructions\n  through `Convert-PromoteInstructionsForTool` (Step 4c.LTD) so the deployed\n  prompt drops every local Podman\u002FDocker build\u002Finspect\u002Fpull\u002Fpush reference\n  and points at the deployed Discovery tool(s) by name. The cloud has no\n  local container runtime — never deploy local image tags or build contexts.\n  Confirm each declared tool is `provisioningState=Succeeded` with its image\n  present in the workspace's ACR (Step 7c\u002F7d) **before** `UpsertAgent`.\n- **Tool detection is mandatory for tool-bearing agents.** Always run Step\n  7c `GetDiscoveryTool` pre-flight before asking ACR\u002FRG questions or\n  building images. If you prompt the user for an ACR that turns out to be\n  irrelevant because the tool already exists, you've wasted their time.\n  Toolless agents skip 7c\u002F7d entirely.\n- **Idempotency.** If an image tag already exists in ACR with the same\n  digest, do not rebuild. If a hosted agent with the same name already\n  exists in the Foundry project, prefer `update` over `create` and ask the\n  user once before overwriting.\n- **Never push to public registries.** Only the ACR named in step 7c.2 is a\n  valid push target. Reject any attempt to push to `docker.io`, `ghcr.io`,\n  or any other registry.\n- **No secrets through `vscode_askQuestions`.** If the Foundry deployment\n  requires a token the user has not already configured via `az login`, stop\n  and ask them to authenticate in the terminal.\n- **Bail on RBAC failures.** If the Foundry-managed identity cannot be\n  granted `AcrPull` on the registry, stop and report the missing\n  permission. Do not retry by escalating privileges.\n- **Always preserve `discovery_catalog\u002F\u003Cname>\u002F` after deployment.** Step 7\n  may rewrite `tool.yaml#infra.image.acr` in place — that's fine — but it\n  must not delete the local folder or its `tools\u002F` subtree.\n- **`microsoft-foundry` is a skill, not a subagent.** Do not call\n  `runSubagent agentName='microsoft-foundry'`. Execute the deploy\n  pipeline directly using Discovery MCP + `az` CLI as described above.\n- **Tool ARM `definitionContent` is an object, not a string.** Build it\n  with `[ordered]@{}` (or `ConvertFrom-Yaml`) and `ConvertTo-Json`; never\n  pass raw `tool.yaml` text. A string payload fails with\n  `InvalidType: Expected type object but found type string`.\n- **Container tools must declare `language: python3`.** `python` passes the\n  tool ARM PUT but breaks Foundry agent-binding (bare `Failed`, no error).\n- **Give tool changes ~30–60 s to propagate** before binding them to an\n  agent; an immediate `UpsertAgent` after a tool re-register can still\n  `Fail` even though the tool shows `Succeeded`.\n- **`az acr build` may crash the Windows console but still build.** Set\n  `$env:PYTHONIOENCODING='utf-8'` before calling it; if it crashed, poll\n  `az acr task list-runs` for the queued run id instead of rebuilding.\n\n### Step 8 — Cleanup and summary\n\n1. Remove the temp clone directory: `Remove-Item -Recurse -Force $work`.\n2. Print a structured summary to chat:\n   - **Selection mode** (All \u002F Specific \u002F By group) and **resolved selection** (N agents)\n   - **Deployment target** (Local \u002F Discovery \u002F LocalToDiscovery)\n   - **Catalog folders created** (N — `discovery_catalog\u002F\u003Cname>\u002F` did not exist locally before this run; list names)\n   - **Catalog folders refreshed** (N — `discovery_catalog\u002F\u003Cname>\u002F` was overwritten with the latest upstream copy; list names)\n   - **Catalog folders skipped** (N — name not present in `agents\u002F` upstream; e.g. removed from the catalog)\n   - **Companions already present** (N — `.github\u002Fagents\u002F\u003Cname>.agent.md` existed before this run; from `$existingLocalAgents`. These were re-generated, not skipped.)\n   - **Copilot agents generated** (N `.github\u002Fagents\u002F*.agent.md` files written — only when target == `Local`. Includes both fresh files and re-generations.)\n   - **Copilot agents skipped** (N, with reason — missing `agent.yaml`, empty `instructions`, etc.)\n  - **Container bootstrap preambles emitted** (N agents that had at least one `tools\u002F*\u002FDockerfile` upstream)\n   - **Pre-existing tool ARMs detected** (N, list `toolName → ARM ID` — image build skipped for these — only when target is a Discovery-class target)\n   - **Tool images built and pushed** (N images pushed to `\u003Cacr>.azurecr.io` — only when target == `Discovery` and at least one tool was missing)\n   - **Tool ARMs registered** (N new `Microsoft.Discovery\u002Ftools` resources created — only when target is a Discovery-class target)\n   - **Discovery agents provisioned** (N agents created\u002Fupdated in the Discovery project via `UpsertAgent` — only when target is a Discovery-class target)\n   - **Local Discovery runtime entries created** (N agents registered via `agents action=create` — only when user opted into Step 7f)\n   - **Deployment failures** (N, with the failing agent name and error message — never silently drop)\n\nWhen `$deployTarget == 'Local'`, this skill does NOT build or pull local\ncontainer images. Image builds are deferred to each generated `.agent.md` at\ninvocation time and are conditional on the image being absent.\n\nWhen `$deployToCloud` is true (`$deployTarget` is `Discovery` or\n`LocalToDiscovery`), Step 7c pre-flights each tool against\nthe workspace's RG via `GetDiscoveryTool`. If every tool already exists\n(`provisioningState=Succeeded`), Step 7d is skipped entirely — no ACR\nprompts, no image builds, no RBAC. Step 7e then provisions the agent in\nthe Discovery project via `UpsertAgent` + `GetAgent` provisioningState\npolling (the `GetAgentOperation` MCP tool is broken in practice — see the\nScripted MCP invocation section above). Step\n7f (local runtime registration) is optional and skipped by default.\n\n## Verification checklist\n\nAfter adding the agents, for at least one newly-created agent, confirm:\n\n- [ ] `discovery_catalog\u002F\u003Cname>\u002Fagent.yaml` exists and starts with `kind: prompt`\n- [ ] `discovery_catalog\u002F\u003Cname>\u002Fmetadata.yaml` lists `associated_tools` pointing at `agents\u002F\u003Cname>\u002Ftools\u002F\u003CTool>`\n- [ ] `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002FDockerfile` exists\n- [ ] `discovery_catalog\u002F\u003Cname>\u002Ftools\u002F\u003CTool>\u002Ftool.yaml` parses as YAML and contains an `infra:` block with `image.acr`\n\nWhen `$deployTarget == 'Local'`:\n\n- [ ] `.github\u002Fagents\u002F\u003Cname>.agent.md` exists, starts with `---`, and its frontmatter `name:` matches `agent.yaml#name`\n- [ ] The body of `.github\u002Fagents\u002F\u003Cname>.agent.md` is the (de-indented) contents of `agent.yaml#instructions`, preceded by the container bootstrap preamble when at least one `tools\u002F*\u002FDockerfile` exists\n- [ ] The hand-authored Copilot agents (`batteries-included`, `bookshelf-researcher`, `project-setup-orchestrator`) are untouched\n\nWhen `$deployToCloud` is true (`$deployTarget` is `Discovery` or `LocalToDiscovery`):\n\n- [ ] Every `tools\u002F\u003CTool>\u002FDockerfile` in `$selected` has produced an image at `\u003Cacr>.azurecr.io\u002F\u003Ctool>:latest` (verify with the Azure MCP or `az acr repository show-tags`)\n- [ ] The corresponding `tool.yaml#infra.image.acr` field has been updated to point at the pushed tag\n- [ ] Each agent appears in `agents action=list` with the expected name and tool grants\n- [ ] A hosted prompt agent with the same name exists in the configured Foundry project\n\n## Things this skill must NOT do\n\n- Do not edit `agent.yaml` or `metadata.yaml` contents during the local copy step — copy verbatim. (Step 7 may rewrite `tool.yaml#infra.image.acr` after a successful ACR push; that is allowed.)\n- Do not generate placeholder Dockerfiles for tools that lack one upstream.\n- **Do not run local `podman build|pull|push` or `docker build|pull|push` directly from this skill when `$deployTarget == 'Local'`.** Local image bootstrap is delegated to the generated agents and must happen lazily at invocation time only when the image is missing.\n- When `$deployTarget == 'Local'`, do not touch Azure Container Registry, Microsoft Foundry, or the Discovery agent registry.\n- Do not delete existing local agents that aren't in upstream.\n- Do not create `.md` documentation of the add operation — print the summary to chat.\n- Do not overwrite or delete `.github\u002Fagents\u002F*.agent.md` files whose stem does **not** correspond to a `discovery_catalog\u002F\u003Cname>\u002F` folder (those are hand-authored Copilot agents).\n\n## Embedded Discovery MCP scripts\n\nThese embedded scripts are the authoritative source for the generated\n`.vscode\u002Fdiscovery-mcp-proxy.ps1` and `.vscode\u002FInvoke-DiscoveryMcp.ps1` files.\nDo not require sibling `.ps1` files next to this skill. Extract these blocks\nverbatim with the Step 4d bootstrap before making Discovery MCP calls.\n\n\u003C!-- BEGIN:embedded-discovery-mcp-proxy.ps1 -->\n```powershell\n#Requires -Version 7\n\u003C#\n.SYNOPSIS\n  Local stdio\u003C->HTTP proxy for the Microsoft Discovery remote MCP server.\n\n.DESCRIPTION\n  VS Code launches this script as a stdio MCP server. It transparently:\n  1. Mints an Entra access token for https:\u002F\u002Fdiscovery.azure.com via\n     `az account get-access-token`, using whatever tenant + subscription\n     the active `az` session is signed into.\n  2. Forwards every newline-delimited JSON-RPC message from stdin to\n     https:\u002F\u002Fmcp.discovery.azure.com\u002Fmcp via HTTPS POST, attaching the\n     bearer token and the Mcp-Session-Id header.\n  3. Streams the response back to stdout. Handles both `application\u002Fjson`\n     (single response) and `text\u002Fevent-stream` (SSE) responses.\n  4. On HTTP 401 (token expired or wrong tenant), automatically mints a\n     fresh token from `az` and retries the request once. No user\n     interaction, no clipboard, no command-palette prompt.\n\n  Replaces the legacy `inputs[type=promptString]` flow that required the\n  user to paste a token into a command-palette input every time the MCP\n  server restarted.\n\n.NOTES\n  - Requires PowerShell 7+ (uses Invoke-WebRequest -SkipHttpErrorCheck).\n  - Requires `az` CLI on PATH with an active session (`az login`).\n  - All diagnostic output goes to STDERR so it does not corrupt the MCP\n  stdio JSON-RPC channel on STDOUT.\n#>\n\n[CmdletBinding()]\nparam(\n  [string]$Endpoint = 'https:\u002F\u002Fmcp.discovery.azure.com\u002Fmcp',\n  [string]$Resource = 'https:\u002F\u002Fdiscovery.azure.com'\n)\n\n$ErrorActionPreference = 'Stop'\n$ProgressPreference = 'SilentlyContinue'\n\nfunction Write-Diag([string]$Message) {\n  [Console]::Error.WriteLine(\"[discovery-mcp-proxy] $Message\")\n}\n\nfunction New-DiscoveryToken {\n  $azPath = (Get-Command az -ErrorAction SilentlyContinue)?.Source\n  if (-not $azPath) {\n    throw \"az CLI not found on PATH. Install Azure CLI and run 'az login'.\"\n  }\n  $tok = & az account get-access-token --resource $Resource --query accessToken -o tsv 2>$null\n  if ([string]::IsNullOrWhiteSpace($tok) -or $tok -match '^(ERROR|AADSTS)') {\n    throw \"Failed to mint Discovery access token via az. Run 'az login --tenant \u003Ctenant>' and try again.\"\n  }\n  return $tok.Trim()\n}\n\n$script:Token = $null\n$script:SessionId = $null\n\ntry {\n  $script:Token = New-DiscoveryToken\n  Write-Diag \"Initial token minted (len=$($script:Token.Length)).\"\n} catch {\n  Write-Diag \"FATAL: $($_.Exception.Message)\"\n  exit 1\n}\n\nfunction Invoke-McpRequest {\n  param([string]$Body)\n\n  $headers = @{\n    'Authorization' = \"Bearer $script:Token\"\n    'Accept'        = 'application\u002Fjson, text\u002Fevent-stream'\n  }\n  if ($script:SessionId) {\n    $headers['Mcp-Session-Id'] = $script:SessionId\n  }\n\n  $attempt = 0\n  while ($true) {\n    $attempt++\n    try {\n      $resp = Invoke-WebRequest -Uri $Endpoint `\n                     -Method Post `\n                     -Body $Body `\n                     -ContentType 'application\u002Fjson' `\n                     -Headers $headers `\n                     -SkipHttpErrorCheck `\n                     -ErrorAction Stop\n    } catch {\n      Write-Diag \"POST exception: $($_.Exception.Message)\"\n      return $null\n    }\n\n    if ($resp.StatusCode -eq 401 -and $attempt -eq 1) {\n      Write-Diag \"401 from Discovery MCP; refreshing token and retrying.\"\n      try {\n        $script:Token = New-DiscoveryToken\n        $headers['Authorization'] = \"Bearer $script:Token\"\n        continue\n      } catch {\n        Write-Diag \"Token refresh failed: $($_.Exception.Message)\"\n        return $null\n      }\n    }\n\n    foreach ($k in $resp.Headers.Keys) {\n      if ($k -ieq 'Mcp-Session-Id') {\n        $val = $resp.Headers[$k]\n        if ($val -is [array]) { $val = $val[0] }\n        if ($val) { $script:SessionId = $val }\n        break\n      }\n    }\n\n    if ($resp.StatusCode -ge 400) {\n      Write-Diag \"HTTP $($resp.StatusCode) from Discovery MCP: $($resp.Content)\"\n    }\n    return $resp\n  }\n}\n\nfunction Write-McpLine([string]$Line) {\n  if ([string]::IsNullOrWhiteSpace($Line)) { return }\n  [Console]::Out.WriteLine($Line)\n  [Console]::Out.Flush()\n}\n\nfunction Emit-Response($Resp) {\n  if (-not $Resp) { return }\n  if ($Resp.StatusCode -eq 202) { return }\n  if ([string]::IsNullOrEmpty($Resp.Content)) { return }\n\n  $ctype = ''\n  foreach ($k in $Resp.Headers.Keys) {\n    if ($k -ieq 'Content-Type') {\n      $v = $Resp.Headers[$k]\n      if ($v -is [array]) { $v = $v[0] }\n      $ctype = [string]$v\n      break\n    }\n  }\n\n  if ($ctype -like 'text\u002Fevent-stream*') {\n    foreach ($block in ($Resp.Content -split \"(?:`r?`n){2,}\")) {\n      $dataLines = @()\n      foreach ($line in ($block -split \"`r?`n\")) {\n        if ($line -match '^data:\\s?(.*)$') { $dataLines += $matches[1] }\n      }\n      if ($dataLines.Count -gt 0) {\n        Write-McpLine (($dataLines -join \"`n\").Trim())\n      }\n    }\n  } else {\n    $compact = ($Resp.Content -replace \"`r?`n\", '').Trim()\n    Write-McpLine $compact\n  }\n}\n\nWrite-Diag \"Proxy ready. Endpoint=$Endpoint\"\n\ntry {\n  while ($null -ne ($line = [Console]::In.ReadLine())) {\n    if ([string]::IsNullOrWhiteSpace($line)) { continue }\n    $resp = Invoke-McpRequest -Body $line\n    Emit-Response $resp\n  }\n} catch {\n  Write-Diag \"Main loop exception: $($_.Exception.Message)\"\n  exit 2\n}\n\nWrite-Diag \"stdin closed; exiting cleanly.\"\n```\n\u003C!-- END:embedded-discovery-mcp-proxy.ps1 -->\n\n\u003C!-- BEGIN:embedded-Invoke-DiscoveryMcp.ps1 -->\n```powershell\n#Requires -Version 7\n\u003C#\n.SYNOPSIS\n  Canonical helper to invoke any Microsoft Discovery MCP tool from scripted\n  PowerShell, without depending on the VS Code MCP runtime surfacing the\n  `mcp_microsoft-dis_*` tools mid-session.\n\n.DESCRIPTION\n  Spawns `discovery-mcp-proxy.ps1` as a stdio process, sends an MCP\n  `initialize` + one `tools\u002Fcall` per call in $Calls, and returns a hash\n  keyed by JSON-RPC id (`'2'`, `'3'`, ...) whose values are the parsed\n  response objects.\n\n  This is the PREFERRED path for any MCP work this skill performs. The\n  VS Code mcp.json registration is a nice-to-have for the user's future\n  interactive sessions - do not block on it for scripted runs.\n\n.EXAMPLE\n  . \"$PSScriptRoot\\Invoke-DiscoveryMcp.ps1\"\n  $results = Invoke-DiscoveryMcp -ProxyPath \"$workspaceRoot\\.vscode\\discovery-mcp-proxy.ps1\" -Calls @(\n    @{ name='ListAgents'; args=@{ subscriptionId=$sub; resourceGroupName=$rg; workspaceName=$ws; projectName=$proj } }\n  )\n  $r = $results['2']\n  $txt = ($r.result.content | Where-Object { $_.type -eq 'text' } | Select-Object -ExpandProperty text) -join \"`n\"\n  $obj = $txt | ConvertFrom-Json -Depth 50\n\n.NOTES\n  - Requires PowerShell 7+.\n  - Each call is a single `tools\u002Fcall`; results are returned as parsed\n  JSON-RPC objects keyed by id. Inspect `$r.result.isError` for\n  server-side tool errors (the JSON-RPC frame still succeeds in that\n  case).\n  - On HTTP 401, the proxy refreshes the `az` token automatically.\n#>\n\nfunction Invoke-DiscoveryMcp {\n  [CmdletBinding()]\n  param(\n    [Parameter(Mandatory)][string]$ProxyPath,\n    [Parameter(Mandatory)][object[]]$Calls\n  )\n\n  if (-not (Test-Path $ProxyPath)) {\n    throw \"Discovery MCP proxy not found at $ProxyPath\"\n  }\n\n  $msgs = @()\n  $msgs += '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"add-agent-from-catalog\",\"version\":\"1.0.0\"}}}'\n  $msgs += '{\"jsonrpc\":\"2.0\",\"method\":\"notifications\u002Finitialized\",\"params\":{}}'\n\n  $id = 2\n  foreach ($c in $Calls) {\n    $payload = @{\n      jsonrpc = '2.0'\n      id      = $id\n      method  = 'tools\u002Fcall'\n      params  = @{ name = $c.name; arguments = ($c.args ?? @{}) }\n    } | ConvertTo-Json -Depth 30 -Compress\n    $msgs += $payload\n    $id++\n  }\n\n  $tmp = New-TemporaryFile\n  try {\n    ($msgs -join \"`n\") | Set-Content -Path $tmp.FullName -Encoding ascii\n    $raw = Get-Content $tmp.FullName | pwsh -NoProfile -File $ProxyPath 2>$null\n  } finally {\n    Remove-Item $tmp.FullName -ErrorAction SilentlyContinue\n  }\n\n  $results = [ordered]@{}\n  foreach ($line in $raw) {\n    if ([string]::IsNullOrWhiteSpace($line)) { continue }\n    try {\n      $obj = $line | ConvertFrom-Json -Depth 50\n    } catch { continue }\n    if ($null -eq $obj.id) { continue }\n    $results[[string]$obj.id] = $obj\n  }\n  return $results\n}\n\nfunction Get-DiscoveryMcpText {\n  \u003C#\n  .SYNOPSIS\n    Extract the text payload from a single MCP tool\u002Fcall response object\n    and parse it as JSON when possible.\n  .DESCRIPTION\n    Most Discovery MCP tools return their payload inside\n    $r.result.content[].text as a JSON string. This helper concatenates\n    those text blocks and (optionally) parses the result.\n  #>\n  [CmdletBinding()]\n  param(\n    [Parameter(Mandatory)][object]$Response,\n    [switch]$AsJson\n  )\n  if (-not $Response) { return $null }\n  $texts = @()\n  foreach ($c in $Response.result.content) {\n    if ($c.type -eq 'text') { $texts += $c.text }\n  }\n  $blob = $texts -join \"`n\"\n  if ($AsJson) {\n    try { return $blob | ConvertFrom-Json -Depth 50 } catch { return $blob }\n  }\n  return $blob\n}\n\nfunction Wait-DiscoveryAgentReady {\n  \u003C#\n  .SYNOPSIS\n    Poll GetAgent until provisioningState == 'Succeeded' (or 'Failed').\n  .DESCRIPTION\n    Replaces the unreliable GetAgentOperation polling. The MCP server's\n    GetAgentOperation often returns an opaque \"An error occurred invoking\n    'GetAgentOperation'.\" text even when UpsertAgent has succeeded - but\n    GetAgent reliably reports provisioningState.\n  #>\n  [CmdletBinding()]\n  param(\n    [Parameter(Mandatory)][string]$ProxyPath,\n    [Parameter(Mandatory)][string]$SubscriptionId,\n    [Parameter(Mandatory)][string]$ResourceGroupName,\n    [Parameter(Mandatory)][string]$WorkspaceName,\n    [Parameter(Mandatory)][string]$ProjectName,\n    [Parameter(Mandatory)][string]$AgentName,\n    [int]$TimeoutSeconds = 300,\n    [int]$IntervalSeconds = 5\n  )\n  $deadline = (Get-Date).AddSeconds($TimeoutSeconds)\n  while ((Get-Date) -lt $deadline) {\n    $results = Invoke-DiscoveryMcp -ProxyPath $ProxyPath -Calls @(\n      @{ name='GetAgent'; args=@{ subscriptionId=$SubscriptionId; resourceGroupName=$ResourceGroupName; workspaceName=$WorkspaceName; projectName=$ProjectName; agentName=$AgentName } }\n    )\n    $r = $results['2']\n    $obj = Get-DiscoveryMcpText -Response $r -AsJson\n    if ($obj -and $obj.provisioningState) {\n      if ($obj.provisioningState -eq 'Succeeded') { return $obj }\n      if ($obj.provisioningState -eq 'Failed')    { throw \"Agent '$AgentName' provisioning Failed: $($obj | ConvertTo-Json -Depth 10 -Compress)\" }\n    }\n    Start-Sleep -Seconds $IntervalSeconds\n  }\n  throw \"Timed out after ${TimeoutSeconds}s waiting for agent '$AgentName' to reach Succeeded.\"\n}\n```\n\u003C!-- END:embedded-Invoke-DiscoveryMcp.ps1 -->\n- Do not add `tools:` frontmatter to generated `.agent.md` files — Discovery tool IDs don't map to Copilot tool names, and a wrong list silently disables tools.\n- **Do not call `runSubagent agentName='microsoft-foundry'`.** That skill is not registered as a subagent in this workspace, and even when invoked directly it assumes an azd `.foundry\u002F` overlay that catalog agents don't have. Execute the deploy pipeline inline via Discovery MCP (`GetDiscoveryTool`, `UpsertAgent`, `GetAgent` provisioningState polling) + `az` CLI, as documented in Steps 7c–7e.\n- Do not push tool images to any registry other than the ACR named in Step 7c.2.\n- Do not request secrets through `vscode_askQuestions`; require the user to authenticate to Azure with `az login` directly in the terminal when needed. Do not ask for GitHub authentication for the public `microsoft\u002Fdiscovery` catalog fetch.\n\n## When to ask the user\n\nAsk **once, up front**, in **this order** (the order matters — each answer\nshapes the next prompt):\n\n1. **Deployment target** (Step 4c) — Local Copilot only \u002F Microsoft Discovery + Azure (from upstream) \u002F\n   Local app -> Microsoft Discovery + Azure (promote). Default =\n   `Local Copilot only` (cheapest, fastest, fully local).\n   This is the **first** user-facing prompt; everything else is scoped to\n   the answer here.\n2. **Discovery tenant + subscription + workspace + project** (Step 4d,\n   only when target is `Discovery` or `LocalToDiscovery`) — install the Microsoft Discovery\n   MCP server **without asking** if `agents action=registry.list` doesn't\n   already succeed (the user opted into the Discovery + Azure path; the\n   MCP is a hard prerequisite). Before starting the MCP server, prompt\n   the user **once** (single `vscode_askQuestions` call, two questions)\n   for the Azure **tenant ID** and **subscription ID** (Step 7a.2.5),\n   then run `az login --tenant \u003Cid>` and `az account set --subscription\n   \u003Cid>` on their behalf in a foreground terminal. Persist the choices to\n   `\u002Fmemories\u002Frepo\u002F`. After `az` is ready, restart the MCP server, then\n   present single-select prompts for workspace and project (sourced via\n   `ListWorkspaces` \u002F\n   `ListProjects` calls (always via `Invoke-DiscoveryMcp`; never depend on the\n   VS Code deferred `mcp_microsoft-dis_*` tools surfacing). Always list the existing agents in\n   the chosen project before continuing, and confirm before moving on to\n   the agent picker. **These four prompts (tenant, subscription,\n   workspace, project) are mandatory on every Discovery run — never\n   skip them based on saved values in `\u002Fmemories\u002Frepo\u002F`. Saved values\n   are used only to mark the corresponding option as `recommended` in\n   the picker.**\n3. **Agent selection** (Step 4e) — present the All \u002F Specific \u002F By group\n   prompt via `vscode_askQuestions`. This is mandatory; never default to\n   adding the whole catalog without confirmation. When target ==\n   `Discovery`, annotate options whose folder name matches an existing\n   agent in the project (from step 2) with `[ALREADY IN PROJECT]` so the\n   user knows what will be updated by `UpsertAgent`.\n4. **Local runtime readiness** (Step 4f, only when target == `Local`) —\n  detect Podman\u002FDocker availability. If both are installed, ask once which\n  runtime the user prefers (default `podman`). If only one is installed,\n  auto-select it. If neither is installed, ask once whether to install\n  Podman automatically; on yes run `winget install --id RedHat.Podman --accept-source-agreements --accept-package-agreements`, on no continue with a clear warning that container-based tools cannot run until Podman or Docker is installed.\n5. **Overwrite conflicts** — if any folder in `$selected` already exists\n   locally, ask once whether to overwrite. Default = no.\n6. **Azure deployment configuration** (Step 7c.2, only when target == `Discovery`\n   **and** Step 7c found at least one tool that needs building) —\n   subscription, resource group, ACR, region. Foundry project is pre-filled\n   from Step 4d; the user only overrides it if they explicitly need a\n   different target. Ask all in a single `vscode_askQuestions` call. Pre-fill\n   defaults from `az account show` and any prior values stored in\n   `\u002Fmemories\u002Frepo\u002F`. **Skip entirely when every declared tool already\n   exists as an ARM resource** (the common case for shared catalog images).\n7. **Azure MCP install** (Step 7b, only when target is `Discovery` or `LocalToDiscovery`) — if a\n   relevant Azure plugin is `metadata_only`, ask once whether to install it.\n   Default = no (fall back to `az` CLI).\n8. **Agent overwrite** (Step 7e) — if an agent with the same name already\n   exists in the target Discovery project (visible from `ListAgents` in\n   Step 4d), ask once before calling `UpsertAgent` (which will update the\n   existing definition in place). Default = no.\n\nDo NOT ask whether to pre-build local images when `$deployTarget == 'Local'` —\nthat step never builds images. Ask runtime readiness only (Step 4f).\nEach generated agent will build its own image lazily on first invocation,\ntrying Podman first and Docker second, only if the image is not already present.\n\nDo not launch a GitHub device-flow prompt in Step 2. The upstream\n`microsoft\u002Fdiscovery` repository is public, so GitHub authentication is not\npart of this workflow. `az login` in Step 7a.2.5 is still launched on the\nuser's behalf as soon as tenant + subscription are picked.\n\nOtherwise run end-to-end without further prompting.\n\n\n\n\n\n",{"name":5,"license":16,"metadata":55,"description":7},{"author":56,"version":57,"changelog":58},"Internal","1.16.0",[59,60,61,62,63,64,65,66,67,68,69],"1.16.0: LocalToDiscovery promote now sources the agent `name` and `description` from the .github\u002Fagents\u002F\u003Cname>.agent.md companion frontmatter (same source of truth as `instructions`), NOT from discovery_catalog\u002F\u003Cname>\u002Fagent.yaml, for BOTH tool-bearing and toolless agents. Added Get-AgentMdFrontmatterValue helper (Step 4c.LTD), updated the 4c.LTD classification, Step 7e.1 field sourcing + code, Step 7e.4 description bullet, and the Step 7g guard-rail. Description is still truncated to the 512-char Foundry cap; falls back to agent.yaml#description only when the companion has none.","1.15.0: Fixed a CRLF line-ending bug that produced a truncated (~369-char) instructions body on Windows companions. Get-AgentMdInstructions and Convert-PromoteInstructionsForTool now use '\\r?\\n---\\r?\\n' (not '\\n---\\n') for the bootstrap horizontal-rule delimiter — a bare '\\n---\\n' never matches a CRLF companion, so the '|\\z' fallback in Convert previously swallowed the whole prompt. Added a Step 7e.1 length sanity-check (throw if \u003C500 chars). Hardened Step 7e.4 description sourcing with the 512-char Foundry cap (bare Failed \u002F foundryDetails=null is a description-length problem, not tool-binding). Added Step 7c guidance: a previously-deployed tool ARM can be deleted (404) while its image survives in ACR — check 'az acr repository show-tags' and re-register the tool ARM without rebuilding when the image is present.","1.14.0: LocalToDiscovery promote now rewrites tool-bearing agents' cloud instructions to reference the deployed Discovery tool instead of a local Podman\u002FDocker image. Added Convert-PromoteInstructionsForTool (Step 4c.LTD) which strips the container bootstrap preamble, scrubs residual podman\u002Fdocker build\u002Fpull\u002Fpush\u002Fimage-inspect lines and discovery_catalog\u002F...\u002Ftools\u002F... build-context references, and appends a 'Tool execution (Microsoft Discovery)' note naming the deployed tool(s). Step 7e.1 applies it for $agentHasCatalogFolder agents and requires each declared tool to be provisioningState=Succeeded with its image in the workspace ACR before UpsertAgent. Added a Step 7g guard-rail.","1.13.0: LocalToDiscovery (promote) now sources the agent picker from .github\u002Fagents\u002F*.agent.md (the local-app companions) instead of requiring a discovery_catalog\u002F\u003Cname>\u002F folder. Agents are classified into tool-bearing (has discovery_catalog folder + agent.yaml + tools) vs toolless (companion only, created locally with no container tool). Toolless agents skip Step 7c\u002F7d entirely and get instructions from the .agent.md body (frontmatter for name\u002Fdescription, body minus the container-bootstrap preamble for instructions) with an empty toolIds. Added Get-AgentMdInstructions helper, $agentHasCatalogFolder classification, and relaxed the 7g 'source of truth' guard-rail so a missing discovery_catalog folder is valid for toolless promotes.","1.12.0: Hardened the Discovery deploy path from a real promotion run. Tool ARM registration now requires properties.definitionContent to be a JSON object built with [ordered]@{} (raw tool.yaml string fails InvalidType) and passes the body via a temp file with --body @file. code_environments[].language must be normalized to python3 (python passes the tool PUT but breaks Foundry agent-binding with a bare Failed). Added az acr build Windows console UnicodeEncodeError guidance (set PYTHONIOENCODING=utf-8; poll az acr task list-runs instead of rebuilding). Added Step 7e recovery flow for fast tool-binding failures: isolate prompt vs tool by upserting without toolIds, fix language, wait ~30-60s for Foundry propagation before rebinding, and use GetAgentOperation (operationId) to extract the real error when GetAgent reports a bare Failed.","1.11.0: Added a third deployment target (LocalToDiscovery) that promotes an agent already added to the local Copilot app — its local discovery_catalog\u002F\u003Cname>\u002F folder and locally-built tool container — up to a specific Microsoft Discovery project + Azure without re-fetching or refreshing from upstream. Source of truth is the local folder; tool images are pushed from the local build context or the locally-built image. Added $deployToCloud \u002F $sourceMode helper flags, Step 4c.LTD (local catalog index), Step 5 skip for the local source, and Step 7d.LTD (push local image).","1.10.1: Hardened local generation: require temp .ps1 execution for multi-line scripts, fix .agent.md stem detection, parse YAML block-scalar descriptions correctly, and write generated .agent.md files with read\u002Fwrite sharing to avoid transient editor locks.","1.10.0: Changed upstream source from private microsoft\u002Fdiscovery-catalog agents\u002Fmicrosoft\u002F to public microsoft\u002Fdiscovery agents\u002F, removing GitHub authentication requirements.","1.9.0: Added Local runtime selection flow (Podman\u002FDocker detection, defaulting, optional Podman auto-install) and changed generated .agent.md bootstrap instructions to try Podman first then Docker as fallback.","1.8.0: Embedded discovery-mcp-proxy.ps1 and Invoke-DiscoveryMcp.ps1 directly in SKILL.md and changed Step 4d\u002F7a to extract them into .vscode, so the skill can be distributed as one file.","1.7.0: Co-located proxy + Invoke-DiscoveryMcp helper as sibling files. Made scripted stdio invocation the canonical MCP path (no longer depends on VS Code surfacing mcp_microsoft-dis_* tools mid-session). Replaced GetAgentOperation polling with GetAgent provisioningState polling. Bumped ARM api-version to 2026-06-01. Added explicit 'agents are NOT an ARM resource type' callout.","main","a7d5fef00a8d15e0705c88f2c53a61c02e738526","skills\u002Fadd-example-agents",101,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery","https:\u002F\u002Fgithub.com\u002Fmicrosoft","https:\u002F\u002Fopensource.microsoft.com","Open source projects and samples from Microsoft","2026-11-14 07:24:09",{"source":9,"skillName":5,"commands":80,"prompt":90,"zipAvailable":91},[81,84,87],{"tool":82,"command":83},"npx","npx skills add microsoft\u002Fdiscovery --skill add-example-agents",{"tool":85,"command":86},"bunx","bunx skills add microsoft\u002Fdiscovery --skill add-example-agents",{"tool":88,"command":89},"pnpm","pnpm dlx skills add microsoft\u002Fdiscovery --skill add-example-agents","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery\u002Fblob\u002Fmain\u002Fskills\u002Fadd-example-agents\u002FSKILL.md",true,[],[94,102,121,147,166,184],{"skillNo":95,"name":96,"nameZh":17,"description":97,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":101},"01M78JX3QZ6SK68TQDMZ5QCCYD","quickstart-runner","Follow a supplied full QuickStart Scenario guide and its exact input files from a fresh Discovery project. Use for run this QuickStart, BioPharma, SiPhy, CMS or Bookshelf setup. Check readiness, obtain separate setup and execution approvals, and validate actual outputs. Do not replace the guide with a generated profile or infer permission from examples.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery\u002Fblob\u002Fmain\u002Fskills\u002Fquickstart-runner\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":103,"name":104,"nameZh":17,"description":105,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":50},"01M6PJFHF9C2GSFK8DFW6D5RF7","token-estimator-mvp","Estimate AI planning ranges from a work description or explicitly authorized safe project context. Provides coarse class ranges or conditional planning bases without requiring token guesses.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery\u002Fblob\u002Fmain\u002Fskills\u002Ftoken-estimator-mvp\u002FSKILL.md",[],[109,110,111,112,113,114,115,116,117,118,119,120],"mvp","token estimator mvp","token","bases","work","estimate","planning","project","safe","conditional","project context","context",{"skillNo":122,"name":123,"nameZh":17,"description":124,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":50},"01M6M0MTE9BST8PT7ECHCC5KJK","build-research-paper","Cross-domain \u002F Scientific writing and publication — Build\nbeautifully-formatted, arxiv-ready research paper PDFs from a mix of\nhand-authored LaTeX and\u002For markdown + PNG figures, using `tectonic`\n(default) or `pandoc` (escape hatch). Captures the reusable pattern that\nresearch projects keep re-discovering: `report\u002Fmain.tex` + `references.bib`\n+ `generate_figures.py` + iterative feedback\u002Fresponse scaffolding, all\nbuildable with a single command. WHEN: write a research paper, arxiv\nsubmission, prepub, generate PDF from markdown, LaTeX paper, build main.tex,\njournal manuscript, referee revision, response to referee, resubmission\npackage, publication-quality figures, matplotlib publication style, tectonic\nbuild, pandoc build, generate arxiv-ready PDF, bibliography from BibTeX.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery\u002Fblob\u002Fmain\u002Fskills\u002Fbuild-research-paper\u002FSKILL.md",[],[128,129,130,131,132,133,134,135,70,136,137,138,139,140,141,142,143,144,145,146],"build research paper","build","paper","research","hand","journal","writing","generate pdf","tectonic","PDF","references","scientific","command","default","ready","projects","mix","scaffolding","re",{"skillNo":148,"name":149,"nameZh":150,"description":151,"descriptionZh":152,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":153,"categories":154,"keywords":161,"publishedAt":50},"01M69BE703VQGX4F9Z5J4MTJV2","migrate-podman-containerfile","Podman Containerfile 迁移","Migrate a Podman Containerfile to the canonical Dockerfile required by the Discovery catalog. Use when a PR fails POL-022, a tool contains Containerfile or Dockerfile.in, or a contributor asks to convert Podman build files for Docker. Creates the Dockerfile directly only when the migration is mechanically safe and refuses ambiguous preprocessing or multi-file builds.","将 Podman Containerfile 迁移为 Discovery 目录要求的规范 Dockerfile。当 PR 未通过 POL-022 检查、某个工具包含 Containerfile 或 Dockerfile.in，或贡献者要求将 Podman 构建文件转换为 Docker 构建文件时使用。仅在迁移在机械上安全时直接创建 Dockerfile，并拒绝处理存在歧义的预处理或多文件构建。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fmigrate-podman-containerfile\u002FSKILL.md",[155,158],{"categoryNo":156,"categoryName":157,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQGD4WETX0HM3SM9QKQ15B","SRE 工程师",{"categoryNo":159,"categoryName":160,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BSTR9076S7ETYWTQVVK45G","云原生计算与容器编排",[162,38,163,164,46,117,165],"migrate podman containerfile","discovery catalog","pr","dockerfile",{"skillNo":167,"name":168,"nameZh":169,"description":170,"descriptionZh":171,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":172,"categories":173,"keywords":178,"publishedAt":50},"01M69BE4KN4J5R2RY3927C8PM6","discovery-services-starter-kit-deployer","Discovery 入门工具包部署","Deploy Discovery catalog starter-kits end-to-end: validate kit.json agentRefs, build and deploy every referenced agent tool, deploy each referenced agent individually, and summarize deployed agents\u002Ftools plus customer-ready sample prompts. Use this skill whenever the user asks to deploy a Discovery starter-kit or deploy all agents listed in starter-kits\u002F*\u002Fkit.json.","端到端部署 Discovery 目录中的入门工具包（starter-kit）：验证 kit.json 中的 agentRefs、构建并部署每个引用的智能体工具、逐一部署每个引用的智能体，并汇总已部署的智能体\u002F工具以及可直接提供给客户的示例提示词。当用户要求部署 Discovery 入门工具包，或部署 starter-kits\u002F*\u002Fkit.json 中列出的所有智能体时使用此技能。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fdiscovery-services-starter-kit-deployer\u002FSKILL.md",[174,175],{"categoryNo":156,"categoryName":157,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":176,"categoryName":177,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BQNXPY1AV6BSR5VKHDMWRH","部署与发布管理",[179,180,181,163,182,183],"discovery services starter kit deployer","summarize","validate","deploy","customer",{"skillNo":185,"name":186,"nameZh":187,"description":188,"descriptionZh":189,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":190,"categories":191,"keywords":194,"publishedAt":50},"01M69BE20F244MGDJC74AFXGZ2","discovery-services-agent-deployer","Discovery 智能体端到端部署","Deploy Discovery catalog agents end-to-end with one command: discover the agent, build and bind its tool when present, skip tool stages for agents without tools, deploy the agent, and optionally run validation. Use this skill whenever the user asks to deploy a Discovery agent, publish or rebuild an agent tool image, register a Discovery tool from a repo Dockerfile\u002Ftool.yaml, resume a failed deployment, or produce a dry-run deployment plan for an agent in this catalog.","通过一个命令端到端部署 Discovery 目录中的智能体：发现智能体、在存在工具时构建并绑定该工具、对没有工具的智能体跳过工具相关阶段、部署智能体，并可选择运行验证。当用户要求部署 Discovery 智能体、发布或重建智能体工具镜像、从仓库中的 Dockerfile\u002Ftool.yaml 注册 Discovery 工具、恢复失败的部署，或为该目录中的某个智能体生成预演（dry-run）部署计划时使用此技能。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdiscovery\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fdiscovery-services-agent-deployer\u002FSKILL.md",[192,193],{"categoryNo":156,"categoryName":157,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":176,"categoryName":177,"taxonomyType":28,"taxonomyTypeDesc":29},[195,163,182,49,34,36,165],"discovery services agent deployer"]