Skip to content
Back to search

ouroboros

Sits in front of Claude Code and fixes the brief before the code. An interview scores how vague your request is, and a score above the bar blocks spec generation until you pass force explicitly. When an acceptance criterion defines a verify command or an expected-output assertion, those values are omitted from the worker's contract block, with no flag to put them back, so the worker is asked for the outcome rather than handed the assertion. Redaction of those values elsewhere is literal over five encodings, so a reshaped copy can still get through; that gap is tracked in a public issue.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Q00/ouroboros with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Q00/ouroboros'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/q00--ouroboros/badge.svg)](/listings/q00--ouroboros)

HTML

<a href="/listings/q00--ouroboros"><img src="/api/listings/q00--ouroboros/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

# macOS / Linux / WSL 2
curl -fsSL https://raw.githubusercontent.com/Q00/ouroboros/main/scripts/install.sh | OUROBOROS_INSTALL_REF=readme bash
# Windows (PowerShell) — no Python needed; installs Git and uv for you
irm https://raw.githubusercontent.com/Q00/ouroboros/main/scripts/install.ps1 | iex

When installation finishes, the Ouroboros console opens in your browser and walks you through connecting your agent tools. Reopen it any time with `ouroboros gui`.

The installer finds the agent tools you already have and connects Ouroboros to them. Native Windows is experimental, and Codex CLI needs WSL 2; see [platform support](./docs/platform-support.md).

**Other ways to install.** These don't open the console for you; run `ouroboros gui` once the `ouroboros` command is installed.

# Claude Code plugin only (then run /ouroboros:setup inside Claude Code)
claude plugin marketplace add Q00/ouroboros && claude plugin install ouroboros@ouroboros

# pip / uv / pipx (Python 3.12+)
pip install 'ouroboros-ai[mcp,tui]' && ouroboros setup --runtime claude-cli

# Homebrew (macOS / Linux)
brew tap q00/tap && brew install ouroboros-ai && ouroboros setup

Every install path, profile and host is in [Getting Started](./docs/getting-started.md). `ouroboros uninstall` removes Ouroboros's configuration, MCP registrations and data directory (`~/.ouroboros/`). It leaves the Python package and the Claude Code plugin installed; finish with the steps in [UNINSTALL.md](./UNINSTALL.md).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 40 lines
  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "ouroboros",
  4. "description": "Sits in front of Claude Code and fixes the brief before the code. An interview scores how vague your request is, and a score above the bar blocks spec generation until you pass force explicitly. When an acceptance criterion defines a verify command or an expected-output assertion, those values are omitted from the worker's contract block, with no flag to put them back, so the worker is asked for the outcome rather than handed the assertion. Redaction of those values elsewhere is literal over five encodings, so a reshaped copy can still get through; that gap is tracked in a public issue.",
  5. "owner": {
  6. "name": "Q00",
  7. "email": "jqyu.lee@gmail.com"
  8. },
  9. "plugins": [
  10. {
  11. "name": "ouroboros",
  12. "description": "Sits in front of Claude Code and fixes the brief before the code. An interview scores how vague your request is, and a score above the bar blocks spec generation until you pass force explicitly. When an acceptance criterion defines a verify command or an expected-output assertion, those values are omitted from the worker's contract block, with no flag to put them back, so the worker is asked for the outcome rather than handed the assertion. Redaction of those values elsewhere is literal over five encodings, so a reshaped copy can still get through; that gap is tracked in a public issue.",
  13. "version": "0.61.1",
  14. "author": {
  15. "name": "Q00",
  16. "email": "jqyu.lee@gmail.com"
  17. },
  18. "source": "./",
  19. "category": "development",
  20. "homepage": "https://github.com/Q00/ouroboros",
  21. "repository": "https://github.com/Q00/ouroboros",
  22. "license": "MIT",
  23. "keywords": [
  24. "workflow",
  25. "requirements",
  26. "socratic",
  27. "interview",
  28. "seed",
  29. "evaluation",
  30. "agentic-loop",
  31. "loop-engineering"
  32. ],
  33. "tags": [
  34. "requirement-engineering",
  35. "self-improving",
  36. "crystallization"
  37. ]
  38. }
  39. ]
  40. }
README.md · README · 206 lines · 1 finding marked
  1. <!-- mcp-name: io.github.Q00/ouroboros -->
  2. <p align="right">
  3. <strong>English</strong> | <a href="./README.ko.md">한국어</a> | <a href="./README.zh-CN.md">简体中文</a>
  4. </p>
  5. <p align="center">
  6. <br/>
  7. ◯ ─────────── ◯
  8. <br/><br/>
  9. <img src="./docs/images/ouroboros.png" width="420" alt="Ouroboros">
  10. <br/><br/>
  11. <strong>O U R O B O R O S</strong>
  12. <br/><br/>
  13. ◯ ─────────── ◯
  14. <br/>
  15. </p>
  16. <p align="center">
  17. <strong>It gets smarter on its own. We just hold the line.</strong>
  18. <br/>
  19. <sub>Ask first, build second, check always: spec-first AI coding for the agents you already use.</sub>
  20. </p>
  21. <p align="center">
  22. <a href="https://github.com/Q00/ouroboros"><img src="https://img.shields.io/github/stars/Q00/ouroboros?color=yellow&logo=github&label=stars" alt="GitHub stars"></a>
  23. <a href="https://pypi.org/project/ouroboros-ai/"><img src="https://img.shields.io/pypi/v/ouroboros-ai?color=blue" alt="PyPI"></a>
  24. <a href="https://github.com/Q00/ouroboros/actions/workflows/test.yml"><img src="https://img.shields.io/github/actions/workflow/status/Q00/ouroboros/test.yml?branch=main" alt="Tests"></a>
  25. <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License"></a>
  26. <a href="https://github.com/sponsors/Q00"><img src="https://img.shields.io/github/sponsors/Q00?logo=githubsponsors&color=EA4AAA&label=sponsors" alt="GitHub Sponsors"></a>
  27. </p>
  28. <p align="center">
  29. <a href="https://trendshift.io/repositories/26008?utm_source=repository-badge&utm_medium=badge&utm_campaign=badge-repository-26008" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/26008" alt="Q00%2Fouroboros | Trendshift" width="250" height="55"/></a>
  30. </p>
  31. <p align="center">
  32. <a href="#install">Install</a> ·
  33. <a href="#first-steps">First steps</a> ·
  34. <a href="#works-with">Works with</a> ·
  35. <a href="#learn-more">Learn more</a> ·
  36. <a href="https://ouroboros.page/learn/en/">Guide</a>
  37. </p>
  38. Ouroboros helps your AI coding agent build the right thing. It asks you
  39. questions until the goal is clear, writes the answer down as a spec with
  40. checkable acceptance criteria, hands that spec to the coding agent you already
  41. use, and then checks the result against the spec.
  42. <p align="center">
  43. <img src="./docs/images/console-tour-en.gif" width="900" alt="Screen recording of the Ouroboros console in a browser. On the Chat page in Auto mode, the request Please make a todo cli tool starts an ouroboros auto run whose output streams into the chat; the tour then visits the Runs, Connect, Agents and models, Providers, Shared MCP and Health pages.">
  44. </p>
  45. <p align="center">
  46. <sub>The Ouroboros console: type what you want in Chat, and it runs the interview, the spec, the build and the checks for you.</sub>
  47. </p>
  48. ## Install
  49. ```bash
  50. # macOS / Linux / WSL 2
  51. curl -fsSL https://raw.githubusercontent.com/Q00/ouroboros/main/scripts/install.sh | OUROBOROS_INSTALL_REF=readme bash
  52. ```
  53. ```powershell
  54. # Windows (PowerShell) — no Python needed; installs Git and uv for you
  55. irm https://raw.githubusercontent.com/Q00/ouroboros/main/scripts/install.ps1 | iex
  56. ```
  57. When installation finishes, the Ouroboros console opens in your browser and
  58. walks you through connecting your agent tools. Reopen it any time with
  59. `ouroboros gui`.
  60. The installer finds the agent tools you already have and connects Ouroboros to
  61. them. Native Windows is experimental, and Codex CLI needs WSL 2; see
  62. [platform support](./docs/platform-support.md).
  63. **Other ways to install.** These don't open the console for you; run
  64. `ouroboros gui` once the `ouroboros` command is installed.
  65. ```bash
  66. # Claude Code plugin only (then run /ouroboros:setup inside Claude Code)
  67. claude plugin marketplace add Q00/ouroboros && claude plugin install ouroboros@ouroboros
  68. # pip / uv / pipx (Python 3.12+)
  69. pip install 'ouroboros-ai[mcp,tui]' && ouroboros setup --runtime claude-cli
  70. # Homebrew (macOS / Linux)
  71. brew tap q00/tap && brew install ouroboros-ai && ouroboros setup
  72. ```
  73. Every install path, profile and host is in
  74. [Getting Started](./docs/getting-started.md). `ouroboros uninstall` removes
  75. Ouroboros's configuration, MCP registrations and data directory
  76. (`~/.ouroboros/`). It leaves the Python package and the Claude Code plugin
  77. installed; finish with the steps in [UNINSTALL.md](./UNINSTALL.md).
  78. ## First steps
  79. Describe what you want in plain words. Four good places to start:
  80. - **Console Chat**: type a goal and pick **Interview** (it asks until the goal is clear) or **Auto** (it fills the gaps itself), then hand the spec to your agents and watch the run.
  81. - **`ooo interview "a todo CLI with due dates"`** in your agent: questions until the goal is clear, then a spec (a *Seed*).
  82. - **`ooo auto "a todo CLI with due dates"`**: asks only what is missing, writes the spec, runs it, and checks it.
  83. - **`ooo run`**: builds an existing Seed and checks every acceptance criterion.
  84. In Claude Code, run `/ouroboros:setup` once and finish its questions, then send
  85. your first `ooo` command as a separate message. From a plain terminal,
  86. `ouroboros init start "..."` and `ouroboros auto "..."` do the same without an
  87. agent host. The full command list is in
  88. [Getting Started](./docs/getting-started.md#commands).
  89. > Ouroboros runs coding agents that can change files and run commands in your
  90. > project. Read [permission scope](./skills/help/TROUBLESHOOTING.md#permission-scope)
  91. > before using it on a project you don't trust.
  92. ## Works with
  93. [Claude Code](./docs/runtime-guides/claude-code.md) ·
  94. [Codex CLI](./docs/runtime-guides/codex.md) ·
  95. [GitHub Copilot CLI](./docs/runtime-guides/copilot.md) ·
  96. [OpenCode](./docs/runtime-guides/opencode.md) ·
  97. [Hermes](./docs/runtime-guides/hermes.md) ·
  98. [Gemini CLI](./docs/runtime-guides/gemini.md) ·
  99. [Kiro CLI](./docs/runtime-guides/kiro.md) ·
  100. [Pi](./docs/runtime-guides/pi.md) ·
  101. [OMP](./docs/runtime-guides/omp.md) ·
  102. [Zcode](./docs/runtime-guides/zcode.md) ·
  103. [Goose](./docs/runtime-guides/goose.md) ·
  104. [GJC](./docs/runtime-guides/gjc.md) ·
  105. [Antigravity CLI](./docs/runtime-guides/antigravity.md) ·
  106. [Grok Build CLI](./docs/runtime-guides/grok.md) ·
  107. [DeepSeek Harness](./docs/guides/deepseek-harness.md)
  108. The installer connects the ones you have; the console's **Connect** page
  109. installs and connects the rest. Want to see it first?
  110. [Watch the interview run on seven different hosts](./docs/how-ouroboros-works.md#see-it-on-each-host).
  111. ## Learn more
  112. - [Getting Started](./docs/getting-started.md): every install path, host-by-host setup, your first workflow, and all commands.
  113. - [Console guide](./docs/guides/console.md): what each console page does, the shared MCP server, and starting the console at login.
  114. - [How Ouroboros works](./docs/how-ouroboros-works.md): the loop, the agents, the ambiguity gate, the Agent OS stack, architecture, and philosophy.
  115. - [CLI reference](./docs/cli-reference.md) · [Configuration](./docs/config-reference.md) · [Platform support](./docs/platform-support.md) · [All docs](./docs/README.md)
  116. - [Interactive guide](https://ouroboros.page/learn/en/)
  117. <p align="center">
  118. <sub>Most people find out they were unclear about three files into the review.<br/>
  119. If that feels familiar, star <a href="https://github.com/Q00/ouroboros"><strong>Q00/ouroboros on GitHub</strong></a> so the next person it could save can find it.</sub>
  120. </p>
  121. ## Contributing
  122. ```bash
  123. git clone https://github.com/Q00/ouroboros
  124. cd ouroboros
  125. uv sync --python 3.13 --all-groups
  126. uv run --python 3.13 --no-sync pytest
  127. ```
  128. [Issues](https://github.com/Q00/ouroboros/issues) · [Discussions](https://github.com/Q00/ouroboros/discussions) · [Contributing Guide](./CONTRIBUTING.md)
  129. ## Sponsors
  130. Ouroboros is MIT-licensed and built in the open. If it saves you rework, consider
  131. sponsoring: it funds maintenance, new runtime integrations, and sponsor-only
  132. deep-dive content.
  133. <p align="center">
  134. <a href="https://github.com/sponsors/Q00"><img src="https://img.shields.io/badge/%E2%9D%A4%EF%B8%8E%20Sponsor%20on%20GitHub-EA4AAA?style=for-the-badge&logo=githubsponsors&logoColor=white" alt="Sponsor Q00 on GitHub"></a>
  135. </p>
  136. ## Activity
  137. These numbers are generated from GitHub data and refreshed automatically; caching may delay updates.
  138. <p align="center">
  139. <a href="https://github.com/Q00/ouroboros/graphs/contributors"><img src="https://img.shields.io/github/contributors/Q00/ouroboros?color=orange" alt="Contributors"></a>
  140. <a href="https://github.com/Q00/ouroboros/commits/main"><img src="https://img.shields.io/github/commit-activity/m/Q00/ouroboros?color=orange" alt="Commit activity"></a>
  141. <a href="https://github.com/Q00/ouroboros/pulls?q=is%3Apr+is%3Aclosed"><img src="https://img.shields.io/github/issues-pr-closed/Q00/ouroboros?color=orange" alt="Closed pull requests"></a>
  142. <a href="https://github.com/Q00/ouroboros/commits/main"><img src="https://img.shields.io/github/last-commit/Q00/ouroboros?color=orange" alt="Last commit"></a>
  143. </p>
  144. ## Disclaimer
  145. > The Ouroboros project and community are **not affiliated with any
  146. > cryptocurrency, token, memecoin, or trading community** — including, but not
  147. > limited to, any "ouroboros" tickers on pump.fun or other launchpads. This is
  148. > an open-source developer tool. We do not issue, endorse, or hold any coins.
  149. > Any token claiming association with this project is unauthorized.
  150. > **Naming note.** A separate, unaffiliated open-source project also uses the
  151. > name "Ouroboros" — Anton Razzhigaev's self-modifying, autonomous-memory agent
  152. > at `github.com/razzant/ouroboros`. No shared code, no relationship. This
  153. > project locks a specification before executing rather than rewriting its own
  154. > architecture; if you're looking for the latter, that's the other one.
  155. ---
  156. <p align="center">
  157. <em>"The beginning is the end, and the end is the beginning."</em>
  158. <br/><br/>
  159. <strong>The serpent does not repeat -- it evolves.</strong>
  160. <br/><br/>
  161. <code>MIT License</code>
  162. </p>
scripts/install.ps1 · Bundled script · 628 lines · 1 finding marked
  1. # Ouroboros installer for native Windows (PowerShell 5.1+ / pwsh 7+).
  2. #
  3. # Usage (no Python, no uv, no Git needed beforehand):
  4. # irm https://raw.githubusercontent.com/Q00/ouroboros/main/scripts/install.ps1 | iex
    • Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
    • Line 4 on GitHub
  5. #
  6. # With options (the pipe form cannot take parameters, so bind the script first):
  7. # & ([scriptblock]::Create((irm https://raw.githubusercontent.com/Q00/ouroboros/main/scripts/install.ps1))) -Runtime codex
  8. #
  9. # Environment variables mirror scripts/install.sh and work with the pipe form:
  10. # OUROBOROS_INSTALL_RUNTIME claude|claude-sdk|claude-cli|codex|opencode|hermes|gemini|goose|kiro|copilot|pi|gjc|all
  11. # OUROBOROS_INSTALL_RECONFIGURE set to 1 to ignore the runtime saved in ~/.ouroboros/config.yaml
  12. # OUROBOROS_INSTALL_PRE set to 1 to allow pre-release versions
  13. # OUROBOROS_NO_CONSOLE set to 1 to skip starting the Ouroboros console (same as -NoConsole)
  14. #
  15. # Parameters: -Runtime <name>, -Reconfigure, -Pre, -NoConsole
  16. #
  17. # What it does, in order:
  18. # 1. Git >= 2.36 and uv: installed through winget when missing (uv falls back
  19. # to the astral.sh installer). uv downloads its own Python, so the machine
  20. # does not need one.
  21. # 2. Picks a backend the same way install.sh does: explicit > saved config >
  22. # single detected CLI > prompt.
  23. # 3. `uv tool install` with the selected distribution's own extras, like install.sh.
  24. # 4. `ouroboros setup --runtime <backend> --non-interactive`, `setup refresh`,
  25. # and the Claude Code plugin when `claude` is on PATH.
  26. # 5. When the installed release ships `ouroboros gui` and this is an
  27. # interactive desktop session (no CI variable, console input not
  28. # redirected, not an SSH session), starts the Ouroboros console in a
  29. # hidden background process, which opens it in the browser. Otherwise it
  30. # only prints the command. -NoConsole / OUROBOROS_NO_CONSOLE=1 skip this.
  31. #
  32. # This installer emits no installer events of its own (no install_started /
  33. # install_completed). The `ouroboros` CLI it invokes for setup follows the normal
  34. # telemetry controls in TELEMETRY.md, exactly as it does under install.sh.
  35. # Native Windows support is experimental; Codex CLI is only supported under WSL 2 (docs/platform-support.md).
  36. [CmdletBinding()]
  37. param(
  38. [string]$Runtime = $env:OUROBOROS_INSTALL_RUNTIME,
  39. [switch]$Reconfigure,
  40. [switch]$Pre,
  41. [switch]$NoConsole
  42. )
  43. $ErrorActionPreference = 'Stop'
  44. Set-StrictMode -Version 2.0
  45. # Dependency versions belong to the selected distribution's extras. Do not
  46. # override an older PyPI release with optional pins from this installer.
  47. $PackageName = 'ouroboros-ai'
  48. $ClickSpec = 'click>=8.1.0,<9.0.0'
  49. $DefaultPythonSpec = '>=3.12'
  50. $LiteLLMPythonSpec = '>=3.12,<3.14'
  51. $MinGitVersion = [version]'2.36.0'
  52. $MinPython = [version]'3.12'
  53. $HookPythonVersion = '3.13'
  54. $AllRuntimes = @('claude', 'claude-sdk', 'claude-cli', 'codex', 'opencode', 'hermes', 'gemini', 'goose', 'kiro', 'copilot', 'pi', 'gjc')
  55. if ([string]::IsNullOrWhiteSpace($Runtime)) { $Runtime = '' }
  56. if (-not $Reconfigure -and $env:OUROBOROS_INSTALL_RECONFIGURE) { $Reconfigure = $true }
  57. if (-not $Pre -and $env:OUROBOROS_INSTALL_PRE) { $Pre = $true }
  58. # --- output helpers -----------------------------------------------------------
  59. function Write-Step([string]$Title, [string]$Detail) {
  60. Write-Host ''
  61. Write-Host "== $Title" -ForegroundColor Cyan
  62. if ($Detail) { Write-Host " $Detail" -ForegroundColor DarkGray }
  63. }
  64. function Write-Ok([string]$Message) { Write-Host " [ok] $Message" -ForegroundColor Green }
  65. function Write-Info([string]$Message) { Write-Host " - $Message" -ForegroundColor DarkGray }
  66. function Write-Warn([string]$Message) { Write-Host " [!] $Message" -ForegroundColor Yellow }
  67. function Write-Err([string]$Message) { Write-Host " [x] $Message" -ForegroundColor Red }
  68. function Test-Interactive {
  69. try { return -not [Console]::IsInputRedirected } catch { return $false }
  70. }
  71. # Installers register their directories in the user/machine PATH, but the
  72. # current session keeps the PATH it started with. Merge the registry PATH in so
  73. # a tool installed a moment ago is visible without opening a new terminal.
  74. function Sync-SessionPath {
  75. $parts = New-Object System.Collections.Generic.List[string]
  76. $seen = @{}
  77. foreach ($scope in @('Process', 'User', 'Machine')) {
  78. $value = [Environment]::GetEnvironmentVariable('Path', $scope)
  79. if (-not $value) { continue }
  80. foreach ($entry in $value.Split(';')) {
  81. $trimmed = $entry.Trim()
  82. if (-not $trimmed) { continue }
  83. $key = $trimmed.TrimEnd('\').ToLowerInvariant()
  84. if ($seen.ContainsKey($key)) { continue }
  85. $seen[$key] = $true
  86. $parts.Add($trimmed)
  87. }
  88. }
  89. $env:Path = ($parts -join ';')
  90. }
  91. function Add-SessionPathFront([string]$Directory) {
  92. if (-not $Directory) { return }
  93. $current = $env:Path.Split(';') | ForEach-Object { $_.TrimEnd('\').ToLowerInvariant() }
  94. if ($current -contains $Directory.TrimEnd('\').ToLowerInvariant()) { return }
  95. $env:Path = "$Directory;$env:Path"
  96. }
  97. function Get-CommandPath([string]$Name) {
  98. $found = Get-Command $Name -ErrorAction SilentlyContinue
  99. if ($found) { return $found.Source }
  100. return $null
  101. }
  102. # Native commands do not throw on Windows PowerShell 5.1; check the exit code.
  103. function Invoke-Native([string]$Command, [string[]]$Arguments) {
  104. $global:LASTEXITCODE = 0
  105. # Output goes straight to the host so the function returns only the bool.
  106. & $Command @Arguments | Out-Host
  107. return ($LASTEXITCODE -eq 0)
  108. }
  109. function Test-Winget {
  110. return [bool](Get-CommandPath 'winget')
  111. }
  112. function Install-WithWinget([string]$Id, [string]$Label) {
  113. if (-not (Test-Winget)) { return $false }
  114. Write-Info "Installing $Label with winget ($Id)..."
  115. $ok = Invoke-Native 'winget' @('install', '--id', $Id, '-e', '--silent', '--accept-source-agreements', '--accept-package-agreements')
  116. Sync-SessionPath
  117. return $ok
  118. }
  119. # --- banner -------------------------------------------------------------------
  120. Write-Host ''
  121. Write-Host ' Ouroboros installer (Windows)' -ForegroundColor Magenta
  122. Write-Host ' Specification-first AI development' -ForegroundColor DarkGray
  123. Write-Host ''
  124. Write-Warn 'Native Windows support is experimental. Codex CLI needs WSL 2; for the fully supported path run scripts/install.sh inside WSL 2.'
  125. # --- 1/4 prerequisites: Git and uv -------------------------------------------
  126. Write-Step '1/4 Checking Git and uv' 'Both are installed automatically when missing. No Python is required.'
  127. Sync-SessionPath
  128. $gitPath = Get-CommandPath 'git'
  129. if (-not $gitPath) {
  130. Write-Warn 'Git not found.'
  131. if (-not (Install-WithWinget 'Git.Git' 'Git')) {
  132. Write-Err 'Git >= 2.36 is required and could not be installed automatically.'
  133. Write-Info 'Install it from https://git-scm.com/download/win, open a new PowerShell window, and run this installer again.'
  134. exit 1
  135. }
  136. $gitPath = Get-CommandPath 'git'
  137. if (-not $gitPath) {
  138. Write-Err 'Git was installed but is not on PATH yet. Open a new PowerShell window and run this installer again.'
  139. exit 1
  140. }
  141. }
  142. $gitVersionText = (& git --version 2>$null) -join ' '
  143. $gitMatch = [regex]::Match($gitVersionText, '(\d+)\.(\d+)\.(\d+)')
  144. if ($gitMatch.Success) {
  145. $gitVersion = [version]("{0}.{1}.{2}" -f $gitMatch.Groups[1].Value, $gitMatch.Groups[2].Value, $gitMatch.Groups[3].Value)
  146. if ($gitVersion -lt $MinGitVersion) {
  147. Write-Err "Git $gitVersion found, but Ouroboros needs Git >= $MinGitVersion."
  148. Write-Info 'Upgrade with: winget upgrade --id Git.Git -e'
  149. exit 1
  150. }
  151. Write-Ok "Git found: $gitVersionText"
  152. } else {
  153. Write-Warn "Could not parse the Git version from '$gitVersionText'; continuing."
  154. }
  155. $uvPath = Get-CommandPath 'uv'
  156. if (-not $uvPath) {
  157. Write-Warn 'uv not found.'
  158. if (-not (Install-WithWinget 'astral-sh.uv' 'uv')) {
  159. Write-Info 'winget unavailable or failed; using the astral.sh installer...'
  160. try {
  161. [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
  162. $uvInstaller = Invoke-RestMethod -Uri 'https://astral.sh/uv/install.ps1' -UseBasicParsing
  163. Invoke-Expression $uvInstaller
  164. } catch {
  165. Write-Err "uv could not be installed: $($_.Exception.Message)"
  166. Write-Info 'Install it manually: winget install --id astral-sh.uv -e (or see https://docs.astral.sh/uv/getting-started/installation/)'
  167. exit 1
  168. }
  169. Sync-SessionPath
  170. }
  171. $uvPath = Get-CommandPath 'uv'
  172. if (-not $uvPath) {
  173. $fallbackBin = Join-Path $env:USERPROFILE '.local\bin'
  174. if (Test-Path (Join-Path $fallbackBin 'uv.exe')) {
  175. Add-SessionPathFront $fallbackBin
  176. $uvPath = Get-CommandPath 'uv'
  177. }
  178. }
  179. if (-not $uvPath) {
  180. Write-Err 'uv was installed but is not on PATH yet. Open a new PowerShell window and run this installer again.'
  181. exit 1
  182. }
  183. }
  184. Write-Ok "uv found: $((& uv --version 2>$null) -join ' ')"
  185. # --- 2/4 backend selection ------------------------------------------------------
  186. Write-Step '2/4 Choosing an agent backend' 'Claude, Codex, Hermes, OpenCode, Gemini, Goose, Kiro, Copilot, Pi, and GJC are supported.'
  187. $detected = @{}
  188. foreach ($pair in @(
  189. @('claude', 'claude'), @('codex', 'codex'), @('hermes', 'hermes'), @('opencode', 'opencode'),
  190. @('gemini', 'gemini'), @('goose', 'goose'), @('kiro', 'kiro-cli'), @('copilot', 'copilot'),
  191. @('pi', 'pi'), @('gjc', 'gjc'))) {
  192. $key = $pair[0]
  193. $exe = $pair[1]
  194. $found = Get-CommandPath $exe
  195. if ($found) {
  196. $detected[$key] = $found
  197. Write-Ok "$key found: $found"
  198. }
  199. }
  200. # Read the previously configured runtime so upgrades keep the user's choice.
  201. function Get-SavedRuntime {
  202. $config = Join-Path $env:USERPROFILE '.ouroboros\config.yaml'
  203. if (-not (Test-Path $config)) { return '' }
  204. $supported = @('claude', 'claude_mcp', 'codex', 'opencode', 'hermes', 'gemini', 'goose', 'kiro', 'copilot', 'pi', 'gjc')
  205. $inOrchestrator = $false
  206. foreach ($line in (Get-Content $config -ErrorAction SilentlyContinue)) {
  207. if ($line -match '^orchestrator:\s*(#.*)?$') { $inOrchestrator = $true; continue }
  208. if ($inOrchestrator -and $line -and -not [char]::IsWhiteSpace($line[0])) { break }
  209. if ($inOrchestrator) {
  210. $m = [regex]::Match($line, '^\s+runtime_backend:\s*["'']?([^"''\s#]+)')
  211. if ($m.Success -and ($supported -contains $m.Groups[1].Value)) {
  212. # claude is the SDK/MCP 1 profile; claude_mcp is the CLI/MCP 2 worker profile.
  213. if ($m.Groups[1].Value -eq 'claude_mcp') { return 'claude-cli' }
  214. return $m.Groups[1].Value
  215. }
  216. }
  217. }
  218. return ''
  219. }
  220. function Read-Choice([string]$Prompt, [string]$Default) {
  221. $answer = Read-Host $Prompt
  222. if ([string]::IsNullOrWhiteSpace($answer)) { return $Default }
  223. return $answer.Trim()
  224. }
  225. function Select-RuntimeInteractive([bool]$AllowNone) {
  226. $menu = @(
  227. @('1', 'claude', "Claude SDK (MCP 1.x) + skills; MCP 2 server is isolated ($PackageName[claude,tui])"),
  228. @('2', 'codex', "Codex plugin artifacts ($PackageName[tui]) -- native Windows: WSL 2 recommended"),
  229. @('3', 'hermes', "Hermes agent guides + MCP server ($PackageName[mcp,tui])"),
  230. @('4', 'opencode', "OpenCode commands and agent files ($PackageName[tui])"),
  231. @('5', 'gemini', "Gemini CLI integration ($PackageName[tui])"),
  232. @('6', 'goose', "Goose CLI integration ($PackageName[tui])"),
  233. @('7', 'kiro', "Kiro CLI integration ($PackageName[tui])"),
  234. @('8', 'copilot', "GitHub Copilot integration ($PackageName[tui])"),
  235. @('9', 'pi', "Pi CLI bridge and instruction artifacts ($PackageName[tui])"),
  236. @('10', 'gjc', "GJC CLI bridge and instruction artifacts ($PackageName[tui])"),
  237. @('11', 'all', "Install every optional integration ($PackageName[all])")
  238. )
  239. foreach ($item in $menu) { Write-Host (" {0,2}) {1,-9} {2}" -f $item[0], $item[1], $item[2]) }
  240. if ($AllowNone) { Write-Host (" {0,2}) {1,-9} {2}" -f '0', 'none', 'Base CLI only; choose a backend later') }
  241. $choice = Read-Choice 'Select [1]' '1'
  242. if ($AllowNone -and $choice -eq '0') { return '' }
  243. foreach ($item in $menu) { if ($item[0] -eq $choice) { return $item[1] } }
  244. return 'claude'
  245. }
  246. $selected = ''
  247. if ($Runtime) {
  248. if ($AllRuntimes -notcontains $Runtime -and $Runtime -ne 'all') {
  249. Write-Err "unsupported runtime '$Runtime'"
  250. Write-Info "Expected one of: $($AllRuntimes -join ', '), all"
  251. exit 1
  252. }
  253. $selected = $Runtime
  254. Write-Ok "Runtime: $selected (from -Runtime / OUROBOROS_INSTALL_RUNTIME)"
  255. } else {
  256. $saved = ''
  257. if (-not $Reconfigure) { $saved = Get-SavedRuntime }
  258. if ($saved) {
  259. $selected = $saved
  260. Write-Ok "Runtime: $selected (preserved from ~/.ouroboros/config.yaml)"
  261. Write-Info 'Re-run with -Reconfigure (or OUROBOROS_INSTALL_RECONFIGURE=1) to choose again.'
  262. } elseif ($detected.Count -gt 1) {
  263. if (Test-Interactive) {
  264. Write-Host ''
  265. Write-Host 'Multiple runtimes detected. Pick where Ouroboros should appear first:'
  266. $selected = Select-RuntimeInteractive $false
  267. } else {
  268. Write-Warn 'Multiple runtimes detected in non-interactive mode; defaulting to Claude.'
  269. $selected = 'claude'
  270. }
  271. } elseif ($detected.Count -eq 1) {
  272. $selected = @($detected.Keys)[0]
  273. } else {
  274. if (Test-Interactive) {
  275. Write-Host ''
  276. Write-Host 'No runtime CLI detected yet. Choose the agent you plan to use:'
  277. $selected = Select-RuntimeInteractive $true
  278. } else {
  279. Write-Warn 'No runtime detected in non-interactive mode; installing the base package.'
  280. Write-Info "Pick a backend afterwards with: ouroboros setup --runtime <$($AllRuntimes -join '|')>"
  281. $selected = ''
  282. }
  283. }
  284. }
  285. if ($selected -eq 'codex') {
  286. Write-Warn 'Codex CLI is not supported on native Windows. Setup will not register a persistent MCP server here; use WSL 2 for Codex.'
  287. }
  288. # Map the backend to the target distribution's extras. `tui` ships with every selection so
  289. # `ouroboros config` works out of the box; `[all]` stays on the MCP 1.x bundle.
  290. $extrasLabel = '[tui]'
  291. $setupRuntime = $selected
  292. $pythonSpec = $DefaultPythonSpec
  293. switch ($selected) {
  294. 'claude' { $extrasLabel = '[claude,tui]' }
  295. 'claude-sdk' { $extrasLabel = '[claude-sdk,tui]' }
  296. 'claude-cli' { $extrasLabel = '[claude-cli,tui]' }
  297. 'hermes' { $extrasLabel = '[mcp,tui]' }
  298. 'all' {
  299. $extrasLabel = '[all]'
  300. $pythonSpec = $LiteLLMPythonSpec
  301. $setupRuntime = ''
  302. }
  303. default { }
  304. }
  305. if ($setupRuntime) { Write-Ok "Selected backend: $setupRuntime" }
  306. elseif ($selected -eq 'all') { Write-Ok 'Selected backend: all' }
  307. else { Write-Info 'Selected backend: none yet' }
  308. # --- 3/4 install ------------------------------------------------------------------
  309. Write-Step '3/4 Installing Ouroboros' "Package: $PackageName$extrasLabel via uv tool install (uv downloads Python $pythonSpec itself)"
  310. $uvArgs = @('tool', 'install', '--upgrade', '--python', $pythonSpec, "$PackageName$extrasLabel", '--with', $ClickSpec)
  311. if ($Pre) { $uvArgs += '--prerelease=allow' }
  312. Write-Info "Running: uv $($uvArgs -join ' ')"
  313. if (-not (Invoke-Native 'uv' $uvArgs)) {
  314. Write-Err 'uv tool install failed. Fix the error above and run the installer again.'
  315. exit 1
  316. }
  317. # Put the tool bin directory on PATH: persistently (uv edits the user PATH) and
  318. # for this session, so setup below runs the binary that was just installed.
  319. $toolBin = ((& uv tool dir --bin 2>$null) -join '').Trim()
  320. if (-not (Invoke-Native 'uv' @('tool', 'update-shell'))) {
  321. Write-Warn "Could not update the user PATH automatically. Add this directory to PATH: $toolBin"
  322. }
  323. if ($toolBin) { Add-SessionPathFront $toolBin }
  324. $ouroborosExe = $null
  325. if ($toolBin -and (Test-Path (Join-Path $toolBin 'ouroboros.exe'))) {
  326. $ouroborosExe = Join-Path $toolBin 'ouroboros.exe'
  327. } else {
  328. $ouroborosExe = Get-CommandPath 'ouroboros'
  329. }
  330. if (-not $ouroborosExe) {
  331. Write-Err "Ouroboros was installed but 'ouroboros' is not on PATH. Add $toolBin to PATH, open a new window, and run: ouroboros setup --runtime <backend>"
  332. exit 1
  333. }
  334. Write-Ok "Installed: $((& $ouroborosExe --version 2>$null) -join ' ')"
  335. # Optional: the Claude Code plugin hooks look for python3/python on PATH and
  336. # skip themselves when none is found. Skills fall back to uv on their own, so
  337. # this is a convenience, not a requirement, and its failure is not fatal.
  338. function Test-PythonAtLeast([string]$Exe) {
  339. $found = Get-CommandPath $Exe
  340. if (-not $found) { return $false }
  341. # Windows ships Microsoft Store execution aliases in WindowsApps. They
  342. # print a diagnostic instead of running Python; skip them before invoking
  343. # the native command so Windows PowerShell does not surface NativeCommandError.
  344. if ($found -match '\\WindowsApps\\(?:python|python3)(?:\.exe)?$') { return $false }
  345. # Avoid embedded quotes: Windows PowerShell 5.1 strips them from native arguments.
  346. # This optional probe may emit stderr, which 5.1 turns into NativeCommandError
  347. # under Stop even with 2>$null. Judge the exit code and stdout instead.
  348. $previousErrorActionPreference = $ErrorActionPreference
  349. try {
  350. $ErrorActionPreference = 'Continue'
  351. $out = (& $found -c 'import sys; print(*sys.version_info[:2], sep=chr(46))' 2>$null) -join ''
  352. } catch {
  353. return $false
  354. } finally {
  355. $ErrorActionPreference = $previousErrorActionPreference
  356. }
  357. if ($LASTEXITCODE -ne 0 -or -not ($out -match '^\d+\.\d+$')) { return $false }
  358. $parsedVersion = $null
  359. if (-not [version]::TryParse($out, [ref]$parsedVersion)) { return $false }
  360. return ($parsedVersion -ge $MinPython)
  361. }
  362. if ((Test-PythonAtLeast 'python3') -or (Test-PythonAtLeast 'python')) {
  363. Write-Ok "Python >= $MinPython found on PATH (used by the Claude Code plugin hooks)"
  364. } else {
  365. Write-Info "No Python >= $MinPython on PATH; installing a uv-managed Python $HookPythonVersion for the plugin hooks..."
  366. if (Invoke-Native 'uv' @('python', 'install', '--default', $HookPythonVersion)) {
  367. Write-Ok "Python $HookPythonVersion installed (python/python3 in $((& uv python dir --bin 2>$null) -join ''))"
  368. Write-Info 'If `python` still opens the Microsoft Store, turn off its App execution alias in Settings > Apps > Advanced app settings.'
  369. } else {
  370. Write-Warn 'Could not install a default Python; plugin hooks will skip themselves until one is on PATH. Skills keep working through uv.'
  371. }
  372. }
  373. # --- 4/4 setup ------------------------------------------------------------------
  374. Write-Step '4/4 Wiring local integrations' 'Creates config and runtime-specific files when a backend was selected.'
  375. if ($setupRuntime) {
  376. Write-Info "Running: ouroboros setup --runtime $setupRuntime --non-interactive"
  377. if (-not (Invoke-Native $ouroborosExe @('setup', '--runtime', $setupRuntime, '--non-interactive'))) {
  378. Write-Warn 'Runtime setup failed; installation is incomplete. Fix the error above and re-run setup.'
  379. exit $LASTEXITCODE
  380. }
  381. } else {
  382. Write-Info 'No backend selected; skipping runtime setup.'
  383. }
  384. # Refresh artifacts for every detected runtime (presence-gated, never touches
  385. # MCP registrations or config), so upgrades do not leave other hosts stale.
  386. Write-Info 'Refreshing runtime artifacts for detected runtimes'
  387. if (-not (Invoke-Native $ouroborosExe @('setup', 'refresh'))) {
  388. Write-Warn 'Artifact refresh skipped; run: ouroboros setup refresh'
  389. }
  390. if ($detected.ContainsKey('claude')) {
  391. Write-Host ''
  392. Write-Host ' Claude Code skills' -ForegroundColor Blue
  393. Write-Info 'Installing Ouroboros skills via Claude plugin marketplace...'
  394. Invoke-Native 'claude' @('plugin', 'marketplace', 'add', 'Q00/ouroboros') | Out-Null
  395. Invoke-Native 'claude' @('plugin', 'marketplace', 'update', 'ouroboros') | Out-Null
  396. if (Invoke-Native 'claude' @('plugin', 'install', 'ouroboros@ouroboros')) {
  397. # `install` is a no-op for an already-installed plugin; `update` moves it to the latest version.
  398. Invoke-Native 'claude' @('plugin', 'update', 'ouroboros@ouroboros') | Out-Null
  399. Write-Ok 'Skills installed'
  400. } else {
  401. Write-Warn 'Skills skipped. Manual install: claude plugin marketplace add Q00/ouroboros; claude plugin install ouroboros@ouroboros'
  402. }
  403. }
  404. Write-Host ''
  405. Write-Host 'Done! Ouroboros is ready.' -ForegroundColor Green
  406. Write-Host ''
  407. Write-Host 'Get started'
  408. Write-Info 'Open a NEW PowerShell window (PATH changes apply there), then in your AI coding agent run: > ooo interview "your idea here"'
  409. Write-Info 'Or from the terminal: ouroboros init start "your idea here"'
  410. if ($setupRuntime) { Write-Info "Current backend: $setupRuntime" }
  411. Write-Info "Switch backend later: ouroboros setup --runtime <$($AllRuntimes -join '|')>"
  412. Write-Host 'Model settings'
  413. Write-Info 'Inside your AI agent: > ooo config (opens in your browser)'
  414. Write-Info 'From this terminal: ouroboros config (full-screen TUI; use Windows Terminal, not cmd.exe)'
  415. Write-Host ''
  416. Write-Host 'Like Ouroboros? Star the repo: https://github.com/Q00/ouroboros'
  417. # --- Ouroboros console ------------------------------------------------------------
  418. # Once the install is done, start the browser console so a new user lands in a
  419. # guided UI. It runs in a hidden background process: the installer returns,
  420. # never waits on it beyond a bounded readiness check, and never fails because
  421. # of it. Releases without `ouroboros gui` get no console output at all.
  422. # Mirrors the same step at the end of scripts/install.sh.
  423. # -NoConsole or OUROBOROS_NO_CONSOLE=1 skips this step. The variable takes a
  424. # closed set of values; anything else is reported and treated as an opt-out,
  425. # because not starting a background server is the safe reading.
  426. function Test-ConsoleOptOut([bool]$Flag, [string]$Value) {
  427. if ($Flag) { return $true }
  428. $normalized = ''
  429. if ($Value) { $normalized = $Value.Trim().ToLowerInvariant() }
  430. if (@('', '0', 'false', 'no', 'off') -contains $normalized) { return $false }
  431. if (@('1', 'true', 'yes', 'on') -contains $normalized) { return $true }
  432. Write-Warn 'OUROBOROS_NO_CONSOLE has an unrecognized value (expected 1 or 0); not starting the console.'
  433. return $true
  434. }
  435. # `ouroboros gui --help` exits 0 only on a release that ships the console; older
  436. # ones fail with "No such command". Telemetry is off for the probe since it is
  437. # not a real use. A probe that outlives the timeout is killed and counts as no.
  438. function Test-ConsoleCommand([string]$Exe, [int]$TimeoutMs) {
  439. try {
  440. $info = New-Object System.Diagnostics.ProcessStartInfo
  441. $info.FileName = $Exe
  442. $info.Arguments = 'gui --help'
  443. $info.UseShellExecute = $false
  444. $info.CreateNoWindow = $true
  445. $info.RedirectStandardInput = $true
  446. $info.RedirectStandardOutput = $true
  447. $info.RedirectStandardError = $true
  448. $info.EnvironmentVariables['OUROBOROS_TELEMETRY'] = '0'
  449. $info.EnvironmentVariables['DO_NOT_TRACK'] = '1'
  450. $probe = [System.Diagnostics.Process]::Start($info)
  451. $probe.StandardInput.Close()
  452. # Drain both pipes so a chatty help screen cannot block the child.
  453. $null = $probe.StandardOutput.ReadToEndAsync()
  454. $null = $probe.StandardError.ReadToEndAsync()
  455. if (-not $probe.WaitForExit($TimeoutMs)) {
  456. # Kill is SIGKILL / TerminateProcess, which a child cannot ignore;
  457. # reaping it is bounded too, so the probe returns within the
  458. # timeout plus 2 s.
  459. try { $probe.Kill() } catch { }
  460. try { $null = $probe.WaitForExit(2000) } catch { }
  461. return $false
  462. }
  463. return ($probe.ExitCode -eq 0)
  464. } catch {
  465. return $false
  466. }
  467. }
  468. # A logon session with a desktop: services are not user-interactive, and an SSH
  469. # session's browser would open on this machine, not for the person connected.
  470. function Test-ConsoleDesktop {
  471. if (-not [Environment]::UserInteractive) { return $false }
  472. if ($env:SSH_CONNECTION -or $env:SSH_CLIENT -or $env:SSH_TTY) { return $false }
  473. return $true
  474. }
  475. # Turn the console's state file (~/.ouroboros/gui/server.json, written by
  476. # `ouroboros gui` once it listens) into the loopback URL it serves. Only a
  477. # well-formed JSON object counts (ConvertFrom-Json rejects trailing text), and
  478. # only its own top-level `host` (a loopback name) and `port` (an integer in
  479. # 1-65535) are read. Returns $null otherwise.
  480. function ConvertTo-ConsoleUrl([string]$Text) {
  481. if ([string]::IsNullOrWhiteSpace($Text)) { return $null }
  482. # ConvertFrom-Json unrolls a one-element array into its element; the
  483. # state must be an object itself.
  484. if (-not $Text.TrimStart(" `t`r`n".ToCharArray()).StartsWith('{')) { return $null }
  485. try { $state = ConvertFrom-Json -InputObject $Text } catch { return $null }
  486. if ($null -eq $state) { return $null }
  487. $names = @($state.PSObject.Properties | ForEach-Object { $_.Name })
  488. if (($names -notcontains 'port') -or ($names -notcontains 'host')) { return $null }
  489. $port = $state.port
  490. if (-not (($port -is [int]) -or ($port -is [long]))) { return $null }
  491. if ($port -lt 1 -or $port -gt 65535) { return $null }
  492. if (@('127.0.0.1', 'localhost', '0.0.0.0') -cnotcontains [string]$state.host) { return $null }
  493. return "http://localhost:$port/"
  494. }
  495. function Read-ConsoleState([string]$Path) {
  496. try { return [System.IO.File]::ReadAllText($Path) } catch { return '' }
  497. }
  498. # Start `ouroboros gui` hidden and wait at most $WaitMs for it to report its
  499. # address; every check in the wait is in-process, so the deadline holds. A
  500. # console that is already running is reused by `ouroboros gui`, which then only
  501. # opens the browser and exits 0. The logs get no explicit ACL: they inherit the
  502. # per-user %USERPROFILE%\.ouroboros\gui directory's permissions.
  503. function Start-ConsoleDetached([string]$Exe, [int]$WaitMs) {
  504. $dir = Join-Path (Join-Path $env:USERPROFILE '.ouroboros') 'gui'
  505. $statePath = Join-Path $dir 'server.json'
  506. $log = Join-Path $dir 'console.log'
  507. $errLog = Join-Path $dir 'console.err.log'
  508. try {
  509. New-Item -ItemType Directory -Force -Path $dir | Out-Null
  510. $before = Read-ConsoleState $statePath
  511. $process = Start-Process -FilePath $Exe -ArgumentList 'gui' -WindowStyle Hidden `
  512. -RedirectStandardOutput $log -RedirectStandardError $errLog -PassThru
  513. # Windows PowerShell 5.1 reports no ExitCode unless the handle was taken.
  514. $null = $process.Handle
  515. } catch {
  516. Write-Warn "The Ouroboros console did not start: $($_.Exception.Message). The installation itself is complete."
  517. Write-Info 'Start it any time with: ouroboros gui'
  518. return
  519. }
  520. $url = $null
  521. $exitCode = $null
  522. $last = $before
  523. $deadline = [DateTime]::UtcNow.AddMilliseconds($WaitMs)
  524. while ($true) {
  525. if ($process.HasExited) { $exitCode = $process.ExitCode; break }
  526. $current = Read-ConsoleState $statePath
  527. if ($current -and ($current -ne $last)) {
  528. $last = $current
  529. $url = ConvertTo-ConsoleUrl $current
  530. if ($url) { break }
  531. }
  532. if ([DateTime]::UtcNow -ge $deadline) { break }
  533. Start-Sleep -Milliseconds 100
  534. }
  535. if ($url) {
  536. Write-Ok "The Ouroboros console is running in the background at $url"
  537. Write-Info 'It opens in your browser. Stop it with "Stop console" at the bottom of its sidebar.'
  538. Write-Info 'Reopen it any time with: ouroboros gui'
  539. Write-Info "Log: $log"
  540. } elseif ($exitCode -eq 0) {
  541. $url = ConvertTo-ConsoleUrl (Read-ConsoleState $statePath)
  542. if ($url) {
  543. Write-Ok "The Ouroboros console is already running at $url; opened it in your browser."
  544. Write-Info 'Reopen it any time with: ouroboros gui'
  545. } else {
  546. Write-Warn 'Could not confirm that the Ouroboros console started.'
  547. Write-Info "Log: $log"
  548. Write-Info 'Start it any time with: ouroboros gui'
  549. }
  550. } elseif ($null -ne $exitCode) {
  551. Write-Warn "The Ouroboros console did not start (exit $exitCode). The installation itself is complete."
  552. Write-Info "Log: $errLog"
  553. Write-Info 'Start it any time with: ouroboros gui'
  554. } else {
  555. Write-Info 'The Ouroboros console is still starting in the background; it opens in your browser when ready.'
  556. Write-Info 'Stop it with "Stop console" at the bottom of its sidebar. Reopen it any time with: ouroboros gui'
  557. Write-Info "Log: $log"
  558. }
  559. }
  560. function Invoke-ConsoleAfterInstall([string]$Exe, [bool]$OptOut) {
  561. if ($OptOut -or -not $Exe) { return }
  562. if (-not (Test-ConsoleCommand $Exe 15000)) { return }
  563. if ((Test-Path Env:CI) -or -not (Test-Interactive) -or -not (Test-ConsoleDesktop)) {
  564. Write-Host ''
  565. Write-Host 'Next: open the Ouroboros console in your browser with: ouroboros gui'
  566. return
  567. }
  568. Write-Host ''
  569. Write-Host ' Ouroboros console' -ForegroundColor Blue
  570. Start-ConsoleDetached $Exe 20000
  571. }
  572. try {
  573. Invoke-ConsoleAfterInstall $ouroborosExe (Test-ConsoleOptOut ([bool]$NoConsole) $env:OUROBOROS_NO_CONSOLE)
  574. } catch {
  575. Write-Warn "Could not start the Ouroboros console: $($_.Exception.Message)"
  576. Write-Info 'Start it any time with: ouroboros gui'
  577. }
scripts/install.sh · Bundled script · 1,917 lines · 1 finding marked
  1. #!/bin/bash
  2. # Ouroboros installer — auto-detects runtime and installs accordingly.
  3. # Usage: curl -fsSL https://raw.githubusercontent.com/Q00/ouroboros/main/scripts/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 3 on GitHub
  4. #
  5. # Runtime selection (first match wins):
  6. # 1. OUROBOROS_INSTALL_RUNTIME env var
  7. # (claude|claude-sdk|claude-cli|codex|opencode|hermes|gemini|goose|kiro|copilot|pi|gjc|omp|all)
  8. # 2. Existing ~/.ouroboros/config.yaml runtime — preserved on upgrade
  9. # unless OUROBOROS_INSTALL_RECONFIGURE=1 (or --reconfigure flag) is set.
  10. # 3. Interactive prompt when stdin is a TTY.
  11. # 4. Auto-detect single CLI on PATH; default to claude in pipe mode.
  12. #
  13. # When no usable installer is present, uv is fetched from astral.sh because it
  14. # carries its own Python. Set OUROBOROS_INSTALL_BOOTSTRAP_UV=0 to decline that
  15. # and get installation instructions instead.
  16. #
  17. # Flags: --runtime <name>, --reconfigure, --no-console
  18. # (through a pipe: curl -fsSL <url> | bash -s -- --no-console)
  19. #
  20. # Console: when the installed release ships `ouroboros gui` and the install
  21. # finishes in an interactive desktop session (a reachable terminal, no CI
  22. # variable, macOS or a Linux/WSL display or WSL browser bridge, and not an
  23. # SSH session without a display), the Ouroboros console starts in the
  24. # background and opens in the browser. Otherwise only the command is printed.
  25. # Skip it with --no-console or OUROBOROS_NO_CONSOLE=1.
  26. set -euo pipefail
  27. PACKAGE_NAME="ouroboros-ai"
  28. CLICK_SPEC="click>=8.1.0,<9.0.0"
  29. MIN_PYTHON="3.12"
  30. DEFAULT_PYTHON_SPEC=">=3.12"
  31. LITELLM_PYTHON_SPEC=">=3.12,<3.14"
  32. IS_LOCAL=false
  33. RECONFIGURE="${OUROBOROS_INSTALL_RECONFIGURE:-}"
  34. EXPLICIT_RUNTIME="${OUROBOROS_INSTALL_RUNTIME:-}"
  35. BOOTSTRAP_UV="${OUROBOROS_INSTALL_BOOTSTRAP_UV:-1}"
  36. NO_CONSOLE_FLAG=""
  37. if [ -z "${NO_COLOR:-}" ] && { [ -t 1 ] || [ -n "${FORCE_COLOR:-}" ]; } && { [ "${TERM:-}" != "dumb" ] || [ -n "${FORCE_COLOR:-}" ]; }; then
  38. BOLD="$(printf '\033[1m')"
  39. DIM="$(printf '\033[2m')"
  40. GREEN="$(printf '\033[1;32m')"
  41. YELLOW="$(printf '\033[1;33m')"
  42. BLUE="$(printf '\033[1;34m')"
  43. CYAN="$(printf '\033[1;36m')"
  44. MAGENTA="$(printf '\033[1;35m')"
  45. RED="$(printf '\033[1;31m')"
  46. RESET="$(printf '\033[0m')"
  47. else
  48. BOLD=""
  49. DIM=""
  50. GREEN=""
  51. YELLOW=""
  52. BLUE=""
  53. CYAN=""
  54. MAGENTA=""
  55. RED=""
  56. RESET=""
  57. fi
  58. _say() {
  59. printf '%s\n' "$*"
  60. }
  61. _blank() {
  62. printf '\n'
  63. }
  64. _banner() {
  65. _say "${MAGENTA}╭────────────────────────────────────────────╮${RESET}"
  66. _say "${MAGENTA}│${RESET} ${BOLD}${CYAN}Ouroboros installer${RESET} ${MAGENTA}│${RESET}"
  67. _say "${MAGENTA}│${RESET} ${DIM}Specification-first AI development${RESET} ${MAGENTA}│${RESET}"
  68. _say "${MAGENTA}╰────────────────────────────────────────────╯${RESET}"
  69. _say "${DIM}Installs the CLI, chooses an agent backend, and wires up local skills.${RESET}"
  70. }
  71. _step() {
  72. _blank
  73. _say "${BLUE}◆${RESET} ${BOLD}$1${RESET}"
  74. if [ "${2:-}" != "" ]; then
  75. _say " ${DIM}$2${RESET}"
  76. fi
  77. }
  78. _ok() {
  79. _say " ${GREEN}✓${RESET} $1"
  80. }
  81. _warn() {
  82. _say " ${YELLOW}!${RESET} $1"
  83. }
  84. _err() {
  85. _say " ${RED}✗${RESET} $1"
  86. }
  87. _info() {
  88. _say " ${DIM}•${RESET} $1"
  89. }
  90. # Quote a string as one shell word using ASCII only, independent of the host
  91. # bash version. `printf %q` cannot be used here: bash 3.2 (the macOS system
  92. # bash) escapes only the bytes of a multibyte character that it happens to
  93. # consider unsafe, leaving the rest raw, which emits invalid UTF-8 and lets a
  94. # profile name smuggle RTL overrides or ANSI escapes into the terminal. This
  95. # escapes every byte outside a conservative safe set, so the output is always
  96. # printable ASCII and always re-reads as the original name.
  97. _shell_quote() {
  98. local _sq_in=$1 _sq_out='' _sq_char _sq_code _sq_i _sq_len
  99. local LC_ALL=C
  100. case $_sq_in in
  101. '') printf "\$''"; return ;;
  102. *[!A-Za-z0-9_.,:/@%+=-]*) ;;
  103. *) printf '%s' "$_sq_in"; return ;;
  104. esac
  105. _sq_len=${#_sq_in}
  106. _sq_i=0
  107. while [ "$_sq_i" -lt "$_sq_len" ]; do
  108. _sq_char=${_sq_in:_sq_i:1}
  109. case $_sq_char in
  110. [A-Za-z0-9_.,:/@%+=-]) _sq_out=$_sq_out$_sq_char ;;
  111. *)
  112. # `printf "'c"` yields a signed value, so bytes >= 0x80 arrive
  113. # negative; mask them back into the 0-255 range before formatting.
  114. printf -v _sq_code '%d' "'$_sq_char"
  115. printf -v _sq_code '%03o' "$((_sq_code & 255))"
  116. _sq_out=$_sq_out\\$_sq_code
  117. ;;
  118. esac
  119. _sq_i=$((_sq_i + 1))
  120. done
  121. printf '%s' "\$'$_sq_out'"
  122. }
  123. _choice() {
  124. printf ' %b[%s]%b %-8s %s\n' "$BOLD" "$1" "$RESET" "$2" "$3"
  125. }
  126. _prompt() {
  127. printf '%b' "${BOLD}$1${RESET}"
  128. }
  129. # --- Anonymous install telemetry (PostHog) ---------------------------------
  130. # Same privacy contract as the CLI (see TELEMETRY.md): random UUID, no PII,
  131. # no code/paths. Disable with DO_NOT_TRACK=1, OUROBOROS_TELEMETRY=0, or
  132. # telemetry.enabled: false in ~/.ouroboros/config.yaml.
  133. # The API key is a public write-only PostHog project key.
  134. # TELEMETRY.md declares ~/.ouroboros/.env a trusted persistent control
  135. # source; the application loader applies it at import via python-dotenv's
  136. # dotenv_values(), which resolves a key repeated in the file to its LAST
  137. # occurrence. This standalone installer must honor the same telemetry keys
  138. # before any notice or capture, so a persisted opt-out or destination
  139. # override there holds during install -- including matching that same
  140. # last-wins resolution for an internally-duplicated key, so the two loaders
  141. # never disagree about a single file's meaning. Only the four allowlisted
  142. # telemetry keys are read, and an already-set real process environment
  143. # value always wins over the file, no matter how many times a key repeats
  144. # in it (mirrors config/loader.py).
  145. #
  146. # Grammar covered exactly like dotenv_values(): bare/export-prefixed
  147. # bindings, single- and double-quoted values (with an inline `# comment`
  148. # after a closing quote), one layer of matching quotes around the KEY
  149. # itself, and last-wins on duplicate keys. Grammar this single-line shell
  150. # reader genuinely cannot follow -- a physically MULTILINE quoted value, or
  151. # an ESCAPE sequence inside a double-quoted value -- is never guessed at:
  152. # `_TELEMETRY_USER_ENV_AMBIGUOUS` is set instead, and `_telemetry_enabled`
  153. # treats that as an unconditional opt-out. A real parse error dotenv itself
  154. # also rejects (trailing garbage after a legitimate closing quote) stays a
  155. # plain skip -- both loaders already agree there's nothing to trust there.
  156. _telemetry_load_user_env() {
  157. local f="$HOME/.ouroboros/.env" line key value rest after trailing
  158. local preset_var parsed_var
  159. local preset_DO_NOT_TRACK preset_OUROBOROS_TELEMETRY
  160. local preset_OUROBOROS_POSTHOG_API_KEY preset_OUROBOROS_POSTHOG_HOST
  161. local parsed_DO_NOT_TRACK="" parsed_OUROBOROS_TELEMETRY=""
  162. local parsed_OUROBOROS_POSTHOG_API_KEY="" parsed_OUROBOROS_POSTHOG_HOST=""
  163. { [ -f "$f" ] && [ -r "$f" ]; } || return 0
  164. # Phase 1: snapshot which of the four allowlisted keys are already set in
  165. # the REAL process environment, before the trusted file is consulted at
  166. # all -- this is the one precedence check that must survive unchanged.
  167. for key in DO_NOT_TRACK OUROBOROS_TELEMETRY OUROBOROS_POSTHOG_API_KEY OUROBOROS_POSTHOG_HOST; do
  168. if eval "[ -n \"\${$key+x}\" ]"; then
  169. printf -v "preset_$key" '%s' true
  170. else
  171. printf -v "preset_$key" '%s' false
  172. fi
  173. done
  174. while IFS= read -r line || [ -n "$line" ]; do
  175. line="${line#"${line%%[![:space:]]*}"}"
  176. case "$line" in ''|'#'*) continue ;; esac
  177. case "$line" in
  178. export[[:space:]]*)
  179. line="${line#export}"
  180. line="${line#"${line%%[![:space:]]*}"}"
  181. ;;
  182. esac
  183. case "$line" in *=*) ;; *) continue ;; esac
  184. key="${line%%=*}"
  185. key="${key%"${key##*[![:space:]]}"}"
  186. # python-dotenv also accepts a key wrapped in one layer of matching
  187. # quotes (`'OUROBOROS_TELEMETRY'=0`, `"DO_NOT_TRACK"=1`) -- strip it
  188. # before the allowlist check so those parse identically to the bare
  189. # form. A key that only has ONE side quoted (no matching closing quote)
  190. # falls through unchanged and correctly misses the allowlist below,
  191. # same as today.
  192. case "$key" in
  193. \"*\")
  194. key="${key#\"}"
  195. key="${key%\"}"
  196. ;;
  197. \'*\')
  198. key="${key#\'}"
  199. key="${key%\'}"
  200. ;;
  201. esac
  202. case "$key" in
  203. DO_NOT_TRACK|OUROBOROS_TELEMETRY|OUROBOROS_POSTHOG_API_KEY|OUROBOROS_POSTHOG_HOST) ;;
  204. *) continue ;;
  205. esac
  206. value="${line#*=}"
  207. value="${value#"${value%%[![:space:]]*}"}"
  208. case "$value" in
  209. \"*)
  210. # A quoted value's content runs to the FIRST matching quote; only
  211. # trailing whitespace and/or a `# comment` may follow it (matches
  212. # python-dotenv). This is what makes a normal persisted opt-out like
  213. # `OUROBOROS_TELEMETRY="0" # persisted opt-out` parse to "0" instead
  214. # of falling into the unquoted branch below and keeping its quotes.
  215. # A missing closing quote and trailing garbage after a real closing
  216. # quote are NOT the same situation in dotenv, even though both look
  217. # like "unparseable" to a single-line shell reader:
  218. # - trailing garbage after a legitimate closing quote (e.g.
  219. # `OUROBOROS_TELEMETRY="0"x`) IS a parse error in python-dotenv
  220. # too -- both sides skip the binding, no disagreement possible.
  221. # - a MISSING closing quote is not an error to dotenv at all: it
  222. # is the start of a value that continues reading subsequent
  223. # PHYSICAL LINES until a closing quote is found (a genuinely
  224. # multiline value), which this single-line reader cannot
  225. # follow. Silently skipping here left telemetry ON while the
  226. # application resolved a real (stripped) value -- fail closed
  227. # instead, same posture as the escape-bearing case below.
  228. rest="${value#\"}"
  229. case "$rest" in
  230. *\"*) ;;
  231. *) _TELEMETRY_USER_ENV_AMBIGUOUS=1; continue ;;
  232. esac
  233. after="${rest#*\"}"
  234. trailing="${after#"${after%%[![:space:]]*}"}"
  235. case "$trailing" in
  236. ''|'#'*) ;;
  237. *) continue ;;
  238. esac
  239. value="${rest%%\"*}"
  240. # dotenv_values() decodes backslash escapes inside a double-quoted
  241. # value (e.g. the two source characters `\n` become an actual
  242. # newline); this shell parser copies them literally. A hand-rolled
  243. # parser will never chase python-dotenv's full escape grammar
  244. # (`\"` alone would need real state tracking), so rather than guess
  245. # and risk agreeing with neither interpretation, refuse to trust
  246. # THIS occurrence's value at all and force telemetry off for the
  247. # whole run: under-collecting on an ambiguous value is always safe,
  248. # over-collecting is the actual privacy violation. This is
  249. # deliberately asymmetric -- an ambiguous value that LOOKS like an
  250. # enable (e.g. `"1\n"`) also disables the installer run, diverging
  251. # from the application only in the safe direction.
  252. case "$value" in
  253. *\\*) _TELEMETRY_USER_ENV_AMBIGUOUS=1; continue ;;
  254. esac
  255. ;;
  256. \'*)
  257. # Single-quoted values are literal (no escape decoding, matching
  258. # today's handling already), but a missing closing quote has the
  259. # SAME multiline-continuation meaning in dotenv as the double-quote
  260. # case above -- fail closed for the same reason, not a plain skip.
  261. rest="${value#\'}"
  262. case "$rest" in
  263. *\'*) ;;
  264. *) _TELEMETRY_USER_ENV_AMBIGUOUS=1; continue ;;
  265. esac
  266. after="${rest#*\'}"
  267. trailing="${after#"${after%%[![:space:]]*}"}"
  268. case "$trailing" in
  269. ''|'#'*) ;;
  270. *) continue ;;
  271. esac
  272. value="${rest%%\'*}"
  273. ;;
  274. *)
  275. # Unquoted values follow dotenv grammar: an inline ` # comment` is
  276. # not part of the value. Dropping it here matters for opt-outs --
  277. # `OUROBOROS_TELEMETRY=0 # off` must parse as "0", not fail the
  278. # flag match and silently keep collection on.
  279. value="${value%%[[:space:]]#*}"
  280. value="${value%"${value##*[![:space:]]}"}"
  281. ;;
  282. esac
  283. [ -n "$value" ] || continue
  284. # Phase 2: accumulate into a per-key holding variable rather than
  285. # exporting immediately -- overwriting on every valid occurrence gives
  286. # LAST-wins semantics for a key duplicated WITHIN the trusted file,
  287. # matching dotenv_values(). The old per-line "export, then skip if
  288. # already set" approach silently flipped this to first-wins: once the
  289. # first occurrence exported the variable, the same `${key+x}` guard
  290. # would already be true for every later occurrence in THIS SAME file
  291. # too, blocking them even though none of them are the real process env
  292. # this guard exists to protect.
  293. printf -v "parsed_$key" '%s' "$value"
  294. done < "$f"
  295. # Phase 3: export each key's last-parsed-from-file value, but ONLY if it
  296. # was not already present in the real process environment (phase 1) --
  297. # preserving real process-env precedence while now resolving duplicates
  298. # inside the file itself with last-wins instead of first-wins. An empty
  299. # `parsed_*` here means no occurrence in the file ever produced a value
  300. # worth keeping (every occurrence, if any, failed to parse or was empty).
  301. for key in DO_NOT_TRACK OUROBOROS_TELEMETRY OUROBOROS_POSTHOG_API_KEY OUROBOROS_POSTHOG_HOST; do
  302. preset_var="preset_$key"
  303. parsed_var="parsed_$key"
  304. if [ "${!preset_var}" = false ] && [ -n "${!parsed_var}" ]; then
  305. export "$key=${!parsed_var}"
  306. fi
  307. done
  308. }
  309. _telemetry_load_user_env
  310. PH_API_KEY="${OUROBOROS_POSTHOG_API_KEY:-phc_mSoetD4ExLDDCi3vNua635NhwRTgHfRaCG9WYNKmrvv5}"
  311. PH_HOST="${OUROBOROS_POSTHOG_HOST:-https://us.i.posthog.com}"
  312. _telemetry_config_allows() {
  313. local f="$HOME/.ouroboros/config.yaml" script_path script_dir source_root=""
  314. local python_candidate ouroboros_cmd shebang status
  315. # `-e` is false for a dangling symlink. That is invalid persisted state,
  316. # not a genuinely absent config, so keep it on the fail-closed path.
  317. [ -e "$f" ] || [ -L "$f" ] || return 0
  318. [ -r "$f" ] || return 1
  319. # Match the application resolver: parse the complete YAML document and
  320. # validate every known field before trusting telemetry.enabled. A partial
  321. # text parser can accept telemetry.enabled=true while overlooking malformed
  322. # YAML or an invalid unrelated field. Existing configuration therefore
  323. # requires a Python environment with Ouroboros' real schema available;
  324. # otherwise collection fails closed. A genuinely absent config retains the
  325. # documented default-on behavior after the notice below.
  326. # `curl | bash` has no sourced file path; nounset must not break this
  327. # optional local-source optimization.
  328. script_path="${BASH_SOURCE[0]-}"
  329. script_dir=""
  330. if [ -n "$script_path" ]; then
  331. script_dir=$(CDPATH='' cd -- "$(dirname -- "$script_path")" 2>/dev/null && pwd) || true
  332. fi
  333. if [ -n "$script_dir" ] && [ -f "$script_dir/../src/ouroboros/config/models.py" ]; then
  334. source_root=$(CDPATH='' cd -- "$script_dir/../src" 2>/dev/null && pwd) || true
  335. fi
  336. _telemetry_validate_config_with_python() {
  337. local interpreter="$1"
  338. "$interpreter" -I - "$f" "$source_root" <<'PY'
  339. import sys
  340. config_path, source_root = sys.argv[1:]
  341. if source_root:
  342. sys.path.insert(0, source_root)
  343. try:
  344. import yaml
  345. from ouroboros.config.models import OuroborosConfig
  346. except Exception:
  347. raise SystemExit(2)
  348. try:
  349. with open(config_path, encoding="utf-8") as config_file:
  350. raw = yaml.safe_load(config_file)
  351. config = OuroborosConfig.model_validate({} if raw is None else raw)
  352. except Exception:
  353. raise SystemExit(1)
  354. # Older installed schemas may validate without a telemetry field. Fail closed
  355. # instead of dereferencing an attribute the schema does not have.
  356. enabled = getattr(getattr(config, "telemetry", None), "enabled", False)
  357. raise SystemExit(0 if enabled is True else 1)
  358. PY
  359. }
  360. for python_candidate in python3 python; do
  361. python_candidate=$(command -v "$python_candidate" 2>/dev/null || true)
  362. [ -n "$python_candidate" ] || continue
  363. if _telemetry_validate_config_with_python "$python_candidate"; then
  364. unset -f _telemetry_validate_config_with_python
  365. return 0
  366. else
  367. status=$?
  368. if [ "$status" -ne 2 ]; then
  369. unset -f _telemetry_validate_config_with_python
  370. return 1
  371. fi
  372. fi
  373. done
  374. # uv/pipx entry points carry their environment's Python interpreter in the
  375. # shebang. It may have the schema when the system Python does not.
  376. ouroboros_cmd=$(command -v ouroboros 2>/dev/null || true)
  377. if [ -n "$ouroboros_cmd" ] && [ -r "$ouroboros_cmd" ]; then
  378. shebang=$(head -n 1 "$ouroboros_cmd" 2>/dev/null || true)
  379. case "$shebang" in
  380. '#!'/*)
  381. python_candidate=${shebang#'#!'}
  382. case "$python_candidate" in
  383. *' '*) ;;
  384. *)
  385. if [ -x "$python_candidate" ]; then
  386. if _telemetry_validate_config_with_python "$python_candidate"; then
  387. unset -f _telemetry_validate_config_with_python
  388. return 0
  389. fi
  390. fi
  391. ;;
  392. esac
  393. ;;
  394. esac
  395. fi
  396. unset -f _telemetry_validate_config_with_python
  397. return 1
  398. }
  399. _telemetry_enabled() {
  400. [ -n "$PH_API_KEY" ] || return 1
  401. # Set by _telemetry_load_user_env when a trusted-file value couldn't be
  402. # parsed unambiguously (an escape-bearing double-quoted value) -- an
  403. # opt-out this installer cannot resolve is treated as an opt-out, not
  404. # ignored. Any one disabling control wins, matching every other flag here.
  405. [ -z "${_TELEMETRY_USER_ENV_AMBIGUOUS:-}" ] || return 1
  406. local dnt oel
  407. # Lowercase and trim each flag before matching so `OFF`, `Yes`, `TRUE`,
  408. # or values with stray whitespace are recognized the same as their
  409. # canonical lowercase forms (mirrors config/loader.py's `.strip().lower()`).
  410. dnt=$(printf '%s' "${DO_NOT_TRACK:-}" | tr '[:upper:]' '[:lower:]')
  411. dnt="${dnt#"${dnt%%[![:space:]]*}"}"
  412. dnt="${dnt%"${dnt##*[![:space:]]}"}"
  413. case "$dnt" in 1|true|on|yes) return 1 ;; esac
  414. oel=$(printf '%s' "${OUROBOROS_TELEMETRY:-}" | tr '[:upper:]' '[:lower:]')
  415. oel="${oel#"${oel%%[![:space:]]*}"}"
  416. oel="${oel%"${oel##*[![:space:]]}"}"
  417. case "$oel" in 0|false|off|no) return 1 ;; esac
  418. # OUROBOROS_TELEMETRY=1 is never an override: persisted opt-out and
  419. # malformed configuration stay authoritative (TELEMETRY.md: any one
  420. # disabling control wins), matching the application resolver.
  421. _telemetry_config_allows || return 1
  422. command -v curl &>/dev/null || return 1
  423. return 0
  424. }
  425. _telemetry_distinct_id() {
  426. local f="$HOME/.ouroboros/telemetry.json" id="" winner_id="" tmp file_existed=false lockdir wait_i
  427. local salvage_id=""
  428. local uuid_re='^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
  429. # Four nested helpers, all `unset -f` below so extracting just this outer
  430. # function's source -- e.g. for an isolated concurrency-test driver --
  431. # carries them along automatically instead of leaving a dangling
  432. # reference:
  433. #
  434. # _telemetry_extract_uuid -- LENIENT, TEXT-ONLY. Prints the id,
  435. # canonicalized to lowercase, whenever a sed match ANYWHERE in the raw
  436. # text looks UUID-shaped -- ignorant of JSON structure entirely. This is
  437. # only correct for genuinely unparseable text (telemetry.py salvages the
  438. # same way there, via a raw-text regex): once a document IS valid JSON,
  439. # a sed match found "anywhere" could be nested inside another object, or
  440. # the first of several duplicate top-level keys, and must NOT be trusted
  441. # -- see `_telemetry_read_state`.
  442. #
  443. # _telemetry_read_state -- the structural source of truth. Requires
  444. # python3 (a soft dependency elsewhere in this installer too). Parses
  445. # the file as JSON and looks at the TOP-LEVEL `distinct_id` field only
  446. # -- Python's own json.load naturally resolves duplicate keys to the
  447. # LAST occurrence, matching telemetry.py's loader exactly, and a value
  448. # nested inside another object is correctly invisible to a plain
  449. # `data.get(...)`. Prints one of: `CANONICAL:<id>` (top-level, pattern-
  450. # valid, already lowercase -- fully valid, no repair needed),
  451. # `REPAIR:<id>` (top-level, pattern-valid, wrong case -- a real identity
  452. # worth salvaging, canonicalized), `INVALID` (valid JSON, but no usable
  453. # top-level id -- missing, non-string, non-UUID, or only present nested
  454. # -- telemetry.py does NOT salvage from a valid-but-wrong-shaped
  455. # document, only from unparseable text, so this must NOT fall through to
  456. # the lenient text search), `MALFORMED` (not valid JSON at all -- the
  457. # lenient, text-only salvage path legitimately applies here), or
  458. # `NO_PYTHON3` when python3 isn't on PATH -- without a JSON parser, pure
  459. # shell cannot tell top-level from nested or resolve duplicate keys, so
  460. # this is a documented best-effort gap.
  461. #
  462. # _telemetry_canonical_id -- STRICT adopt-without-repair check ("has a
  463. # real repair already landed on disk"): CANONICAL only when python3 is
  464. # present; falls back to the old pattern+case-only sed check (no
  465. # structural awareness) when it is not.
  466. #
  467. # _telemetry_salvage_candidate -- the repair candidate getter: reuses a
  468. # REPAIR-state top-level id or a MALFORMED-text lenient match; withholds
  469. # entirely on INVALID (mirrors telemetry.py: no salvage from valid JSON
  470. # lacking a usable top-level id); falls back to the lenient text search
  471. # without python3.
  472. _telemetry_extract_uuid() {
  473. local r
  474. r=$(sed -n 's/.*"distinct_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$1" 2>/dev/null | head -1)
  475. if [[ "$r" =~ $uuid_re ]]; then
  476. printf '%s' "$r" | tr '[:upper:]' '[:lower:]'
  477. fi
  478. }
  479. _telemetry_read_state() {
  480. local py
  481. py=$(command -v python3 2>/dev/null || true)
  482. if [ -z "$py" ]; then
  483. printf 'NO_PYTHON3'
  484. return 0
  485. fi
  486. "$py" -c '
  487. import json, re, sys
  488. uuid_re = re.compile(
  489. r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
  490. )
  491. try:
  492. with open(sys.argv[1], encoding="utf-8") as fh:
  493. data = json.load(fh)
  494. except Exception:
  495. print("MALFORMED")
  496. else:
  497. value = data.get("distinct_id") if isinstance(data, dict) else None
  498. if isinstance(value, str) and uuid_re.match(value):
  499. lowered = value.lower()
  500. print(("CANONICAL:" if lowered == value else "REPAIR:") + lowered)
  501. else:
  502. print("INVALID")
  503. ' "$1" 2>/dev/null
  504. }
  505. _telemetry_canonical_id() {
  506. local state r
  507. state=$(_telemetry_read_state "$1")
  508. case "$state" in
  509. CANONICAL:*)
  510. printf '%s' "${state#CANONICAL:}"
  511. ;;
  512. NO_PYTHON3)
  513. r=$(sed -n 's/.*"distinct_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$1" 2>/dev/null | head -1)
  514. [[ "$r" =~ $uuid_re ]] || return 0
  515. [ "$r" = "$(printf '%s' "$r" | tr '[:upper:]' '[:lower:]')" ] || return 0
  516. printf '%s' "$r"
  517. ;;
  518. *) ;; # REPAIR / INVALID / MALFORMED: not yet fully valid
  519. esac
  520. }
  521. _telemetry_salvage_candidate() {
  522. local state
  523. state=$(_telemetry_read_state "$1")
  524. case "$state" in
  525. CANONICAL:*) printf '%s' "${state#CANONICAL:}" ;;
  526. REPAIR:*) printf '%s' "${state#REPAIR:}" ;;
  527. INVALID) ;; # valid JSON, no usable top-level id -- no salvage
  528. *) _telemetry_extract_uuid "$1" ;; # MALFORMED or NO_PYTHON3
  529. esac
  530. }
  531. if [ -f "$f" ]; then
  532. file_existed=true
  533. id=$(_telemetry_canonical_id "$f")
  534. if [ -z "$id" ]; then
  535. # Not already fully valid. Keep a real (top-level, or -- only for
  536. # genuinely unparseable text -- lenient-text) id as a SALVAGE
  537. # candidate rather than discarding it for a fresh mint; an id that
  538. # isn't usable at all (no field, a non-UUID value, or only nested
  539. # inside otherwise-valid JSON) leaves `salvage_id` empty and is
  540. # treated as fully corrupt below.
  541. salvage_id=$(_telemetry_salvage_candidate "$f")
  542. fi
  543. fi
  544. if [ -z "$id" ]; then
  545. if [ -n "$salvage_id" ]; then
  546. id="$salvage_id"
  547. elif command -v uuidgen &>/dev/null; then
  548. id=$(uuidgen | tr '[:upper:]' '[:lower:]')
  549. elif command -v python3 &>/dev/null; then
  550. id=$(python3 -c "import uuid; print(uuid.uuid4())" 2>/dev/null || true)
  551. fi
  552. if [ -z "$id" ]; then
  553. unset -f _telemetry_extract_uuid _telemetry_read_state _telemetry_canonical_id _telemetry_salvage_candidate
  554. return 1
  555. fi
  556. if ! mkdir -p "$HOME/.ouroboros" 2>/dev/null; then
  557. unset -f _telemetry_extract_uuid _telemetry_read_state _telemetry_canonical_id _telemetry_salvage_candidate
  558. return 1
  559. fi
  560. # Publish the (fresh or salvaged) identity via a same-directory temp
  561. # file, then re-read whatever actually landed on disk instead of
  562. # trusting our own candidate:
  563. # - `$f` absent: publish with `ln` (hard link) — atomic
  564. # create-if-not-exists, it fails if a concurrently-starting process
  565. # (e.g. `ouroboros setup` in step 4, or another MCP session) already
  566. # won, so nothing here is ever clobbered.
  567. # - `$f` present but invalid (unparseable, no distinct_id, a non-UUID
  568. # value, mismatched case, or malformed JSON around an otherwise
  569. # salvageable id): `ln`/an unconditional `mv` are not enough here —
  570. # every racing process would each mint or salvage independently and
  571. # the last `mv` would silently win, so processes that already
  572. # emitted events under their own reading would disagree with what
  573. # ends up persisted. Exactly one process must own the repair.
  574. # `$f.repair.lock` is the SAME lock name telemetry.py's
  575. # `_repair_state` uses (it creates the path with `O_CREAT|O_EXCL` as
  576. # a file; here `mkdir` is the atomic create-if-not-exists primitive).
  577. # Both primitives only check whether *something* already exists at
  578. # that path, regardless of type, so a shell `mkdir` and a Python
  579. # `O_EXCL` file open correctly exclude each other at the same path
  580. # (verified on macOS: whichever side creates the path first, the
  581. # other's create call fails with EEXIST).
  582. # Either way, every process then adopts whichever valid, canonical
  583. # distinct_id survives in `$f` (mirrors telemetry.py's
  584. # `_publish_new_state` / `_repair_state`, which apply the same
  585. # UUID-validate-canonicalize-and-salvage rules).
  586. tmp="$f.$$.tmp"
  587. # Grouped so an unwritable `$HOME/.ouroboros` (read-only dir, e.g.) is
  588. # silent: a shell redirection's own open failure prints to the *current*
  589. # stderr before the trailing `2>/dev/null` on this line ever takes
  590. # effect, unlike an external command's (mv/ln/mkdir below) own error
  591. # output, which a trailing `2>/dev/null` does catch.
  592. { printf '{"distinct_id": "%s", "created_at": "%s", "notice_shown": false}\n' \
  593. "$id" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$tmp"; } 2>/dev/null || true
  594. if [ "$file_existed" = true ]; then
  595. lockdir="$f.repair.lock"
  596. if mkdir "$lockdir" 2>/dev/null; then
  597. # WINNER: re-validate under the lock -- another process may have
  598. # repaired the file (to a valid id) between our first read and
  599. # acquiring it.
  600. winner_id=$(_telemetry_canonical_id "$f")
  601. [ -n "$winner_id" ] || mv "$tmp" "$f" 2>/dev/null || true
  602. rmdir "$lockdir" 2>/dev/null || true
  603. else
  604. # LOSER: someone else owns the repair (or a stale lock). Wait,
  605. # bounded, for a valid id to land.
  606. winner_id=""
  607. wait_i=0
  608. while [ "$wait_i" -lt 10 ]; do
  609. sleep 0.05
  610. winner_id=$(_telemetry_canonical_id "$f")
  611. [ -n "$winner_id" ] && break
  612. wait_i=$((wait_i + 1))
  613. done
  614. if [ -z "$winner_id" ]; then
  615. # Lock never cleared (stale, from a killed process) -- take over
  616. # the replace ourselves rather than waiting forever, accepting
  617. # the tiny remaining race.
  618. mv "$tmp" "$f" 2>/dev/null || true
  619. rmdir "$lockdir" 2>/dev/null || rm -f "$lockdir" 2>/dev/null || true
  620. fi
  621. fi
  622. else
  623. ln "$tmp" "$f" 2>/dev/null || true
  624. fi
  625. rm -f "$tmp" 2>/dev/null || true
  626. # Fail-closed reread: if neither our own publish/repair attempt nor
  627. # anyone else's landed a usable id on disk (e.g. `$HOME/.ouroboros` is
  628. # unwritable/read-only, so every `mv`/`ln` above silently failed),
  629. # printing the local candidate would emit under an ephemeral,
  630. # never-persisted identity that no other process -- or a later run of
  631. # this same one -- could ever reproduce, permanently fragmenting
  632. # identity instead of just skipping a run's telemetry. Drop instead
  633. # (callers already treat a nonzero return as "skip telemetry"), matching
  634. # telemetry.py's stable-identity contract. Deliberately
  635. # `_telemetry_salvage_candidate`, not the strict `_telemetry_canonical_id`:
  636. # this is a "is there now a real, reusable identity at all" check, not a
  637. # "was it perfectly repaired" check -- a top-level id already sitting in
  638. # a file we couldn't write to is still a stable value every future read
  639. # of that same file will keep finding, so it's the best available
  640. # anchor, not a reason to go fully ephemeral. It still withholds on a
  641. # valid-JSON `INVALID` state (no usable top-level id) exactly as the
  642. # top-of-function salvage check does, so this reread can never resurrect
  643. # a nested-only or otherwise-unusable value that was correctly rejected
  644. # earlier in this same call.
  645. winner_id=$(_telemetry_salvage_candidate "$f")
  646. if [ -z "$winner_id" ]; then
  647. unset -f _telemetry_extract_uuid _telemetry_read_state _telemetry_canonical_id _telemetry_salvage_candidate
  648. return 1
  649. fi
  650. id="$winner_id"
  651. fi
  652. unset -f _telemetry_extract_uuid _telemetry_read_state _telemetry_canonical_id _telemetry_salvage_candidate
  653. printf '%s' "$id"
  654. }
  655. _telemetry_notice() {
  656. _telemetry_enabled || return 0
  657. local f="$HOME/.ouroboros/telemetry.json" tmp id py already_shown
  658. # Skip only when the persisted state is valid JSON, a dict, and its
  659. # TOP-LEVEL `notice_shown` is the literal boolean `true` -- mirrors the
  660. # identity reader's structural approach above (and telemetry.py's own
  661. # check). Fail toward disclosure: missing, nested-only (e.g. a
  662. # `{"wrapper": {"notice_shown": true}}` sibling object), a string
  663. # "true"/"false", any other non-bool, or malformed JSON must all still
  664. # show the notice -- a duplicate notice is harmless, a suppressed one
  665. # breaks the privacy contract. Without python3 on PATH we cannot parse
  666. # JSON structure in pure shell, so this falls back to the old raw-text
  667. # grep (documented best-effort gap, matches the identity reader's
  668. # NO_PYTHON3 fallback).
  669. py=$(command -v python3 2>/dev/null || true)
  670. already_shown=false
  671. if [ -f "$f" ]; then
  672. if [ -n "$py" ]; then
  673. if "$py" -c '
  674. import json, sys
  675. try:
  676. with open(sys.argv[1], encoding="utf-8") as fh:
  677. data = json.load(fh)
  678. except Exception:
  679. sys.exit(1)
  680. sys.exit(0 if isinstance(data, dict) and data.get("notice_shown") is True else 1)
  681. ' "$f" 2>/dev/null; then
  682. already_shown=true
  683. fi
  684. elif grep -q '"notice_shown"[[:space:]]*:[[:space:]]*true' "$f" 2>/dev/null; then
  685. already_shown=true
  686. fi
  687. fi
  688. [ "$already_shown" = false ] || return 0
  689. _blank
  690. _say "${BOLD}Anonymous usage stats help improve Ouroboros.${RESET}"
  691. _info "Collects commands, versions, and success rates — never code, prompts, or paths."
  692. _info "Opt out: export OUROBOROS_TELEMETRY=0 | details: https://github.com/Q00/ouroboros/blob/main/TELEMETRY.md"
  693. # Persist the one-time notice before the first collection attempt. Failure
  694. # is harmless: this run was disclosed and a later run will disclose again.
  695. id=$(_telemetry_distinct_id) || return 0
  696. [ -n "$id" ] || return 0
  697. tmp="${f}.notice.$$"
  698. if [ -n "$py" ]; then
  699. # Structural set: parses the file, sets the TOP-LEVEL `notice_shown` to
  700. # the literal boolean `true`, and preserves every other field as-is.
  701. # Unlike the sed fallback below, this also covers a document whose
  702. # top-level `notice_shown` never existed in the first place (e.g. an
  703. # already-valid identity file that was never rewritten by the repair
  704. # path above) -- a blind "replace false with true" text substitution
  705. # has nothing to match there and would silently leave the field
  706. # missing forever, so a later run would show the notice again.
  707. if "$py" -c '
  708. import json, sys
  709. try:
  710. with open(sys.argv[1], encoding="utf-8") as fh:
  711. data = json.load(fh)
  712. if not isinstance(data, dict):
  713. raise ValueError("top-level JSON value is not an object")
  714. except Exception:
  715. sys.exit(1)
  716. data["notice_shown"] = True
  717. with open(sys.argv[2], "w", encoding="utf-8") as fh:
  718. json.dump(data, fh)
  719. fh.write("\n")
  720. ' "$f" "$tmp" 2>/dev/null; then
  721. mv "$tmp" "$f" 2>/dev/null || true
  722. fi
  723. elif sed 's/"notice_shown"[[:space:]]*:[[:space:]]*false/"notice_shown": true/' "$f" > "$tmp" 2>/dev/null; then
  724. mv "$tmp" "$f" 2>/dev/null || true
  725. fi
  726. rm -f "$tmp" 2>/dev/null || true
  727. }
  728. # _telemetry_ping <event> [key=value ...] — fire-and-forget, never fails.
  729. _telemetry_ping() {
  730. _telemetry_enabled || return 0
  731. local event="$1" id os py body kv k v props api_key_safe event_safe id_safe
  732. shift
  733. id=$(_telemetry_distinct_id) || return 0
  734. os=$(uname -s | tr '[:upper:]' '[:lower:]')
  735. [[ "$os" =~ ^[A-Za-z0-9._-]{1,32}$ ]] || os="unknown"
  736. py=$(command -v python3 2>/dev/null || true)
  737. body=""
  738. if [ -n "$py" ]; then
  739. # Structural encoding: every value is JSON-escaped by python3's real
  740. # encoder and passed in via argv -- never interpolated into the -c code
  741. # string itself -- so a hostile value (embedded quotes, backslashes,
  742. # control characters, an attempted `","injected":"...` payload) can
  743. # only ever become the STRING CONTENTS of its own declared property; it
  744. # can never alter the payload's structure or add an undeclared key.
  745. # Keys are call-site literals already, but are still whitelisted to
  746. # `[A-Za-z0-9_]+` defensively -- a key that fails that check is
  747. # dropped, never stringified into a place it could do damage.
  748. body=$("$py" -c '
  749. import json, re, sys
  750. key_re = re.compile(r"^[A-Za-z0-9_]+$")
  751. event, distinct_id, api_key, os_name = sys.argv[1:5]
  752. props = {"os": os_name}
  753. for kv in sys.argv[5:]:
  754. key, sep, value = kv.partition("=")
  755. if sep and key_re.match(key):
  756. props[key] = value
  757. print(json.dumps(
  758. {
  759. "api_key": api_key,
  760. "event": event,
  761. "distinct_id": distinct_id,
  762. "properties": props,
  763. },
  764. separators=(",", ":"),
  765. ))
  766. ' "$event" "$id" "$PH_API_KEY" "$os" "$@" 2>/dev/null)
  767. fi
  768. if [ -z "$body" ]; then
  769. # No python3 (or the structural encoder failed): sanitize every value
  770. # through a strict safe-token filter before string concatenation, so no
  771. # quote/backslash/control character can ever survive to mutate the JSON
  772. # structure. Every legitimate installer value (version numbers,
  773. # method/runtime names, yes/no flags, a canonical-lowercase distinct_id,
  774. # the os/arch tokens above) fits this charset losslessly; anything that
  775. # doesn't is stripped down to it (then length-capped) or falls back to
  776. # `unknown` -- best-effort, consistent with the identity/notice
  777. # readers' own NO_PYTHON3 fallback posture elsewhere in this file.
  778. props='"os":"'"$os"'"'
  779. for kv in "$@"; do
  780. k=$(printf '%s' "${kv%%=*}" | tr -cd 'A-Za-z0-9_')
  781. [ -n "$k" ] || continue
  782. v=$(printf '%s' "${kv#*=}" | tr -cd 'A-Za-z0-9._-')
  783. v="${v:0:64}"
  784. [ -n "$v" ] || v="unknown"
  785. props="$props,\"$k\":\"$v\""
  786. done
  787. api_key_safe=$(printf '%s' "$PH_API_KEY" | tr -cd 'A-Za-z0-9._-')
  788. event_safe=$(printf '%s' "$event" | tr -cd 'A-Za-z0-9._-')
  789. id_safe=$(printf '%s' "$id" | tr -cd 'A-Za-z0-9._-')
  790. body='{"api_key":"'"$api_key_safe"'","event":"'"$event_safe"'","distinct_id":"'"$id_safe"'","properties":{'"$props"'}}'
  791. fi
  792. curl -fsS -m 4 -X POST "$PH_HOST/capture/" -H 'Content-Type: application/json' \
  793. -d "$body" \
  794. >/dev/null 2>&1 &
  795. return 0
  796. }
  797. # ---------------------------------------------------------------------------
  798. # Parse simple flags: --reconfigure, --runtime <name>, --no-console
  799. while [ $# -gt 0 ]; do
  800. case "$1" in
  801. --reconfigure)
  802. RECONFIGURE="1"
  803. shift
  804. ;;
  805. --no-console)
  806. NO_CONSOLE_FLAG="1"
  807. shift
  808. ;;
  809. --runtime)
  810. EXPLICIT_RUNTIME="${2:-}"
  811. shift 2
  812. ;;
  813. --runtime=*)
  814. EXPLICIT_RUNTIME="${1#--runtime=}"
  815. shift
  816. ;;
  817. *)
  818. shift
  819. ;;
  820. esac
  821. done
  822. # Override PACKAGE_NAME if running inside the repository clone
  823. if [ -f "pyproject.toml" ] && grep -q "name = \"ouroboros-ai\"" pyproject.toml; then
  824. PACKAGE_NAME="."
  825. IS_LOCAL=true
  826. elif [ -f "$(dirname "$0")/../pyproject.toml" ] && grep -q "name = \"ouroboros-ai\"" "$(dirname "$0")/../pyproject.toml"; then
  827. PACKAGE_NAME="$(dirname "$0")/.."
  828. IS_LOCAL=true
  829. fi
  830. # Auto-detect: if PyPI's info.version response is a pre-release, allow
  831. # pre-releases. On lookup/parsing failure, stay stable-only.
  832. PRE_FLAG=""
  833. if [ "$IS_LOCAL" = false ] && command -v curl &>/dev/null; then
  834. LATEST=$(curl -fsSL "https://pypi.org/pypi/${PACKAGE_NAME}/json" 2>/dev/null \
  835. | python3 -c "import sys,json; print(json.load(sys.stdin)['info']['version'])" 2>/dev/null || true)
  836. if [ -n "$LATEST" ]; then
  837. if echo "$LATEST" | grep -qE '(a|b|rc|dev)'; then
  838. PRE_FLAG="yes"
  839. fi
  840. fi
  841. fi
  842. # Closed install-channel vocabulary. Unknown values may contain private slugs,
  843. # customer names, or account identifiers, so they always fold to `direct`.
  844. case "${OUROBOROS_INSTALL_REF:-direct}" in
  845. direct|readme|readme-hero|readme-ko|readme-hero-ko|readme-zh|readme-hero-zh|docs-getting-started)
  846. INSTALL_REF="${OUROBOROS_INSTALL_REF:-direct}"
  847. ;;
  848. *) INSTALL_REF="direct" ;;
  849. esac
  850. _banner
  851. _telemetry_notice
  852. # Installs are rare, so install_started needs no daily dedupe: paired with
  853. # install_completed it measures install drop-off by version and ref.
  854. _telemetry_ping install_started "version=${LATEST:-unknown}" "ref=$INSTALL_REF"
  855. # 1. Detect installer: uv > pipx > pip (determines Python requirement)
  856. HAS_UV=false
  857. HAS_PIPX=false
  858. PYTHON=""
  859. _step "1/4 Checking Python tooling" "Prefer uv, then pipx, then pip. uv is installed when none of them can run."
  860. if command -v uv &>/dev/null; then
  861. HAS_UV=true
  862. _ok "uv found: $(uv --version)"
  863. elif command -v pipx &>/dev/null; then
  864. HAS_PIPX=true
  865. _ok "pipx found: $(pipx --version)"
  866. fi
  867. # Helper: check whether a Python executable meets the selected profile's range.
  868. _python_ok() {
  869. local cmd="$1"
  870. local spec="${2:-$DEFAULT_PYTHON_SPEC}"
  871. local ver
  872. ver=$("$cmd" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || true)
  873. if [ -z "$ver" ]; then
  874. return 1
  875. fi
  876. if [ "$(printf '%s\n' "$MIN_PYTHON" "$ver" | sort -V | head -n1)" != "$MIN_PYTHON" ]; then
  877. return 1
  878. fi
  879. if [ "$spec" = "$LITELLM_PYTHON_SPEC" ] && [ "$(printf '%s\n' "3.14" "$ver" | sort -V | head -n1)" = "3.14" ]; then
  880. return 1
  881. fi
  882. return 0
  883. }
  884. _python_requirement_message() {
  885. if [ "${INSTALL_PYTHON_SPEC:-$DEFAULT_PYTHON_SPEC}" = "$LITELLM_PYTHON_SPEC" ]; then
  886. printf 'Python %s (Ouroboros LiteLLM profiles support Python 3.12-3.13; use Python 3.13)' "$LITELLM_PYTHON_SPEC"
  887. else
  888. printf 'Python %s' "$DEFAULT_PYTHON_SPEC"
  889. fi
  890. }
  891. _bootstrap_uv() {
  892. # uv carries its own Python, so installing uv is the single move that unblocks
  893. # a machine with no usable interpreter — the case that previously just exited.
  894. # install.ps1 does the same on Windows (winget, then this script as fallback);
  895. # here the script is the only path needing no package manager and no
  896. # privileges. Everything that already works — an existing uv, or pipx with a
  897. # supported Python — reaches its installer before this is ever called.
  898. if [ "$BOOTSTRAP_UV" = "0" ]; then
  899. # Fetching and running an installer from the network is the one thing here
  900. # a caller may reasonably refuse; declining returns to the instructions.
  901. return 1
  902. fi
  903. if ! command -v curl >/dev/null 2>&1; then
  904. _err "curl is required to install uv automatically."
  905. return 1
  906. fi
  907. _blank
  908. _say "${BOLD}Installing uv${RESET} — it provides its own Python, so none needs to be installed separately."
  909. _info "Source: https://astral.sh/uv/install.sh"
  910. if ! curl -LsSf https://astral.sh/uv/install.sh | sh; then
  911. _err "uv installation failed."
  912. return 1
  913. fi
  914. # The installer does not touch the running shell's PATH, so look where it
  915. # actually writes before deciding it failed.
  916. local candidate
  917. for candidate in "${XDG_BIN_HOME:-}" "${CARGO_HOME:-$HOME/.cargo}/bin" "$HOME/.local/bin"; do
  918. if [ -n "$candidate" ] && [ -x "$candidate/uv" ]; then
  919. PATH="$candidate:$PATH"
  920. export PATH
  921. break
  922. fi
  923. done
  924. if ! command -v uv >/dev/null 2>&1; then
  925. _err "uv was installed but is not on PATH yet."
  926. _info "Open a new shell and run this installer again."
  927. return 1
  928. fi
  929. _ok "uv installed: $(uv --version)"
  930. return 0
  931. }
  932. _print_python_install_remediation() {
  933. _say "${BOLD}Install one of these, then run the installer again:${RESET}"
  934. _info "uv: pipx install uv"
  935. _info "uv: pip install --user uv"
  936. _info "uv: brew install uv"
  937. _info "uv: curl -LsSf https://astral.sh/uv/install.sh | sh"
  938. if [ "${INSTALL_PYTHON_SPEC:-$DEFAULT_PYTHON_SPEC}" = "$LITELLM_PYTHON_SPEC" ]; then
  939. _info "Python 3.13: https://www.python.org/downloads/"
  940. else
  941. _info "Python ${MIN_PYTHON}+: https://www.python.org/downloads/"
  942. fi
  943. }
  944. # 2. Detect runtimes
  945. _step "2/4 Choosing an agent backend" "Codex, Claude, Hermes, OpenCode, Gemini, Goose, Kiro, Copilot, Pi, GJC, and OMP are supported."
  946. EXTRAS=""
  947. RUNTIME=""
  948. HAS_CODEX=false
  949. HAS_CLAUDE=false
  950. HAS_HERMES=false
  951. HAS_OPENCODE=false
  952. HAS_GEMINI=false
  953. HAS_GOOSE=false
  954. HAS_KIRO=false
  955. HAS_COPILOT=false
  956. HAS_PI=false
  957. HAS_OMP=false
  958. HAS_GJC=false
  959. HAS_DSH=false
  960. DSH_PLUGIN_SPEC="github:Q00/ouroboros#main&path:integrations/dsh-plugin"
  961. if command -v codex &>/dev/null; then
  962. _ok "Codex found: $(which codex)"
  963. HAS_CODEX=true
  964. fi
  965. if command -v claude &>/dev/null; then
  966. _ok "Claude found: $(which claude)"
  967. HAS_CLAUDE=true
  968. fi
  969. if command -v hermes &>/dev/null; then
  970. _ok "Hermes found: $(which hermes)"
  971. HAS_HERMES=true
  972. fi
  973. if command -v opencode &>/dev/null; then
  974. _ok "OpenCode found: $(which opencode)"
  975. HAS_OPENCODE=true
  976. fi
  977. if command -v gemini &>/dev/null; then
  978. _ok "Gemini found: $(which gemini)"
  979. HAS_GEMINI=true
  980. fi
  981. if command -v goose &>/dev/null; then
  982. _ok "Goose found: $(which goose)"
  983. HAS_GOOSE=true
  984. fi
  985. if command -v kiro-cli &>/dev/null; then
  986. _ok "Kiro found: $(which kiro-cli)"
  987. HAS_KIRO=true
  988. fi
  989. if command -v copilot &>/dev/null; then
  990. _ok "Copilot found: $(which copilot)"
  991. HAS_COPILOT=true
  992. fi
  993. if command -v pi &>/dev/null; then
  994. _ok "Pi: $(which pi)"
  995. HAS_PI=true
  996. fi
  997. if command -v gjc &>/dev/null; then
  998. _ok "GJC found: $(which gjc)"
  999. HAS_GJC=true
  1000. fi
  1001. if command -v omp &>/dev/null; then
  1002. _ok "OMP found: $(which omp)"
  1003. HAS_OMP=true
  1004. fi
  1005. if command -v dsh &>/dev/null; then
  1006. _ok "DeepSeek Harness found: $(which dsh)"
  1007. HAS_DSH=true
  1008. fi
  1009. RUNTIME_COUNT=0
  1010. [ "$HAS_CLAUDE" = true ] && RUNTIME_COUNT=$((RUNTIME_COUNT + 1))
  1011. [ "$HAS_CODEX" = true ] && RUNTIME_COUNT=$((RUNTIME_COUNT + 1))
  1012. [ "$HAS_HERMES" = true ] && RUNTIME_COUNT=$((RUNTIME_COUNT + 1))
  1013. [ "$HAS_OPENCODE" = true ] && RUNTIME_COUNT=$((RUNTIME_COUNT + 1))
  1014. [ "$HAS_GEMINI" = true ] && RUNTIME_COUNT=$((RUNTIME_COUNT + 1))
  1015. [ "$HAS_GOOSE" = true ] && RUNTIME_COUNT=$((RUNTIME_COUNT + 1))
  1016. [ "$HAS_KIRO" = true ] && RUNTIME_COUNT=$((RUNTIME_COUNT + 1))
  1017. [ "$HAS_COPILOT" = true ] && RUNTIME_COUNT=$((RUNTIME_COUNT + 1))
  1018. [ "$HAS_PI" = true ] && RUNTIME_COUNT=$((RUNTIME_COUNT + 1))
  1019. [ "$HAS_GJC" = true ] && RUNTIME_COUNT=$((RUNTIME_COUNT + 1))
  1020. [ "$HAS_OMP" = true ] && RUNTIME_COUNT=$((RUNTIME_COUNT + 1))
  1021. # Map a runtime name to (EXTRAS, RUNTIME) pair.
  1022. # Used after explicit/preserved runtime resolution to derive install extras.
  1023. # Keep this table boring and explicit: agents reading this installer should be
  1024. # able to see why Claude's SDK runtime and the modern MCP server are installed
  1025. # in different environments. Only the explicit Claude CLI path has no SDK deps.
  1026. _runtime_to_extras() {
  1027. # `tui` ships with every selection so the settings GUI
  1028. # (`ouroboros config`) works out of the box (#1414).
  1029. case "$1" in
  1030. claude) EXTRAS="[claude,tui]"; RUNTIME="claude" ;;
  1031. claude-sdk) EXTRAS="[claude-sdk,tui]"; RUNTIME="claude-sdk" ;;
  1032. claude-cli) EXTRAS="[mcp,tui]"; RUNTIME="claude-cli" ;;
  1033. codex) EXTRAS="[mcp,tui]"; RUNTIME="codex" ;;
  1034. opencode) EXTRAS="[mcp,tui]"; RUNTIME="opencode" ;;
  1035. hermes) EXTRAS="[mcp,tui]"; RUNTIME="hermes" ;;
  1036. gemini) EXTRAS="[mcp,tui]"; RUNTIME="gemini" ;;
  1037. goose) EXTRAS="[mcp,tui]"; RUNTIME="goose" ;;
  1038. kiro) EXTRAS="[mcp,tui]"; RUNTIME="kiro" ;;
  1039. copilot) EXTRAS="[mcp,tui]"; RUNTIME="copilot" ;;
  1040. pi) EXTRAS="[mcp,tui]"; RUNTIME="pi" ;;
  1041. gjc) EXTRAS="[mcp,tui]"; RUNTIME="gjc" ;;
  1042. omp) EXTRAS="[mcp,tui]"; RUNTIME="omp" ;;
  1043. all) EXTRAS="[all]"; RUNTIME="" ;;
  1044. "") EXTRAS="[mcp,tui]"; RUNTIME="" ;;
  1045. *)
  1046. _err "unsupported runtime '$1'"
  1047. _info "Expected one of: claude, claude-sdk, claude-cli, codex, opencode, hermes, gemini, goose, kiro, copilot, pi, gjc, omp, all"
  1048. exit 1
  1049. ;;
  1050. esac
  1051. }
  1052. # Try to read the previously-configured runtime from ~/.ouroboros/config.yaml.
  1053. # Preserves user choice across upgrades unless --reconfigure / --runtime is set.
  1054. EXISTING_RUNTIME=""
  1055. EXISTING_CONFIG="$HOME/.ouroboros/config.yaml"
  1056. if [ -z "$EXPLICIT_RUNTIME" ] && [ -z "$RECONFIGURE" ] && [ -f "$EXISTING_CONFIG" ] && command -v python3 &>/dev/null; then
  1057. EXISTING_RUNTIME=$(EXISTING_CONFIG="$EXISTING_CONFIG" python3 -c "
  1058. import os, re
  1059. supported = {'claude', 'claude_mcp', 'codex', 'opencode', 'hermes', 'gemini', 'goose', 'kiro', 'copilot', 'pi', 'gjc', 'omp'}
  1060. try:
  1061. lines = open(os.environ['EXISTING_CONFIG']).read().splitlines()
  1062. in_orchestrator = False
  1063. for line in lines:
  1064. if re.match(r'^orchestrator:\s*(?:#.*)?$', line):
  1065. in_orchestrator = True
  1066. continue
  1067. if in_orchestrator and line and not line[0].isspace():
  1068. break
  1069. if in_orchestrator:
  1070. match = re.match(r'\s+runtime_backend:\s*[\"\']?([^\"\'\s#]+)', line)
  1071. if match and match.group(1) in supported:
  1072. # Preserve the transport identity on unattended upgrades:
  1073. # claude is the SDK/MCP 1 profile; claude_mcp is the
  1074. # explicit dependency-free CLI/MCP 2 worker profile.
  1075. print('claude-cli' if match.group(1) == 'claude_mcp' else match.group(1))
  1076. break
  1077. except Exception:
  1078. pass
  1079. " 2>/dev/null || true)
  1080. fi
  1081. if [ -n "$EXPLICIT_RUNTIME" ]; then
  1082. _blank
  1083. _ok "Runtime: $EXPLICIT_RUNTIME (from --runtime / OUROBOROS_INSTALL_RUNTIME)"
  1084. _runtime_to_extras "$EXPLICIT_RUNTIME"
  1085. elif [ -n "$EXISTING_RUNTIME" ]; then
  1086. _blank
  1087. _ok "Runtime: $EXISTING_RUNTIME (preserved from $EXISTING_CONFIG)"
  1088. _info "Re-run with --reconfigure to choose again."
  1089. _runtime_to_extras "$EXISTING_RUNTIME"
  1090. elif [ "$RUNTIME_COUNT" -gt 1 ]; then
  1091. if [ -t 0 ]; then
  1092. _blank
  1093. _say "${BOLD}Multiple runtimes detected. Pick where Ouroboros should appear first:${RESET}"
  1094. _choice 1 "Claude SDK" "MCP 1.x Agent SDK profile (${PACKAGE_NAME}[claude,tui]); choose Claude CLI for MCP 2"
  1095. _choice 2 "Codex" "Codex plugin artifacts + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1096. _choice 3 "Hermes" "Hermes agent guides + MCP 2 server (${PACKAGE_NAME}[mcp,tui])"
  1097. _choice 4 "OpenCode" "OpenCode commands + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1098. _choice 5 "Gemini" "Gemini CLI integration + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1099. _choice 6 "Goose" "Goose CLI integration + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1100. _choice 7 "Kiro" "Kiro CLI integration + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1101. _choice 8 "Copilot" "GitHub Copilot integration + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1102. _choice 9 "Pi" "Pi CLI bridge + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1103. _choice 10 "GJC" "GJC CLI bridge + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1104. _choice 11 "OMP" "Oh My Pi (omp) CLI bridge + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1105. _choice 12 "All" "Install every optional integration (${PACKAGE_NAME}[all])"
  1106. _prompt "Select [1]: "
  1107. read -r choice
  1108. case "${choice:-1}" in
  1109. 2) _runtime_to_extras "codex" ;;
  1110. 3) _runtime_to_extras "hermes" ;;
  1111. 4) _runtime_to_extras "opencode" ;;
  1112. 5) _runtime_to_extras "gemini" ;;
  1113. 6) _runtime_to_extras "goose" ;;
  1114. 7) _runtime_to_extras "kiro" ;;
  1115. 8) _runtime_to_extras "copilot" ;;
  1116. 9) _runtime_to_extras "pi" ;;
  1117. 10) _runtime_to_extras "gjc" ;;
  1118. 11) _runtime_to_extras "omp" ;;
  1119. 12) _runtime_to_extras "all" ;;
  1120. *) _runtime_to_extras "claude" ;;
  1121. esac
  1122. else
  1123. # Pipe mode: default to claude when multiple runtimes exist
  1124. _warn "Multiple runtimes detected in non-interactive mode; defaulting to Claude."
  1125. _runtime_to_extras "claude"
  1126. fi
  1127. elif [ "$HAS_CLAUDE" = true ] && [ "$RUNTIME_COUNT" -eq 1 ]; then
  1128. _runtime_to_extras "claude"
  1129. elif [ "$HAS_CODEX" = true ] && [ "$RUNTIME_COUNT" -eq 1 ]; then
  1130. _runtime_to_extras "codex"
  1131. elif [ "$HAS_HERMES" = true ] && [ "$RUNTIME_COUNT" -eq 1 ]; then
  1132. _runtime_to_extras "hermes"
  1133. elif [ "$HAS_OPENCODE" = true ] && [ "$RUNTIME_COUNT" -eq 1 ]; then
  1134. _runtime_to_extras "opencode"
  1135. elif [ "$HAS_GEMINI" = true ] && [ "$RUNTIME_COUNT" -eq 1 ]; then
  1136. _runtime_to_extras "gemini"
  1137. elif [ "$HAS_GOOSE" = true ] && [ "$RUNTIME_COUNT" -eq 1 ]; then
  1138. _runtime_to_extras "goose"
  1139. elif [ "$HAS_KIRO" = true ] && [ "$RUNTIME_COUNT" -eq 1 ]; then
  1140. _runtime_to_extras "kiro"
  1141. elif [ "$HAS_COPILOT" = true ] && [ "$RUNTIME_COUNT" -eq 1 ]; then
  1142. _runtime_to_extras "copilot"
  1143. elif [ "$HAS_PI" = true ] && [ "$RUNTIME_COUNT" -eq 1 ]; then
  1144. _runtime_to_extras "pi"
  1145. elif [ "$HAS_GJC" = true ] && [ "$RUNTIME_COUNT" -eq 1 ]; then
  1146. _runtime_to_extras "gjc"
  1147. elif [ "$HAS_OMP" = true ] && [ "$RUNTIME_COUNT" -eq 1 ]; then
  1148. _runtime_to_extras "omp"
  1149. else
  1150. # No runtime CLI on PATH yet — first install. Always prompt when interactive
  1151. # so the user picks deliberately rather than silently defaulting to claude.
  1152. if [ -t 0 ]; then
  1153. _blank
  1154. _say "${BOLD}No runtime CLI detected yet. Choose the agent you plan to use:${RESET}"
  1155. _choice 1 "Claude SDK" "MCP 1.x Agent SDK profile (${PACKAGE_NAME}[claude,tui]); choose Claude CLI for MCP 2"
  1156. _choice 2 "Codex" "Codex plugin artifacts + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1157. _choice 3 "Hermes" "Hermes agent guides + MCP 2 server (${PACKAGE_NAME}[mcp,tui])"
  1158. _choice 4 "OpenCode" "OpenCode commands + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1159. _choice 5 "Gemini" "Gemini CLI integration + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1160. _choice 6 "Goose" "Goose CLI integration + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1161. _choice 7 "Kiro" "Kiro CLI integration + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1162. _choice 8 "Copilot" "GitHub Copilot integration + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1163. _choice 9 "Pi" "Pi CLI bridge + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1164. _choice 10 "GJC" "GJC CLI bridge + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1165. _choice 11 "OMP" "Oh My Pi (omp) CLI bridge + MCP 2 (${PACKAGE_NAME}[mcp,tui])"
  1166. _choice 12 "All" "Install every optional integration (${PACKAGE_NAME}[all])"
  1167. _choice 0 "MCP 2 default" "Install MCP 2 + settings GUI; choose a compatible backend later"
  1168. _prompt "Select [1]: "
  1169. read -r choice
  1170. case "${choice:-1}" in
  1171. 0) _runtime_to_extras "" ;;
  1172. 2) _runtime_to_extras "codex" ;;
  1173. 3) _runtime_to_extras "hermes" ;;
  1174. 4) _runtime_to_extras "opencode" ;;
  1175. 5) _runtime_to_extras "gemini" ;;
  1176. 6) _runtime_to_extras "goose" ;;
  1177. 7) _runtime_to_extras "kiro" ;;
  1178. 8) _runtime_to_extras "copilot" ;;
  1179. 9) _runtime_to_extras "pi" ;;
  1180. 10) _runtime_to_extras "gjc" ;;
  1181. 11) _runtime_to_extras "omp" ;;
  1182. 12) _runtime_to_extras "all" ;;
  1183. *) _runtime_to_extras "claude" ;;
  1184. esac
  1185. else
  1186. # Pipe mode (curl | bash): install the MCP v2 + settings GUI default profile.
  1187. _blank
  1188. _warn "No runtime detected in non-interactive mode; installing MCP v2 + settings GUI."
  1189. _info "Pick an MCP v2-compatible backend afterwards with: ouroboros setup --runtime <claude-cli|codex|opencode|hermes|gemini|goose|kiro|copilot|pi|gjc|omp>"
  1190. _runtime_to_extras ""
  1191. fi
  1192. fi
  1193. if [ -n "$RUNTIME" ]; then
  1194. _ok "Selected backend: $RUNTIME"
  1195. elif [ "$EXTRAS" = "[all]" ]; then
  1196. _ok "Selected backend: all"
  1197. else
  1198. _info "Selected backend: none yet"
  1199. fi
  1200. INSTALL_SPEC="${PACKAGE_NAME}${EXTRAS}"
  1201. INSTALL_PYTHON_SPEC="$DEFAULT_PYTHON_SPEC"
  1202. case "$EXTRAS" in
  1203. "[all]" | "[litellm]" | *litellm*)
  1204. INSTALL_PYTHON_SPEC="$LITELLM_PYTHON_SPEC"
  1205. ;;
  1206. esac
  1207. # Python check: always required for pip; also needed by pipx to pick the right interpreter.
  1208. if [ "$HAS_UV" = false ]; then
  1209. if [ "$HAS_PIPX" = true ]; then
  1210. # For pipx: probe versioned candidates first, then fall back to generic names.
  1211. for cmd in python3.14 python3.13 python3.12 python3 python; do
  1212. if command -v "$cmd" &>/dev/null && _python_ok "$cmd" "$INSTALL_PYTHON_SPEC"; then
  1213. PYTHON="$(command -v "$cmd")"
  1214. break
  1215. fi
  1216. done
  1217. if [ -z "$PYTHON" ]; then
  1218. _blank
  1219. _warn "pipx requires $(_python_requirement_message), but none was found."
  1220. if _bootstrap_uv; then
  1221. HAS_UV=true
  1222. HAS_PIPX=false
  1223. else
  1224. _blank
  1225. _err "pipx requires $(_python_requirement_message), but none was found."
  1226. _blank
  1227. _print_python_install_remediation
  1228. exit 1
  1229. fi
  1230. fi
  1231. if [ "$HAS_UV" = false ]; then
  1232. _ok "Python found: $($PYTHON --version)"
  1233. fi
  1234. else
  1235. # pip fallback: prefer explicit compatible versions for constrained profiles.
  1236. if [ "$INSTALL_PYTHON_SPEC" = "$LITELLM_PYTHON_SPEC" ]; then
  1237. PYTHON_CANDIDATES="python3.13 python3.12 python3 python"
  1238. else
  1239. PYTHON_CANDIDATES="python3 python"
  1240. fi
  1241. for cmd in $PYTHON_CANDIDATES; do
  1242. if command -v "$cmd" &>/dev/null && _python_ok "$cmd" "$INSTALL_PYTHON_SPEC"; then
  1243. PYTHON="$cmd"
  1244. break
  1245. fi
  1246. done
  1247. if [ -z "$PYTHON" ]; then
  1248. _blank
  1249. _warn "No installer found: uv, pipx, or $(_python_requirement_message)."
  1250. if _bootstrap_uv; then
  1251. HAS_UV=true
  1252. else
  1253. _blank
  1254. _err "No installer found: uv, pipx, or $(_python_requirement_message)."
  1255. _blank
  1256. _print_python_install_remediation
  1257. exit 1
  1258. fi
  1259. fi
  1260. if [ "$HAS_UV" = false ]; then
  1261. _ok "Python found: $($PYTHON --version)"
  1262. fi
  1263. fi
  1264. fi
  1265. _step "3/4 Installing Ouroboros" "Package: ${INSTALL_SPEC}"
  1266. _say "Installing ${INSTALL_SPEC} ..."
  1267. # 3. Install (or upgrade if already installed).
  1268. # Resolve optional dependencies from the selected distribution, not this
  1269. # installer's checkout: PyPI may still serve an older compatible release.
  1270. INSTALL_METHOD=""
  1271. if [ "$HAS_UV" = true ]; then
  1272. INSTALL_METHOD="uv"
  1273. _info "Install method: uv tool install"
  1274. # Keep the bounded Click repair for older wheels that omitted its metadata.
  1275. # The target's extras own SDK/MCP/TUI pins and Python/platform markers.
  1276. UV_ARGS=(tool install --upgrade --python "$INSTALL_PYTHON_SPEC" "$INSTALL_SPEC" --with "$CLICK_SPEC")
  1277. if [ -n "$PRE_FLAG" ]; then
  1278. UV_ARGS+=(--prerelease=allow)
  1279. fi
  1280. uv "${UV_ARGS[@]}"
  1281. elif [ "$HAS_PIPX" = true ]; then
  1282. INSTALL_METHOD="pipx"
  1283. _info "Install method: pipx"
  1284. if [ -n "$PRE_FLAG" ]; then
  1285. pipx install --force --python "$PYTHON" --pip-args='--pre' "$INSTALL_SPEC"
  1286. else
  1287. pipx install --force --python "$PYTHON" "$INSTALL_SPEC"
  1288. fi
  1289. # The venv name is the distribution name even when installing from a local path.
  1290. pipx inject "ouroboros-ai" "$CLICK_SPEC"
  1291. else
  1292. INSTALL_METHOD="pip"
  1293. _info "Install method: pip --user"
  1294. if [ -n "$PRE_FLAG" ]; then
  1295. $PYTHON -m pip install --user --upgrade --pre "$INSTALL_SPEC" "$CLICK_SPEC"
  1296. else
  1297. $PYTHON -m pip install --user --upgrade "$INSTALL_SPEC" "$CLICK_SPEC"
  1298. fi
  1299. fi
  1300. # Ensure setup runs the freshly-installed uv tool binary rather than a stale
  1301. # command already on PATH. uv can install into UV_TOOL_BIN_DIR or its configured
  1302. # tool bin directory without updating the current shell's PATH, so remember the
  1303. # fresh executable and invoke that exact path below. For pipx/pip installs,
  1304. # preserve the existing PATH command unless no ouroboros command is visible.
  1305. OUROBOROS_BIN=""
  1306. _prepend_path_if_ouroboros() {
  1307. local candidate="$1"
  1308. if [ -n "$candidate" ] && [ -x "$candidate/ouroboros" ]; then
  1309. export PATH="$candidate:$PATH"
  1310. if [ -z "$OUROBOROS_BIN" ]; then
  1311. OUROBOROS_BIN="$candidate/ouroboros"
  1312. fi
  1313. return 0
  1314. fi
  1315. return 1
  1316. }
  1317. if [ "$INSTALL_METHOD" = "uv" ]; then
  1318. _prepend_path_if_ouroboros "${UV_TOOL_BIN_DIR:-}" || true
  1319. if command -v uv &>/dev/null; then
  1320. UV_TOOL_BIN="$(uv tool dir --bin 2>/dev/null || true)"
  1321. _prepend_path_if_ouroboros "$UV_TOOL_BIN" || true
  1322. fi
  1323. fi
  1324. if [ -z "$OUROBOROS_BIN" ] && ! command -v ouroboros &>/dev/null; then
  1325. for p in "$HOME/.local/bin" "$HOME/.cargo/bin" "$HOME/bin"; do
  1326. _prepend_path_if_ouroboros "$p" || true
  1327. done
  1328. fi
  1329. OUROBOROS_SETUP_CMD=""
  1330. if [ -n "$OUROBOROS_BIN" ]; then
  1331. OUROBOROS_SETUP_CMD="$OUROBOROS_BIN"
  1332. elif command -v ouroboros &>/dev/null; then
  1333. OUROBOROS_SETUP_CMD="ouroboros"
  1334. fi
  1335. # 4. Setup (ouroboros CLI configures runtime-specific integration)
  1336. _step "4/4 Wiring local integrations" "Creates config and runtime-specific files when a backend was selected."
  1337. if [ -n "$RUNTIME" ] && [ -n "$OUROBOROS_SETUP_CMD" ]; then
  1338. _info "Running: $OUROBOROS_SETUP_CMD setup --runtime $RUNTIME --non-interactive"
  1339. if "$OUROBOROS_SETUP_CMD" setup --runtime "$RUNTIME" --non-interactive; then
  1340. :
  1341. else
  1342. setup_status=$?
  1343. _warn "Runtime setup failed; installation is incomplete. Fix the error above and re-run setup."
  1344. exit "$setup_status"
  1345. fi
  1346. elif [ -n "$RUNTIME" ]; then
  1347. _warn "ouroboros command is not on PATH yet; run setup after your shell sees the installed binary."
  1348. else
  1349. _info "No backend selected; skipping runtime setup."
  1350. fi
  1351. # Refresh already-installed artifacts for every detected runtime, even those
  1352. # that are not the preserved primary backend. Setup only wires the selected
  1353. # runtime, so upgrades must not leave other runtimes' rules/skills/bridges
  1354. # stale. `setup refresh` is presence-gated per artifact and never touches MCP
  1355. # registrations or config.
  1356. if [ -n "$OUROBOROS_SETUP_CMD" ]; then
  1357. _info "Refreshing runtime artifacts for detected runtimes"
  1358. "$OUROBOROS_SETUP_CMD" setup refresh || _warn "Artifact refresh skipped; run: ouroboros setup refresh"
  1359. fi
  1360. _decimal_at_least() {
  1361. local left right
  1362. left="${1#${1%%[!0]*}}"
  1363. right="${2#${2%%[!0]*}}"
  1364. [ -n "$left" ] || left=0
  1365. [ -n "$right" ] || right=0
  1366. if [ "${#left}" -ne "${#right}" ]; then
  1367. [ "${#left}" -gt "${#right}" ]
  1368. else
  1369. [ "$left" = "$right" ] || [[ "$left" > "$right" ]]
  1370. fi
  1371. }
  1372. _ensure_omp_tool_call_timeout() {
  1373. local omp_bin current
  1374. omp_bin="$(command -v omp 2>/dev/null || true)"
  1375. if [ -z "$omp_bin" ]; then
  1376. return 0
  1377. fi
  1378. current="$("$omp_bin" config get extensionHandlers.toolCallTimeoutMs 2>/dev/null || true)"
  1379. case "$current" in
  1380. ''|*[!0-9]*) ;;
  1381. *)
  1382. if _decimal_at_least "$current" 60000; then
  1383. return 0
  1384. fi
  1385. ;;
  1386. esac
  1387. if "$omp_bin" config set extensionHandlers.toolCallTimeoutMs 60000 >/dev/null 2>&1; then
  1388. _ok "OMP MCP tool timeout set to 60s"
  1389. else
  1390. _warn "Could not set OMP MCP tool timeout; run: omp config set extensionHandlers.toolCallTimeoutMs 60000"
  1391. fi
  1392. }
  1393. _ensure_omp_tool_call_timeout
  1394. # 5. Claude Code integration. The default Claude selection and its explicit
  1395. # SDK alias stay on MCP 1.x. The plugin-owned MCP launcher starts MCP 2 in a
  1396. # separate uvx environment and selects the dependency-free CLI worker.
  1397. # Skill refresh is artifact-only and should happen whenever Claude is present;
  1398. # otherwise a Codex-primary upgrade can leave Claude Code reading stale skills.
  1399. if command -v claude &>/dev/null && { [ "$RUNTIME" = "claude" ] || [ "$RUNTIME" = "claude-sdk" ] || [ "$EXTRAS" = "[all]" ]; }; then
  1400. _blank
  1401. _say "${BLUE}◆${RESET} ${BOLD}Claude Code extras${RESET}"
  1402. _warn "Claude SDK is isolated on MCP 1.x. The Claude plugin launches the Ouroboros MCP 2 server in a separate uvx environment with --runtime claude-cli."
  1403. fi
  1404. if command -v claude &>/dev/null; then
  1405. if ! { [ "$RUNTIME" = "claude" ] || [ "$RUNTIME" = "claude-sdk" ] || [ "$EXTRAS" = "[all]" ]; }; then
  1406. _blank
  1407. _say "${BLUE}◆${RESET} ${BOLD}Claude Code skills${RESET}"
  1408. fi
  1409. # 5a. Install/update Ouroboros skills (claude plugin)
  1410. _info "Installing Ouroboros skills via Claude plugin marketplace..."
  1411. claude plugin marketplace add Q00/ouroboros 2>/dev/null || true
  1412. claude plugin marketplace update ouroboros 2>/dev/null || true
  1413. if claude plugin install ouroboros@ouroboros 2>/dev/null; then
  1414. # `install` is a no-op for an already-installed plugin — `update` moves it to the latest version
  1415. claude plugin update ouroboros@ouroboros >/dev/null 2>&1 || true
  1416. _ok "Skills installed"
  1417. else
  1418. _warn "Skills skipped. Manual install: claude plugin marketplace add Q00/ouroboros && claude plugin install ouroboros@ouroboros"
  1419. fi
  1420. fi
  1421. _telemetry_ping install_completed "runtime=${RUNTIME:-none}" \
  1422. "version=${LATEST:-unknown}" "ref=$INSTALL_REF"
  1423. _blank
  1424. _say "${GREEN}${BOLD}Done! Ouroboros is ready.${RESET}"
  1425. _blank
  1426. _say "${BOLD}Get started${RESET}"
  1427. _info 'Open your AI coding agent and run: > ooo interview "your idea here"'
  1428. _info 'Or from the terminal: ouroboros init start "your idea here"'
  1429. if [ -n "$RUNTIME" ]; then
  1430. _info "Current backend: $RUNTIME"
  1431. fi
  1432. _info "Switch backend later: ouroboros setup --runtime <claude|claude-sdk|claude-cli|codex|opencode|hermes|gemini|goose|kiro|copilot|pi|gjc|omp>"
  1433. _say "${BOLD}Model settings — use your default model or configure one directly${RESET}"
  1434. _info 'Inside your AI agent: > ooo config (opens in your browser)'
  1435. _info 'From this terminal: ouroboros config (full-screen TUI)'
  1436. # 6. Optional direct model settings (interactive installs only).
  1437. # install.sh always runs in a real terminal when interactive, so the
  1438. # full-screen Textual settings app can open right here. curl|bash pipe
  1439. # installs skip this automatically ([ -t 0 ] is false).
  1440. if [ -t 0 ] && [ -z "${OUROBOROS_INSTALL_SKIP_CONFIG_GUI:-}" ]; then
  1441. if [ "$RUNTIME" = "codex" ]; then
  1442. GUI_MESSAGE="Codex's current default model is ready to use. Configure a model directly now?"
  1443. else
  1444. GUI_MESSAGE="Your selected runtime's default model is ready to use. Configure a model directly now?"
  1445. fi
  1446. # Most people should start with the runtime default. The settings UI is for
  1447. # deliberate model pins, so it must remain an opt-in rather than a fresh
  1448. # install speed bump.
  1449. GUI_DEFAULT="n"
  1450. GUI_HINT="[y/N]"
  1451. _blank
  1452. _say "${BOLD}${GUI_MESSAGE}${RESET}"
  1453. _prompt "Open direct model settings $GUI_HINT: "
  1454. read -r gui_choice
  1455. case "${gui_choice:-$GUI_DEFAULT}" in
  1456. y | Y | yes | YES)
  1457. GUI_OK=false
  1458. if [ -n "${OUROBOROS_SETUP_CMD:-}" ] && "$OUROBOROS_SETUP_CMD" config; then
  1459. GUI_OK=true
  1460. elif command -v uvx &>/dev/null; then
  1461. # The selected extras may not include [tui]; run the GUI from an
  1462. # ephemeral env with the tui extra instead of fattening the install.
  1463. _info "Settings GUI needs the tui extra; running it via uvx..."
  1464. if uvx --python "$DEFAULT_PYTHON_SPEC" --from "${PACKAGE_NAME}[tui]" ouroboros config; then
  1465. GUI_OK=true
  1466. fi
  1467. fi
  1468. if [ "$GUI_OK" = false ]; then
  1469. _warn "Could not open the settings GUI."
  1470. _info "Run it later with: uvx --python '>=3.12' --from '${PACKAGE_NAME}[tui]' ouroboros config"
  1471. fi
  1472. ;;
  1473. *)
  1474. _info "Using the runtime default model. You can change it anytime:"
  1475. _info ' in your AI agent: > ooo config'
  1476. _info ' in a terminal: ouroboros config'
  1477. ;;
  1478. esac
  1479. fi
  1480. # 6. DeepSeek Harness integration. Unlike the other hosts, dsh keeps its plugins
  1481. # per profile, and `dsh plugin` requires --profile, so there is no single global
  1482. # install to run. Cover the profile a dsh user actually boots (`web`, which
  1483. # `dsh web` scaffolds) and refresh any other profile that already carries the
  1484. # bundle, which is how an existing install picks up a new release.
  1485. if [ "$HAS_DSH" = true ]; then
  1486. _blank
  1487. _say "${BLUE}◆${RESET} ${BOLD}DeepSeek Harness plugin${RESET}"
  1488. DSH_PROFILE_ROOT="${DSH_HOME:-$HOME/.dsh}/profiles"
  1489. DSH_TARGET_PROFILES=("web")
  1490. _dsh_json_python="${PYTHON:-}"
  1491. if [ -z "$_dsh_json_python" ]; then
  1492. _dsh_json_python=$(command -v python3 2>/dev/null || true)
  1493. fi
  1494. if [ -z "$_dsh_json_python" ]; then
  1495. _dsh_ouroboros_cmd=$(command -v ouroboros 2>/dev/null || true)
  1496. if [ -n "$_dsh_ouroboros_cmd" ] && [ -r "$_dsh_ouroboros_cmd" ]; then
  1497. _dsh_shebang=$(head -n 1 "$_dsh_ouroboros_cmd" 2>/dev/null || true)
  1498. case "$_dsh_shebang" in
  1499. '#!'/*)
  1500. _dsh_json_python=${_dsh_shebang#'#!'}
  1501. case "$_dsh_json_python" in
  1502. *' '*) _dsh_json_python="" ;;
  1503. esac
  1504. [ -x "$_dsh_json_python" ] || _dsh_json_python=""
  1505. ;;
  1506. esac
  1507. fi
  1508. fi
  1509. if [ -n "$_dsh_json_python" ] && [ -d "$DSH_PROFILE_ROOT" ]; then
  1510. for _dsh_profile_dir in "$DSH_PROFILE_ROOT"/*/; do
  1511. [ -d "$_dsh_profile_dir" ] || continue
  1512. _dsh_profile=${_dsh_profile_dir#"$DSH_PROFILE_ROOT"/}
  1513. _dsh_profile=${_dsh_profile%/}
  1514. [ "$_dsh_profile" = "web" ] && continue
  1515. # Only profiles that already opted in. Adding Ouroboros tools to an
  1516. # unrelated profile because the installer ran is not an upgrade.
  1517. if "$_dsh_json_python" -c 'import json, sys; data = json.load(open(sys.argv[1], encoding="utf-8")); dependencies = data.get("dependencies", {}) if isinstance(data, dict) else {}; sys.exit(0 if isinstance(dependencies, dict) and "dsh-ouroboros" in dependencies else 1)' "$_dsh_profile_dir/package.json" 2>/dev/null; then
  1518. DSH_TARGET_PROFILES+=("$_dsh_profile")
  1519. fi
  1520. done
  1521. fi
  1522. for _dsh_profile in "${DSH_TARGET_PROFILES[@]}"; do
  1523. _dsh_profile_q=$(_shell_quote "$_dsh_profile")
  1524. if dsh plugin --profile "$_dsh_profile" add "$DSH_PLUGIN_SPEC" >/dev/null 2>&1; then
  1525. _ok "dsh profile $_dsh_profile_q: Ouroboros tools installed"
  1526. else
  1527. _warn "dsh profile $_dsh_profile_q: install skipped"
  1528. _info "Manual install: dsh plugin --profile $_dsh_profile_q add \"$DSH_PLUGIN_SPEC\""
  1529. fi
  1530. done
  1531. _info "Type 'ooo interview <goal>' in a dsh chat to use them."
  1532. fi
  1533. _blank
  1534. _say "${BOLD}Like Ouroboros?${RESET}"
  1535. _info "Give the repo a star on GitHub: https://github.com/Q00/ouroboros"
  1536. # 7. Ouroboros console. Once the install is done, start the browser console so
  1537. # a new user lands in a guided UI. It runs detached: the installer returns the
  1538. # terminal, never waits on it beyond bounded checks, and never fails because of
  1539. # it. Releases without `ouroboros gui` get no console output at all.
  1540. # --no-console or OUROBOROS_NO_CONSOLE=1 skips this step. The variable takes a
  1541. # closed set of values; anything else is reported and treated as an opt-out,
  1542. # because not starting a background server is the safe reading.
  1543. _console_opted_out() {
  1544. local value
  1545. [ -z "$NO_CONSOLE_FLAG" ] || return 0
  1546. value=$(printf '%s' "${OUROBOROS_NO_CONSOLE:-}" | tr '[:upper:]' '[:lower:]')
  1547. value="${value#"${value%%[![:space:]]*}"}"
  1548. value="${value%"${value##*[![:space:]]}"}"
  1549. case "$value" in
  1550. '' | 0 | false | no | off) return 1 ;;
  1551. 1 | true | yes | on) return 0 ;;
  1552. *)
  1553. _warn "OUROBOROS_NO_CONSOLE has an unrecognized value (expected 1 or 0); not starting the console."
  1554. return 0
  1555. ;;
  1556. esac
  1557. }
  1558. # Stop a background child within a fixed bound: SIGTERM, up to 1 s to exit,
  1559. # then SIGKILL and up to 1 s more. Its status is collected only once it is
  1560. # gone, so this never blocks on a child that refuses to die.
  1561. _console_stop_child() {
  1562. local pid="$1" ticks=10
  1563. kill -TERM "$pid" 2>/dev/null || true
  1564. while [ "$ticks" -gt 0 ] && kill -0 "$pid" 2>/dev/null; do
  1565. ticks=$((ticks - 1))
  1566. sleep 0.1
  1567. done
  1568. if kill -0 "$pid" 2>/dev/null; then
  1569. kill -KILL "$pid" 2>/dev/null || true
  1570. ticks=10
  1571. while [ "$ticks" -gt 0 ] && kill -0 "$pid" 2>/dev/null; do
  1572. ticks=$((ticks - 1))
  1573. sleep 0.1
  1574. done
  1575. fi
  1576. if ! kill -0 "$pid" 2>/dev/null; then
  1577. wait "$pid" 2>/dev/null || true
  1578. fi
  1579. }
  1580. # Run a command with stdin closed and stderr discarded (stdout is the
  1581. # caller's), giving it <ticks> tenths of a second. On timeout it is stopped
  1582. # with _console_stop_child and the status is 124, so the whole call returns
  1583. # within its limit plus 2 s.
  1584. _console_run_bounded() {
  1585. local ticks="$1" pid
  1586. shift
  1587. "$@" </dev/null 2>/dev/null &
  1588. pid=$!
  1589. while kill -0 "$pid" 2>/dev/null; do
  1590. if [ "$ticks" -le 0 ]; then
  1591. _console_stop_child "$pid"
  1592. return 124
  1593. fi
  1594. ticks=$((ticks - 1))
  1595. sleep 0.1
  1596. done
  1597. wait "$pid"
  1598. }
  1599. # `ouroboros gui --help` exits 0 only on a release that ships the console;
  1600. # older ones fail with "No such command". Telemetry is off for the probe since
  1601. # it is not a real use.
  1602. _console_supported() {
  1603. _console_run_bounded "$2" env OUROBOROS_TELEMETRY=0 DO_NOT_TRACK=1 "$1" gui --help >/dev/null
  1604. }
  1605. # Under `curl | bash` stdin is the pipe carrying this script, so a terminal is
  1606. # reached through /dev/tty rather than fd 0.
  1607. _console_has_terminal() {
  1608. { : </dev/tty; } 2>/dev/null
  1609. }
  1610. _console_is_wsl() {
  1611. if [ -n "${WSL_DISTRO_NAME:-}" ] || [ -n "${WSL_INTEROP:-}" ]; then
  1612. return 0
  1613. fi
  1614. grep -qi microsoft /proc/sys/kernel/osrelease 2>/dev/null
  1615. }
  1616. # A browser can only be opened on this machine's screen: macOS, or Linux/WSL
  1617. # with an X11/Wayland display, or WSL with a bridge to the Windows browser
  1618. # (wslview, or BROWSER set). An SSH session without a display has none of these
  1619. # for the person at the other end; on macOS the browser would open on the
  1620. # remote Mac's screen even with X11 forwarding.
  1621. _console_has_desktop() {
  1622. local ssh=false
  1623. if [ -n "${SSH_CONNECTION:-}${SSH_CLIENT:-}${SSH_TTY:-}" ]; then
  1624. ssh=true
  1625. fi
  1626. if [ "$(uname -s 2>/dev/null || true)" = "Darwin" ]; then
  1627. [ "$ssh" = false ]
  1628. return
  1629. fi
  1630. if [ -n "${DISPLAY:-}" ] || [ -n "${WAYLAND_DISPLAY:-}" ]; then
  1631. return 0
  1632. fi
  1633. [ "$ssh" = false ] || return 1
  1634. _console_is_wsl || return 1
  1635. [ -n "${BROWSER:-}" ] || command -v wslview >/dev/null 2>&1
  1636. }
  1637. # A Python to parse the console's JSON state with: the interpreter `ouroboros`
  1638. # itself runs on (an absolute `#!/.../python*` shebang, as uv, pipx and pip
  1639. # entry points have), else python3 on PATH. Nothing but a python-named
  1640. # interpreter is ever run with the check, and a candidate counts only if it
  1641. # imports json in isolated mode within the bound. Prints nothing and fails when
  1642. # there is none.
  1643. _console_json_python() {
  1644. local cmd="$1" path shebang candidate
  1645. path=$(command -v "$cmd" 2>/dev/null || true)
  1646. if [ -n "$path" ] && [ -f "$path" ] && [ -r "$path" ]; then
  1647. shebang=$(head -n 1 "$path" 2>/dev/null || true)
  1648. case "$shebang" in
  1649. '#!'/*)
  1650. candidate=${shebang#'#!'}
  1651. case "$candidate" in
  1652. *[[:space:]]*) ;;
  1653. */python | */python3 | */python3.[0-9]*)
  1654. if [ -x "$candidate" ] && _console_run_bounded 50 "$candidate" -I -c 'import json' >/dev/null; then
  1655. printf '%s' "$candidate"
  1656. return 0
  1657. fi
  1658. ;;
  1659. esac
  1660. ;;
  1661. esac
  1662. fi
  1663. candidate=$(command -v python3 2>/dev/null || true)
  1664. if [ -n "$candidate" ] && _console_run_bounded 50 "$candidate" -I -c 'import json' >/dev/null; then
  1665. printf '%s' "$candidate"
  1666. return 0
  1667. fi
  1668. return 1
  1669. }
  1670. # Reads ~/.ouroboros/gui/server.json, written by `ouroboros gui` once it
  1671. # listens, as JSON: only a well-formed top-level object whose own `host` is a
  1672. # loopback name and whose own `port` is an integer in 1-65535 yields a URL.
  1673. _CONSOLE_STATE_PARSER='
  1674. import json, sys
  1675. try:
  1676. with open(sys.argv[1], encoding="utf-8") as fh:
  1677. state = json.load(fh)
  1678. except Exception:
  1679. sys.exit(1)
  1680. if not isinstance(state, dict):
  1681. sys.exit(1)
  1682. port = state.get("port")
  1683. if state.get("host") not in ("127.0.0.1", "localhost", "0.0.0.0"):
  1684. sys.exit(1)
  1685. if type(port) is not int or not 1 <= port <= 65535:
  1686. sys.exit(1)
  1687. print("http://localhost:%d/" % port)
  1688. '
  1689. # Print the console URL from <state file> using <python>; fail closed (print
  1690. # nothing) without a parser, for a file that is not a regular file, or for
  1691. # anything the parser rejects. Bounded like every other child here.
  1692. _console_state_url() {
  1693. local py="$1" state="$2"
  1694. [ -n "$py" ] || return 1
  1695. [ -f "$state" ] || return 1
  1696. _console_run_bounded 30 "$py" -I -c "$_CONSOLE_STATE_PARSER" "$state"
  1697. }
  1698. _console_next_hint() {
  1699. _blank
  1700. _say "${BOLD}Next:${RESET} open the Ouroboros console in your browser with: ouroboros gui"
  1701. }
  1702. _console_log_hint() {
  1703. [ "$1" = /dev/null ] || _info "Log: $1"
  1704. }
  1705. # Start `ouroboros gui` detached and wait until <seconds> have passed for it to
  1706. # report its address (each check is itself bounded, so the wait ends within
  1707. # <seconds> plus one parser bound). Ignoring SIGHUP (what nohup does) and,
  1708. # where available, setsid keep it alive after this terminal closes. A console
  1709. # that is already running is reused by `ouroboros gui`, which then only opens
  1710. # the browser and exits 0.
  1711. _console_start() {
  1712. local cmd="$1" seconds="$2" dir="$HOME/.ouroboros/gui" state log py before current last url="" pid status="" deadline
  1713. state="$dir/server.json"
  1714. log="$dir/console.log"
  1715. if ! mkdir -p "$dir" 2>/dev/null; then
  1716. log=/dev/null
  1717. elif [ -L "$log" ] || { [ -e "$log" ] && [ ! -f "$log" ]; }; then
  1718. log=/dev/null # never follow a link or write into a FIFO or device
  1719. elif [ -e "$log" ] && ! chmod 600 "$log" 2>/dev/null; then
  1720. log=/dev/null # an existing log stays private, or is not used at all
  1721. fi
  1722. py=$(_console_json_python "$cmd" || true)
  1723. if [ -z "$py" ]; then
  1724. # Without a parser the URL cannot be confirmed; only watch for an
  1725. # immediate failure, then hand over to the reopen hint.
  1726. [ "$seconds" -le 3 ] || seconds=3
  1727. fi
  1728. before=""
  1729. if [ -f "$state" ]; then
  1730. before=$(cat "$state" 2>/dev/null || true)
  1731. fi
  1732. last="$before"
  1733. (
  1734. trap '' HUP
  1735. umask 077
  1736. # Python's webbrowser does not know wslview; point it there when WSL has
  1737. # no browser configured, which is the bridge _console_has_desktop found.
  1738. if _console_is_wsl && [ -z "${BROWSER:-}" ] && command -v wslview >/dev/null 2>&1; then
  1739. export BROWSER=wslview
  1740. fi
  1741. if command -v setsid >/dev/null 2>&1; then
  1742. exec setsid "$cmd" gui </dev/null >>"$log" 2>&1
  1743. fi
  1744. exec "$cmd" gui </dev/null >>"$log" 2>&1
  1745. ) &
  1746. pid=$!
  1747. deadline=$((SECONDS + seconds))
  1748. while :; do
  1749. if ! kill -0 "$pid" 2>/dev/null; then
  1750. if wait "$pid" 2>/dev/null; then status=0; else status=$?; fi
  1751. break
  1752. fi
  1753. if [ -f "$state" ]; then
  1754. current=$(cat "$state" 2>/dev/null || true)
  1755. if [ -n "$current" ] && [ "$current" != "$last" ]; then
  1756. last="$current"
  1757. url=$(_console_state_url "$py" "$state" || true)
  1758. [ -z "$url" ] || break
  1759. fi
  1760. fi
  1761. [ "$SECONDS" -lt "$deadline" ] || break
  1762. sleep 0.1
  1763. done
  1764. if [ -n "$url" ]; then
  1765. _ok "The Ouroboros console is running in the background at $url"
  1766. _info "It opens in your browser. Stop it with \"Stop console\" at the bottom of its sidebar."
  1767. _info "Reopen it any time with: ouroboros gui"
  1768. _console_log_hint "$log"
  1769. elif [ "$status" = 0 ]; then
  1770. url=$(_console_state_url "$py" "$state" || true)
  1771. if [ -n "$url" ]; then
  1772. _ok "The Ouroboros console is already running at $url; opened it in your browser."
  1773. _info "Reopen it any time with: ouroboros gui"
  1774. else
  1775. _warn "Could not confirm that the Ouroboros console started."
  1776. _console_log_hint "$log"
  1777. _info "Start it any time with: ouroboros gui"
  1778. fi
  1779. elif [ -n "$status" ]; then
  1780. _warn "The Ouroboros console did not start (exit $status). The installation itself is complete."
  1781. _console_log_hint "$log"
  1782. _info "Start it any time with: ouroboros gui"
  1783. else
  1784. _info "The Ouroboros console is still starting in the background; it opens in your browser when ready."
  1785. _info "Stop it with \"Stop console\" at the bottom of its sidebar. Reopen it any time with: ouroboros gui"
  1786. _console_log_hint "$log"
  1787. fi
  1788. }
  1789. _console_after_install() {
  1790. local cmd="$1"
  1791. if _console_opted_out; then
  1792. return 0
  1793. fi
  1794. [ -n "$cmd" ] || return 0
  1795. _console_supported "$cmd" 150 || return 0
  1796. if [ -n "${CI+x}" ] || ! _console_has_terminal || ! _console_has_desktop; then
  1797. _console_next_hint
  1798. return 0
  1799. fi
  1800. _blank
  1801. _say "${BLUE}◆${RESET} ${BOLD}Ouroboros console${RESET}"
  1802. _console_start "$cmd" 20
  1803. }
  1804. _console_after_install "${OUROBOROS_SETUP_CMD:-}" || true

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.