# Steps installer for Windows. The app fills in the origin and the lasting # instruction before serving this file. The token comes from STEPS_TOKEN or a hidden prompt. # It is never printed and never written into a rule or instruction file. # -Uninstall removes the steps server, marked blocks, and installer backups named # file.bak.YYYYMMDDHHMMSS or file.bak.YYYYMMDDHHMMSS.N. Other files are left alone. # -KeepBackups leaves those backups in place. A failed edit restores the file and keeps that backup. param( [switch]$DryRun, [switch]$Uninstall, [switch]$KeepBackups, [switch]$All, [switch]$Yes, [switch]$StoreToken, [switch]$NoProject, [string]$Project, [string[]]$Harness ) $ErrorActionPreference = "Stop" $Origin = if ($env:STEPS_URL) { $env:STEPS_URL.TrimEnd("/") } else { "https://usesteps.dev" } $Instructions = @' Steps is the organization's library of step-by-step workflows: the source of truth for how work should be done. People author workflows in Steps; you follow them. Finding tools are read-only and already authenticated. Documenting needs a Can edit token. Publish, unpublish, activate_version, and visibility tools need a Can publish token. Whenever someone asks to write up, follow, recall, or change a process, procedure, checklist, or how-to, search Steps first. Do this without waiting for them to say "Steps". That includes onboarding, refunds, provisioning, access, deploys, resets, shipping a change, and anything else the organization might have documented. Before a multi-step task, search Steps for a matching workflow and follow it when one exists. Use Find, then follow the checklist on the first hit: 1. search_workflows with the user's own words. include_checklist defaults to true on this tool: the first hit's checklist field is the same markdown as export_diagram_markdown. Follow that checklist. Read why, fit_reasons, evidence, and confidence. diagram_id is the numeric id. next_step is a sentence of guidance, not an id and not a tool argument. ask_user is a question to show the human, not a tool. 2. If status is needs_more_info, ask the human the ask_user question and offer suggested_refinements, then call search_workflows again. Do not invent steps. Do not call a tool named ask_user. The checklist is omitted when the first hit's confidence is low. 3. get_workflow with the chosen id only when you need another hit, an older version, or the checklist field is absent. id may be a number or a string. Leave full false unless you need older versions or the step graph. full false still includes a versions array with only the active version, and modules[].diagrams without steps. full true lists every version with steps and transitions and keeps modules[].diagrams. 4. export_diagram_markdown with the numeric diagram_id when checklist is absent, or when you want a diagram other than the first hit. Do not pass next_step; it is a sentence and returns 404. Follow the markdown, including the Discussion under each step. Ask the human when a branch is ambiguous. Discussions come with the checklist, the export, and get_workflow. include_discussions defaults to true. Pass false only when you want the steps alone. get_discussions filters one workflow by step_id or by resolved status. A comment can hold the answer the step does not, including a contact someone typed in the thread. Documenting: Edits apply to the version you are changing. Edits to the current published version are live immediately and do not create a new draft. Edits to a draft are not live until someone makes it current (activate_version, needs Can publish). A new version is created only by create_version (POST /api/v1/modules/:id/versions). Historical versions cannot be edited until someone makes them current. Comments do not create a version. Leaving Can publish off does not stop Can edit from changing the current version. lock_version is optional on updates and deletes; always prefer sending lock_version from the last read so concurrent edits are not overwritten. Omitting lock_version applies the change to the latest row without that stale check. On stale_object, error.current has the latest lock_version and fields — re-apply your change on top of that content (merge conflicts; do not blindly overwrite), then retry with the new lock_version. When publish, unpublish, or activate_version is refused because of the current status, error.state has machine, status, attempted, allowed, and next — follow next instead of retrying the same call. Deletes require confirm_name that matches the title exactly — show the UI warning and ask the user to type the exact name; never invent confirm_name. Suite UI: Delete “{title}”? This cannot be undone. then Type the suite name to confirm. Workflow UI: Delete “{title}”? This cannot be undone. then Type the workflow name to confirm. create_workflow, create_module, add_step, create_transition, create_frame, upload_media, reply_comment, and the other documenting tools exist when the token can edit. publish_suite, unpublish_suite, publish_module, unpublish_module, and activate_version need Can publish. If none matches, and the task is repeatable or likely to come up again, ask the user once whether to turn it into a new Steps workflow. Offer a short draft: a title, a suggested suite (an existing one by name, or a new suite if none fits), and numbered steps. Then point them to https://usesteps.dev/authoring, or to that suite. If the token can edit, create_workflow saves that draft. Otherwise these tools cannot create it. After a task that deviated from an existing workflow, suggest a new version of that workflow instead of a duplicate. Ask at most once per task. Skip trivial one-off tasks. A no is final for that task. Do not ask the user to paste a token into chat. '@ $Begin = "" $End = "" $HashBegin = "# BEGIN STEPS CONNECT" $HashEnd = "# END STEPS CONNECT" $Known = @("cursor", "claude", "claude-desktop", "codex", "gemini", "opencode", "goose") $script:Changes = @() $script:StoreToken = [bool]$StoreToken $script:SecretFiles = @() $script:SecretBackups = @() $script:DeletedBackups = @() $script:KeptFailure = @() $script:Restored = @() $script:CreatedThisRun = @() function Fail($Message) { Write-Error "steps-connect: $Message" exit 1 } function Add-Change($Action, $Path) { $script:Changes += " ${Action}: $Path" } function Get-RuleBody { @" Use Steps ($Origin). Search before a multi-step task. If you would add a workflow or suite, ask the user once and send them to $Origin/authoring. $($Instructions.Trim()) MCP at $Origin/mcp is read-only. It cannot create or edit a workflow. Ask the user to open $Origin/authoring. "@ } function Get-Marked([string]$Body) { "$Begin`n$($Body.Trim())`n$End`n" } function Backup-File($Path) { $stamp = Get-Date -Format "yyyyMMddHHmmss" $dest = "$Path.bak.$stamp" $n = 0 while (Test-Path -LiteralPath $dest) { $n += 1 $dest = "$Path.bak.$stamp.$n" } if ($DryRun) { Add-Change "would-backup" $dest if ($Uninstall) { $body = "" if (Test-Path -LiteralPath $Path) { $body = [IO.File]::ReadAllText($Path) } if ($env:STEPS_TOKEN -and $body.Contains($env:STEPS_TOKEN)) { Add-Change "would-restrict" $dest if ($script:SecretBackups -notcontains $dest) { $script:SecretBackups += $dest } } if (-not $KeepBackups) { Add-Change "would-delete-backup" $dest if ($script:DeletedBackups -notcontains $dest) { $script:DeletedBackups += $dest } } } return $null } Copy-Item -LiteralPath $Path -Destination $dest Add-Change "backup" $dest $script:CreatedThisRun += $dest if ($env:STEPS_TOKEN) { $copied = [IO.File]::ReadAllText($dest) if ($copied.Contains($env:STEPS_TOKEN)) { Protect-TokenFile $dest -Quiet if ($script:SecretBackups -notcontains $dest) { $script:SecretBackups += $dest } } } return $dest } function Protect-TokenFile($Path, [switch]$Quiet) { if ($DryRun -or -not (Test-Path -LiteralPath $Path)) { if (-not $Quiet) { Add-Change "would-restrict" $Path } return } $restricted = $false try { $acl = New-Object System.Security.AccessControl.FileSecurity $acl.SetAccessRuleProtection($true, $false) $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($identity, "Read,Write", "Allow") $acl.AddAccessRule($rule) Set-Acl -LiteralPath $Path -AclObject $acl $restricted = $true } catch { $restricted = $false } if (-not $restricted -and (Get-Command chmod -ErrorAction SilentlyContinue)) { & chmod 600 $Path if ($LASTEXITCODE -eq 0) { $restricted = $true } } if (-not $restricted) { Fail "could not limit $Path to the current user. The token was not printed." } if (-not $Quiet) { Add-Change "restrict" $Path } } function Write-TextFile($Path, [string]$Content, [switch]$SecretOk) { if (-not $Content.EndsWith("`n")) { $Content += "`n" } $holds = $env:STEPS_TOKEN -and $Content.Contains($env:STEPS_TOKEN) if ($holds -and -not $SecretOk) { Fail "refusing to store the token in $Path" } if ($holds -and $SecretOk -and ($script:SecretFiles -notcontains $Path)) { $script:SecretFiles += $Path } $exists = Test-Path -LiteralPath $Path $old = if ($exists) { [IO.File]::ReadAllText($Path) } else { $null } if ($old -eq $Content) { Add-Change "unchanged" $Path if ($holds -and $SecretOk) { Protect-TokenFile $Path } return } if ($DryRun) { Add-Change ($(if ($exists) { "would-update" } else { "would-write" })) $Path if ($holds -and $SecretOk) { Add-Change "would-restrict" $Path } if ($Uninstall -and $exists) { Backup-File $Path | Out-Null } return } $dir = Split-Path -Parent $Path if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null } $backup = $null if ($exists) { $backup = Backup-File $Path; Add-Change "update" $Path } else { Add-Change "write" $Path } try { [IO.File]::WriteAllText($Path, $Content) } catch { if ($backup) { Restore-FromBackup $Path $backup } return } if ($holds -and $SecretOk) { Protect-TokenFile $Path } Complete-Edit $Path $backup | Out-Null } function Test-AcceptableToken([string]$Token) { # Real PATs are steps_pat_ plus hex and base64url. -match is case-insensitive, # so this uses a case-sensitive regex. Newlines and quotes never reach a writer. if ([string]::IsNullOrEmpty($Token) -or $Token.Length -lt 20) { return $false } return [regex]::IsMatch($Token, '^steps_pat_[A-Za-z0-9_-]+$') } function Format-TomlString([string]$Value) { # TOML basic string, also used for YAML double quotes. $builder = New-Object System.Text.StringBuilder [void]$builder.Append('"') foreach ($ch in $Value.ToCharArray()) { $code = [int]$ch if ($ch -eq '\') { [void]$builder.Append('\\') } elseif ($ch -eq '"') { [void]$builder.Append('\"') } elseif ($ch -eq "`b") { [void]$builder.Append('\b') } elseif ($ch -eq "`t") { [void]$builder.Append('\t') } elseif ($ch -eq "`n") { [void]$builder.Append('\n') } elseif ($ch -eq "`f") { [void]$builder.Append('\f') } elseif ($ch -eq "`r") { [void]$builder.Append('\r') } elseif ($code -lt 32 -or $code -eq 127) { [void]$builder.Append(('\u{0:X4}' -f $code)) } else { [void]$builder.Append($ch) } } [void]$builder.Append('"') return $builder.ToString() } function Get-AuthHeader([string]$EnvForm) { if (-not $script:StoreToken -or $Uninstall) { return $EnvForm } if (-not (Test-AcceptableToken $env:STEPS_TOKEN)) { Fail "STEPS_TOKEN must be a personal access token starting with steps_pat_ and containing only letters, digits, underscore, and hyphen. The value was not printed." } return "Bearer $($env:STEPS_TOKEN)" } function Remove-OurFile($Path) { if (-not (Test-Path -LiteralPath $Path)) { Add-Change "unchanged" $Path; return } if ($DryRun) { Add-Change "would-delete" $Path if ($Uninstall) { Backup-File $Path | Out-Null } return } $backup = Backup-File $Path try { Remove-Item -LiteralPath $Path -Force } catch { if ($backup) { Restore-FromBackup $Path $backup } return } Add-Change "delete" $Path Complete-Edit $Path $backup | Out-Null } function Restore-FromBackup($Path, $Backup) { if ($script:KeptFailure -notcontains $Backup) { $script:KeptFailure += $Backup } $parent = Split-Path -Parent $Path try { if ($parent -and -not (Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Force -Path $parent | Out-Null } Copy-Item -LiteralPath $Backup -Destination $Path -Force Add-Change "restored" $Path $script:Restored += "$Path (backup kept at $Backup)" } catch { Add-Change "restore-failed" $Path $script:Restored += "$Path (restore copy failed; backup kept at $Backup)" } } function Remove-InstallerBackup($Backup) { if ($KeepBackups -or -not $Backup) { return } if ($script:KeptFailure -contains $Backup) { return } if (-not (Test-Path -LiteralPath $Backup)) { return } try { Remove-Item -LiteralPath $Backup -Force -ErrorAction Stop } catch { if ($script:KeptFailure -notcontains $Backup) { $script:KeptFailure += $Backup } $script:Restored += "$Backup (could not delete backup)" return } if ($script:DeletedBackups -notcontains $Backup) { $script:DeletedBackups += $Backup } Add-Change "removed-backup" $Backup } function Complete-Edit($Path, $Backup) { if (-not $Backup -or -not $Uninstall) { return $true } if (Test-Parses $Path) { Remove-InstallerBackup $Backup return $true } Restore-FromBackup $Path $Backup return $false } function Test-StructuredConfig($Path) { $ext = [IO.Path]::GetExtension($Path).ToLower() $name = [IO.Path]::GetFileName($Path).ToLower() return ($ext -in @(".json", ".jsonc", ".toml", ".yaml", ".yml")) -or $name.EndsWith(".jsonc") } function Test-DelimitersBalanced([string]$Text) { $curly = 0 $square = 0 $inStr = $false $esc = $false foreach ($ch in $Text.ToCharArray()) { if ($inStr) { if ($esc) { $esc = $false; continue } if ($ch -eq '\') { $esc = $true; continue } if ($ch -eq '"') { $inStr = $false } continue } if ($ch -eq '"') { $inStr = $true; continue } if ($ch -eq '{') { $curly += 1 } elseif ($ch -eq '}') { $curly -= 1; if ($curly -lt 0) { return $false } } elseif ($ch -eq '[') { $square += 1 } elseif ($ch -eq ']') { $square -= 1; if ($square -lt 0) { return $false } } } return ((-not $inStr) -and $curly -eq 0 -and $square -eq 0) } function Test-ExternalParse($Kind, $Text) { $py = $null foreach ($name in @("python3", "python")) { $cmd = Get-Command $name -ErrorAction SilentlyContinue if ($cmd) { $py = $cmd.Source; break } } if (-not $py) { return $null } if ($Kind -eq "toml") { $code = "import sys, tomllib`ntry:`n tomllib.loads(sys.stdin.read())`nexcept Exception:`n sys.exit(1)`n" } else { $code = "import sys`ntry:`n import yaml`nexcept Exception:`n sys.exit(2)`ntry:`n yaml.safe_load(sys.stdin.read())`nexcept Exception:`n sys.exit(1)`n" } $tmp = [IO.Path]::GetTempFileName() + ".py" try { [IO.File]::WriteAllText($tmp, $code) $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $py $psi.Arguments = "`"$tmp`"" $psi.RedirectStandardInput = $true $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true $psi.UseShellExecute = $false $psi.CreateNoWindow = $true $proc = New-Object System.Diagnostics.Process $proc.StartInfo = $psi [void]$proc.Start() $proc.StandardInput.Write($Text) $proc.StandardInput.Close() if (-not $proc.WaitForExit(15000)) { try { $proc.Kill() } catch {} return $null } if ($proc.ExitCode -eq 0) { return $true } if ($proc.ExitCode -eq 2) { return $null } return $false } catch { return $null } finally { Remove-Item -LiteralPath $tmp -ErrorAction SilentlyContinue } } function Test-Parses($Path) { if (-not (Test-Path -LiteralPath $Path)) { return $true } $text = [IO.File]::ReadAllText($Path) if (-not (Test-StructuredConfig $Path)) { return $true } $ext = [IO.Path]::GetExtension($Path).ToLower() if ($ext -in @(".json", ".jsonc") -or ([IO.Path]::GetFileName($Path).ToLower().EndsWith(".jsonc"))) { if ([string]::IsNullOrWhiteSpace($text)) { return $true } try { $null = $text | ConvertFrom-Json -ErrorAction Stop return $true } catch { return $false } } $kind = if ($ext -eq ".toml") { "toml" } else { "yaml" } $external = Test-ExternalParse $kind $text if ($null -ne $external) { return [bool]$external } return (Test-DelimitersBalanced $text) } function Test-InstallerBackupName($OriginalName, $CandidateName) { $prefix = "$OriginalName.bak." if (-not $CandidateName.StartsWith($prefix)) { return $false } $rest = $CandidateName.Substring($prefix.Length) return $rest -match '^\d{14}(\.\d+)?$' } function Get-ManagedPaths($ProjectDir) { $config = if ($env:XDG_CONFIG_HOME) { $env:XDG_CONFIG_HOME } else { Join-Path $env:USERPROFILE ".config" } $codex = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $env:USERPROFILE ".codex" } $paths = @( (Join-Path $env:USERPROFILE ".cursor\mcp.json"), (Join-Path $env:USERPROFILE ".cursor\rules\steps.mdc"), (Join-Path $env:USERPROFILE ".claude.json"), (Join-Path $env:USERPROFILE ".claude\CLAUDE.md"), (Join-Path $codex "config.toml"), (Join-Path $codex "AGENTS.md"), (Join-Path $env:USERPROFILE ".gemini\settings.json"), (Join-Path $env:USERPROFILE ".gemini\GEMINI.md"), (Join-Path $config "opencode\opencode.jsonc"), (Join-Path $config "opencode\AGENTS.md"), (Join-Path $config "goose\config.yaml"), (Join-Path $config "goose\AGENTS.md"), (Join-Path $config "goose\.goosehints") ) if ($ProjectDir) { $paths += @( (Join-Path $ProjectDir ".cursor\mcp.json"), (Join-Path $ProjectDir ".cursor\rules\steps.mdc"), (Join-Path $ProjectDir "AGENTS.md"), (Join-Path $ProjectDir ".mcp.json"), (Join-Path $ProjectDir "CLAUDE.md"), (Join-Path $ProjectDir "GEMINI.md"), (Join-Path $ProjectDir ".goosehints") ) } return $paths } function Remove-OldInstallerBackups($ProjectDir) { if (-not $Uninstall) { return } $seen = @{} foreach ($kept in $script:KeptFailure) { $seen[$kept] = $true } $candidates = @() foreach ($path in (Get-ManagedPaths $ProjectDir)) { $parent = Split-Path -Parent $path if (-not $parent -or -not (Test-Path -LiteralPath $parent)) { continue } $name = Split-Path -Leaf $path foreach ($item in @(Get-ChildItem -LiteralPath $parent -Force -File -ErrorAction SilentlyContinue)) { if (Test-InstallerBackupName $name $item.Name) { $candidates += $item.FullName } } } foreach ($created in $script:CreatedThisRun) { if ((Test-Path -LiteralPath $created) -and ($candidates -notcontains $created)) { $candidates += $created } } foreach ($full in $candidates) { if ($seen.ContainsKey($full)) { continue } if (-not (Test-Path -LiteralPath $full)) { continue } $seen[$full] = $true if ($KeepBackups) { continue } if ($DryRun) { Add-Change "would-delete-backup" $full if ($script:DeletedBackups -notcontains $full) { $script:DeletedBackups += $full } continue } Remove-InstallerBackup $full } } function Read-JsonObject($Path) { if (-not (Test-Path -LiteralPath $Path)) { return [pscustomobject]@{} } $text = [IO.File]::ReadAllText($Path) if ([string]::IsNullOrWhiteSpace($text)) { return [pscustomobject]@{} } try { return ($text | ConvertFrom-Json) } catch { Fail "refusing to edit ${Path}: $($_.Exception.Message). The file was not changed." } } function Set-Prop($Object, $Name, $Value) { if ($Object.PSObject.Properties.Name -contains $Name) { $Object.$Name = $Value } else { $Object | Add-Member -NotePropertyName $Name -NotePropertyValue $Value } } function Escape-JsonString([string]$Text) { $sb = New-Object System.Text.StringBuilder [void]$sb.Append('"') foreach ($ch in $Text.ToCharArray()) { $code = [int]$ch if ($code -eq 34) { [void]$sb.Append('\"') } elseif ($code -eq 92) { [void]$sb.Append('\\') } elseif ($code -eq 8) { [void]$sb.Append('\b') } elseif ($code -eq 9) { [void]$sb.Append('\t') } elseif ($code -eq 10) { [void]$sb.Append('\n') } elseif ($code -eq 12) { [void]$sb.Append('\f') } elseif ($code -eq 13) { [void]$sb.Append('\r') } elseif ($code -lt 32) { [void]$sb.AppendFormat('\u{0:x4}', $code) } else { [void]$sb.Append($ch) } } [void]$sb.Append('"') return $sb.ToString() } # ConvertTo-Json on Windows PowerShell 5.1 turns a one-element array into a # scalar and would break another server's "args": ["--stdio"]. function Format-JsonText { param($Value, [int]$Level = 0) if ($null -eq $Value) { return "null" } if ($Value -is [bool]) { if ($Value) { return "true" } else { return "false" } } if ($Value -is [string] -or $Value -is [char]) { return (Escape-JsonString ([string]$Value)) } if ($Value -is [datetime]) { return (Escape-JsonString ($Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ"))) } if ($Value -is [System.ValueType]) { return $Value.ToString([Globalization.CultureInfo]::InvariantCulture) } $pad = " " * ($Level + 1) $close = " " * $Level if (($Value -is [System.Array]) -or ($Value -is [System.Collections.IList])) { $items = New-Object System.Collections.Generic.List[string] foreach ($item in $Value) { [void]$items.Add((Format-JsonText -Value $item -Level ($Level + 1))) } if ($items.Count -eq 0) { return "[]" } $body = ($items | ForEach-Object { $pad + $_ }) -join ",`n" return "[`n$body`n$close]" } $props = @($Value.PSObject.Properties) if ($props.Count -eq 0) { return "{}" } $lines = New-Object System.Collections.Generic.List[string] foreach ($prop in $props) { $rendered = Format-JsonText -Value $prop.Value -Level ($Level + 1) [void]$lines.Add($pad + (Escape-JsonString ([string]$prop.Name)) + ": " + $rendered) } $body = $lines -join ",`n" return "{`n$body`n$close}" } function Write-JsonFile($Path, $Object, [switch]$SecretOk) { $json = Format-JsonText -Value $Object if ($SecretOk) { Write-TextFile $Path $json -SecretOk } else { Write-TextFile $Path $json } } function Remove-NamedServer($Object, $Container, $Name) { $block = $Object.$Container if (-not $block) { return $false } if ($block.PSObject.Properties.Name -notcontains $Name) { return $false } $block.PSObject.Properties.Remove($Name) if (@($block.PSObject.Properties).Count -eq 0) { if ($Object.PSObject.Properties.Name -contains $Container) { $Object.PSObject.Properties.Remove($Container) } } return $true } function Update-ProjectServer($Path, $Container, $Server, [switch]$CreateMissing) { $exists = Test-Path -LiteralPath $Path if ($script:StoreToken -and -not $Uninstall) { if (-not $exists) { return } $data = Read-JsonObject $Path if (-not (Remove-NamedServer $data $Container "steps")) { Add-Change "unchanged" $Path return } if (@($data.PSObject.Properties).Count -eq 0) { Remove-OurFile $Path } else { Write-JsonFile $Path $data } return } if (-not $exists -and ($Uninstall -or -not $CreateMissing)) { return } $data = Read-JsonObject $Path $data = Set-Server $data $Container "steps" $Server if ($Uninstall -and @($data.PSObject.Properties).Count -eq 0) { if ($exists) { Remove-OurFile $Path } else { Add-Change "unchanged" $Path } } else { Write-JsonFile $Path $data } } function Get-HashSpan([string]$Text, [string]$Path) { $start = $Text.IndexOf($HashBegin) if ($start -lt 0) { return $null } $finish = $Text.IndexOf($HashEnd, $start + $HashBegin.Length) if ($finish -lt 0) { Fail "refusing to edit ${Path}: begin marker without an end marker. The file was not changed." } $after = $finish + $HashEnd.Length return @{ Start = $start; After = $after } } function Test-ConsoleInput { try { return -not [Console]::IsInputRedirected } catch { return $false } } function Set-Server($Object, $Container, $Name, $Value) { $block = $Object.$Container if (-not $block) { $block = [pscustomobject]@{} } if ($Uninstall) { if ($block.PSObject.Properties.Name -contains $Name) { $block.PSObject.Properties.Remove($Name) } if (@($block.PSObject.Properties).Count -eq 0) { if ($Object.PSObject.Properties.Name -contains $Container) { $Object.PSObject.Properties.Remove($Container) } } else { Set-Prop $Object $Container $block } } else { Set-Prop $block $Name $Value Set-Prop $Object $Container $block } return $Object } function Update-MarkedFile($Path) { $block = Get-Marked (Get-RuleBody) if (-not (Test-Path -LiteralPath $Path)) { if ($Uninstall) { Add-Change "unchanged" $Path; return } Write-TextFile $Path $block return } $text = [IO.File]::ReadAllText($Path) $start = $text.IndexOf($Begin) $finish = if ($start -ge 0) { $text.IndexOf($End, $start + $Begin.Length) } else { -1 } if ($start -ge 0 -and $finish -ge 0) { $after = $finish + $End.Length if ($after -lt $text.Length -and $text[$after] -eq "`n") { $after += 1 } if ($Uninstall) { $updated = $text.Substring(0, $start) + $text.Substring($after) if ([string]::IsNullOrWhiteSpace($updated)) { Remove-OurFile $Path } else { Write-TextFile $Path $updated } return } Write-TextFile $Path ($text.Substring(0, $start) + $block + $text.Substring($after)) return } if ($Uninstall) { Add-Change "unchanged" $Path; return } $sep = if ($text.EndsWith("`n`n") -or $text -eq "") { "" } elseif ($text.EndsWith("`n")) { "`n" } else { "`n`n" } Write-TextFile $Path ($text + $sep + $block) } function Require-Token { $needsValue = ((-not $DryRun -and -not $Uninstall) -or $script:StoreToken) if (-not $needsValue) { if ($env:STEPS_TOKEN -and -not $env:STEPS_TOKEN.StartsWith("steps_pat_")) { Fail "STEPS_TOKEN must start with steps_pat_. The value was not printed." } return } if (-not $env:STEPS_TOKEN) { if ($DryRun -or -not [Environment]::UserInteractive) { Fail "STEPS_TOKEN is not set. Export it and run again. The token is not printed." } $secure = Read-Host "Steps personal access token (input hidden)" -AsSecureString $ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure) try { $env:STEPS_TOKEN = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) } } if (-not (Test-AcceptableToken $env:STEPS_TOKEN)) { Fail "STEPS_TOKEN must be a personal access token starting with steps_pat_ and containing only letters, digits, underscore, and hyphen. The value was not printed." } } function Resolve-Project { if ($NoProject) { return $null } if ($Project) { if ((Test-Path -LiteralPath $Project) -and -not (Test-Path -LiteralPath $Project -PathType Container)) { Fail "project is not a directory: $Project" } return $Project } $cwd = (Get-Location).Path if ($cwd -eq $env:USERPROFILE) { return $null } foreach ($name in @(".git", "Cargo.toml", "package.json", "go.mod", "pyproject.toml", ".cursor")) { if (Test-Path -LiteralPath (Join-Path $cwd $name)) { return $cwd } } return $null } function Install-Cursor($ProjectDir) { $mcp = Join-Path $env:USERPROFILE ".cursor\mcp.json" $data = Read-JsonObject $mcp $server = [pscustomobject]@{ url = "$Origin/mcp"; headers = [pscustomobject]@{ Authorization = (Get-AuthHeader 'Bearer ${env:STEPS_TOKEN}') } } $data = Set-Server $data "mcpServers" "steps" $server $allow = $script:StoreToken -or $Uninstall if ($Uninstall -and @($data.PSObject.Properties).Count -eq 0) { Remove-OurFile $mcp } else { Write-JsonFile $mcp $data -SecretOk:$allow } $mdc = "---`ndescription: Search Steps first, and ask before creating a workflow or suite`nalwaysApply: true`n---`n`n$(Get-Marked (Get-RuleBody))" # Uninstall may still remove a legacy %USERPROFILE%\.cursor\rules\steps.mdc from older installs. $homeRule = Join-Path $env:USERPROFILE ".cursor\rules\steps.mdc" if ($Uninstall) { if ((Test-Path -LiteralPath $homeRule) -and ([IO.File]::ReadAllText($homeRule).Contains($Begin))) { Remove-OurFile $homeRule } else { Add-Change "unchanged" $homeRule } } elseif ((Test-Path -LiteralPath $homeRule) -and ([IO.File]::ReadAllText($homeRule).Contains($Begin))) { Add-Change "unchanged" $homeRule } if ($ProjectDir) { $envServer = [pscustomobject]@{ url = "$Origin/mcp"; headers = [pscustomobject]@{ Authorization = 'Bearer ${env:STEPS_TOKEN}' } } Update-ProjectServer (Join-Path $ProjectDir ".cursor\mcp.json") "mcpServers" $envServer $rule = Join-Path $ProjectDir ".cursor\rules\steps.mdc" if ($Uninstall) { if ((Test-Path -LiteralPath $rule) -and ([IO.File]::ReadAllText($rule).Contains($Begin))) { Remove-OurFile $rule } else { Add-Change "unchanged" $rule } } else { Write-TextFile $rule $mdc } Update-MarkedFile (Join-Path $ProjectDir "AGENTS.md") } Add-Change "manual" "open Customize in the sidebar -> Rules (User Rules; paste the text printed below)" } function Install-Claude($ProjectDir) { $path = Join-Path $env:USERPROFILE ".claude.json" $data = Read-JsonObject $path $server = [pscustomobject]@{ type = "http" url = "$Origin/mcp" headers = [pscustomobject]@{ Authorization = (Get-AuthHeader 'Bearer ${STEPS_TOKEN}') } } $data = Set-Server $data "mcpServers" "steps" $server $allow = $script:StoreToken -or $Uninstall if ($Uninstall -and @($data.PSObject.Properties).Count -eq 0) { Remove-OurFile $path } else { Write-JsonFile $path $data -SecretOk:$allow } Update-MarkedFile (Join-Path $env:USERPROFILE ".claude\CLAUDE.md") if ($ProjectDir) { $proj = Join-Path $ProjectDir ".mcp.json" $projectServer = [pscustomobject]@{ type = "http" url = "$Origin/mcp" headers = [pscustomobject]@{ Authorization = 'Bearer ${STEPS_TOKEN}' } } Update-ProjectServer $proj "mcpServers" $projectServer -CreateMissing Update-MarkedFile (Join-Path $ProjectDir "CLAUDE.md") } } function Install-ClaudeDesktop { Add-Change "manual" "Claude Desktop has no remote-MCP config file. Settings -> Connectors -> Add custom connector. Name: Steps. URL: $Origin/mcp. Header: Authorization. Value: Bearer and the STEPS_TOKEN value (not printed). Paste the instruction into the app's custom instructions." } function Install-Codex($ProjectDir) { $dir = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $env:USERPROFILE ".codex" } $path = Join-Path $dir "config.toml" $allow = $script:StoreToken -or $Uninstall if ($script:StoreToken -and -not $Uninstall) { $quoted = Format-TomlString (Get-AuthHeader "Bearer") $authLine = "http_headers = { Authorization = $quoted }" } else { $authLine = 'bearer_token_env_var = "STEPS_TOKEN"' } $block = @" $HashBegin [mcp_servers.steps] url = "$Origin/mcp" $authLine enabled = true $HashEnd "@ if (-not (Test-Path -LiteralPath $path)) { if ($Uninstall) { Add-Change "unchanged" $path } else { Write-TextFile $path $block -SecretOk:$allow } } else { $text = [IO.File]::ReadAllText($path) if ($text.Contains($HashBegin)) { $span = Get-HashSpan $text $path $start = $span.Start $after = $span.After if ($Uninstall) { $updated = $text.Substring(0, $start) + $text.Substring($after) if ([string]::IsNullOrWhiteSpace($updated)) { Remove-OurFile $path } else { Write-TextFile $path $updated -SecretOk:$allow } } else { Write-TextFile $path ($text.Substring(0, $start) + $block + "`n" + $text.Substring($after)) -SecretOk:$allow } } elseif (-not $Uninstall) { $sep = if ($text.EndsWith("`n")) { "`n" } else { "`n`n" } Write-TextFile $path ($text + $sep + $block) -SecretOk:$allow } else { Add-Change "unchanged" $path } } Update-MarkedFile (Join-Path $dir "AGENTS.md") if ($ProjectDir) { Update-MarkedFile (Join-Path $ProjectDir "AGENTS.md") } } function Install-Gemini($ProjectDir) { $path = Join-Path $env:USERPROFILE ".gemini\settings.json" $data = Read-JsonObject $path $server = [pscustomobject]@{ httpUrl = "$Origin/mcp" headers = [pscustomobject]@{ Authorization = (Get-AuthHeader 'Bearer ${STEPS_TOKEN}') } } $data = Set-Server $data "mcpServers" "steps" $server $allow = $script:StoreToken -or $Uninstall if ($Uninstall -and @($data.PSObject.Properties).Count -eq 0) { Remove-OurFile $path } else { Write-JsonFile $path $data -SecretOk:$allow } Update-MarkedFile (Join-Path $env:USERPROFILE ".gemini\GEMINI.md") if ($ProjectDir) { Update-MarkedFile (Join-Path $ProjectDir "GEMINI.md") } } function Install-OpenCode($ProjectDir) { $dir = if ($env:XDG_CONFIG_HOME) { $env:XDG_CONFIG_HOME } else { Join-Path $env:USERPROFILE ".config" } $path = Join-Path $dir "opencode\opencode.jsonc" $existed = Test-Path -LiteralPath $path $data = Read-JsonObject $path if (-not $Uninstall -and -not $existed) { Set-Prop $data '$schema' "https://opencode.ai/config.json" } $server = [pscustomobject]@{ type = "remote" url = "$Origin/mcp" enabled = $true oauth = $false headers = [pscustomobject]@{ Authorization = (Get-AuthHeader "Bearer {env:STEPS_TOKEN}") } } $data = Set-Server $data "mcp" "steps" $server $names = @($data.PSObject.Properties.Name) if ($Uninstall -and ($names.Count -eq 0 -or ($names -contains '$schema' -and $names.Count -eq 1))) { if ($existed) { Remove-OurFile $path } else { Add-Change "unchanged" $path } } else { Write-JsonFile $path $data -SecretOk:($script:StoreToken -or $Uninstall) } Update-MarkedFile (Join-Path $dir "opencode\AGENTS.md") if ($ProjectDir) { Update-MarkedFile (Join-Path $ProjectDir "AGENTS.md") } } function Install-Goose($ProjectDir) { $dir = if ($env:XDG_CONFIG_HOME) { $env:XDG_CONFIG_HOME } else { Join-Path $env:USERPROFILE ".config" } $path = Join-Path $dir "goose\config.yaml" $allow = $script:StoreToken -or $Uninstall $auth = Format-TomlString (Get-AuthHeader 'Bearer ${STEPS_TOKEN}') $block = @" $HashBegin steps: enabled: true type: streamable_http name: steps uri: "$Origin/mcp" headers: Authorization: $auth timeout: 300 $HashEnd "@ if (-not (Test-Path -LiteralPath $path)) { if ($Uninstall) { Add-Change "unchanged" $path } else { Write-TextFile $path ("extensions:`n" + $block) -SecretOk:$allow } } else { $text = [IO.File]::ReadAllText($path) if ($text.Contains($HashBegin)) { $span = Get-HashSpan $text $path $start = $span.Start $after = $span.After if ($Uninstall) { $updated = $text.Substring(0, $start) + $text.Substring($after) if ([string]::IsNullOrWhiteSpace($updated) -or $updated.Trim() -eq "extensions:") { Remove-OurFile $path } else { Write-TextFile $path $updated -SecretOk:$allow } } else { Write-TextFile $path ($text.Substring(0, $start) + $block + "`n" + $text.Substring($after)) -SecretOk:$allow } } elseif (-not $Uninstall) { Write-TextFile $path ($text.TrimEnd() + "`n" + $block) -SecretOk:$allow } else { Add-Change "unchanged" $path } } Update-MarkedFile (Join-Path $dir "goose\AGENTS.md") Update-MarkedFile (Join-Path $dir "goose\.goosehints") if ($ProjectDir) { Update-MarkedFile (Join-Path $ProjectDir "AGENTS.md") Update-MarkedFile (Join-Path $ProjectDir ".goosehints") } Add-Change "manual" "Goose loads hints when the Developer extension is enabled (the default profile)." } if ($Origin -notmatch '^https?://[A-Za-z0-9._:\-\[\]]+$') { Fail "set STEPS_URL to the Steps origin, or run the connect.ps1 served by the app." } $selected = @() if ($All) { $selected = $Known } if ($Harness) { # -File passes "cursor,claude" as one literal string, so split commas here. foreach ($raw in $Harness) { foreach ($name in ($raw -split ',')) { $name = $name.Trim() if (-not $name) { continue } if ($Known -notcontains $name) { Fail "unknown harness $name. Choose from: $($Known -join ', ')" } if ($selected -notcontains $name) { $selected += $name } } } } if (-not $selected) { if (Get-Command cursor -ErrorAction SilentlyContinue) { $selected += "cursor" } elseif (Get-Command agent -ErrorAction SilentlyContinue) { $selected += "cursor" } elseif (Test-Path (Join-Path $env:USERPROFILE ".cursor")) { $selected += "cursor" } if (Get-Command claude -ErrorAction SilentlyContinue) { $selected += "claude" } elseif (Test-Path (Join-Path $env:USERPROFILE ".claude.json")) { $selected += "claude" } if (Get-Command codex -ErrorAction SilentlyContinue) { $selected += "codex" } if (Get-Command gemini -ErrorAction SilentlyContinue) { $selected += "gemini" } if (Get-Command opencode -ErrorAction SilentlyContinue) { $selected += "opencode" } if (Get-Command goose -ErrorAction SilentlyContinue) { $selected += "goose" } } if (-not $selected) { Fail "no harness detected. Re-run with -Harness NAME or -All." } Require-Token if (-not $DryRun -and -not $Yes -and -not (Test-ConsoleInput)) { Fail "re-run with -Yes to change files when input is not a terminal. Nothing was written." } if (-not $script:StoreToken -and -not $Uninstall -and -not $DryRun -and -not $Yes -and (Test-ConsoleInput)) { Write-Output "Apps opened from the Dock or Start menu cannot see STEPS_TOKEN from your shell." Write-Output "Saving the token in the MCP config makes that launch work." Write-Output "The value is not printed, and it is not written into rule files." if ($selected -contains "cursor") { Write-Output "For Cursor, saving it is the default: an env-var reference stays empty in a desktop launch." $storeAnswer = Read-Host "Save the token in MCP config files? [Y/n]" if ($storeAnswer -eq "" -or $storeAnswer -match '^(y|yes)$') { $script:StoreToken = $true } } else { $storeAnswer = Read-Host "Save the token in MCP config files? [y/N]" if ($storeAnswer -match '^(y|yes)$') { $script:StoreToken = $true } } } $projectDir = Resolve-Project if (-not $Yes -and -not $DryRun) { $verb = if ($Uninstall) { "Remove Steps from" } else { "Update Steps for" } $answer = Read-Host "$verb $($selected -join ', ')? [y/N]" if ($answer -notmatch '^(y|yes)$') { Fail "cancelled. Nothing was written." } } if ($projectDir -and -not $DryRun -and -not (Test-Path -LiteralPath $projectDir)) { New-Item -ItemType Directory -Force -Path $projectDir | Out-Null } $mode = if ($DryRun) { "dry-run" } elseif ($Uninstall) { "uninstall" } else { "install" } Write-Output "Steps installer ($mode)" Write-Output "Origin: $Origin" Write-Output ("Token in MCP config: " + ($(if ($script:StoreToken) { "yes" } else { "no (env reference)" }))) Write-Output ("Harnesses: " + ($selected -join ", ")) Write-Output ("Project: " + ($(if ($projectDir) { $projectDir } else { "(none; home config only)" }))) foreach ($name in $selected) { $before = $script:Changes.Count Write-Output "" Write-Output $name switch ($name) { "cursor" { Install-Cursor $projectDir } "claude" { Install-Claude $projectDir } "claude-desktop" { Install-ClaudeDesktop } "codex" { Install-Codex $projectDir } "gemini" { Install-Gemini $projectDir } "opencode" { Install-OpenCode $projectDir } "goose" { Install-Goose $projectDir } } if ($script:Changes.Count -eq $before) { Write-Output " unchanged" } else { $script:Changes[$before..($script:Changes.Count - 1)] | ForEach-Object { Write-Output $_ } } } if ($Uninstall) { $beforeBackups = $script:Changes.Count Remove-OldInstallerBackups $projectDir if ($script:Changes.Count -gt $beforeBackups) { Write-Output "" Write-Output "installer backups" $script:Changes[$beforeBackups..($script:Changes.Count - 1)] | ForEach-Object { Write-Output $_ } } } if ($selected -contains "cursor" -and -not $Uninstall) { $text = (Get-RuleBody).Trim() + "`n" Write-Output "" Write-Output "Cursor User Rules are not a file. The CLI cannot set them." if ($projectDir) { Write-Output "In the project, wrote .cursor/rules/steps.mdc with alwaysApply: true." } Write-Output "Open Customize in the sidebar -> Rules and paste this as a User Rule:" Write-Output "---" Write-Output $text Write-Output "---" if ($DryRun) { Write-Output "Clipboard: skipped in -DryRun" } else { try { Set-Clipboard -Value $text Write-Output "Clipboard: copied the User Rule text." } catch { Write-Output "Clipboard: could not copy. Copy the text above." } } if ($script:StoreToken) { Write-Output "The Cursor MCP config holds the token, so a Dock or Start menu launch can connect." } else { Write-Output "Export STEPS_TOKEN in the environment that launches Cursor." Write-Output "A Cursor window opened from the Dock or Start menu does not see a shell export." Write-Output "Re-run with -StoreToken to save the token in the MCP config." } } if ($script:StoreToken -and -not $Uninstall) { Write-Output "" $verb = if ($DryRun) { "would be stored" } else { "is stored" } Write-Output "The token $verb in these MCP config files. It was not printed." if ($script:SecretFiles.Count -eq 0) { Write-Output " (none; this run did not write an MCP config)" } else { $script:SecretFiles | ForEach-Object { Write-Output " $_" } } Write-Output "Those files are limited to the current user. Do not commit them. Rule files do not contain the token." } elseif (-not $Uninstall) { Write-Output "" Write-Output "MCP configs name STEPS_TOKEN and do not contain the token." } if ($Uninstall -and $KeepBackups) { Write-Output "" Write-Output "Installer backups were kept because -KeepBackups was set." if ($script:SecretBackups.Count -gt 0) { if ($DryRun) { Write-Output "These backups would still contain the token. The token was not printed." } else { Write-Output "These backups still contain the token. They are limited to the current user. The token was not printed." } $script:SecretBackups | ForEach-Object { Write-Output " $_" } } } elseif ($Uninstall -and $script:DeletedBackups.Count -gt 0) { Write-Output "" if ($DryRun) { Write-Output "Would remove installer backups (paths only; no token values):" } else { Write-Output "Removed installer backups (paths only; no token values):" } $script:DeletedBackups | ForEach-Object { Write-Output " $_" } } if ($script:Restored.Count -gt 0) { Write-Output "" Write-Output "An edit failed or the result did not parse. The original file was restored and the backup was kept:" $script:Restored | ForEach-Object { Write-Output " $_" } } Write-Output "" Write-Output "Done." if ($script:Restored.Count -gt 0) { exit 1 }