Skip to content
Back to search

ank

MarketplaceWorks with Claude CodeGitHub

The ank skills, served from the repository that carries the tool.

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

It has changed since its scan on 11 Nov 2026.

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/haksolot/ank 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/haksolot/ank'

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/haksolot--ank/badge.svg)](/listings/haksolot--ank)

HTML

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

Install

Install instructions from the README

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

npm install -g @haksolot/ank     # the binary for your platform
npx skills add haksolot/ank      # the skills, for your agent

Linux, macOS and Windows; needs git 2.34 or newer. The shell installers and every other route are in [Install][install]. The version is `0.x` on purpose: the loop and the exit codes are specified, the storage format is not yet.

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 · 15 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. {
  2. "name": "ank",
  3. "description": "The ank skills, served from the repository that carries the tool.",
  4. "owner": {
  5. "name": "haksolot",
  6. "url": "https://github.com/haksolot"
  7. },
  8. "plugins": [
  9. {
  10. "name": "ank",
  11. "source": "./",
  12. "description": "Carries the six ank skills: the contract that teaches claiming work and finishing it with proof, and one policy each for planning, drift, the loop, test-first and diagnosis."
  13. }
  14. ]
  15. }
README.md · README · 83 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <p align="center"><picture>
  2. <source media="(prefers-color-scheme: dark)" srcset="assets/ank-dark.svg">
  3. <img src="assets/ank.svg" alt="" width="88" height="88"></picture></p>
  4. <h1 align="center">ank</h1>
  5. <p align="center"><strong>The stupid coordination tool</strong><br>
  6. Tasks and architecture decisions in your repo, behind one CLI any coding agent can call.</p>
  7. <p align="center"><a href="https://github.com/haksolot/ank/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/haksolot/ank/actions/workflows/ci.yml/badge.svg"></a>
  8. <a href="https://github.com/haksolot/ank/releases/latest"><img alt="Latest release" src="https://img.shields.io/github/v/release/haksolot/ank"></a>
  9. <a href="LICENSE"><img alt="Licence" src="https://img.shields.io/badge/licence-Apache--2.0-blue"></a></p>
  10. An agent can read every line of your code, but not your tracker, your wiki, or
  11. the thread where you decided that sessions must never be self-contained JWTs.
  12. Ank keeps those decisions and the work in `.ank/`, attached to the code they
  13. constrain, and serves them through one CLI.
  14. <p align="center"><picture>
  15. <source media="(prefers-color-scheme: dark)" srcset="assets/demo-dark.gif">
  16. <img src="assets/demo.gif" alt="A terminal session: ank context serves a constraint saying every refusal must name the command that fixes it; ank graph shows which task is takeable; a task is claimed and its criterion frozen; the code written next produces exactly that message; ank done runs the declared verifier and records a hashed proof."></picture></p>
  17. ## Install
  18. ```sh
  19. npm install -g @haksolot/ank # the binary for your platform
  20. npx skills add haksolot/ank # the skills, for your agent
  21. ```
  22. Linux, macOS and Windows; needs git 2.34 or newer. The shell installers and
  23. every other route are in [Install][install]. The version is `0.x` on purpose: the loop and
  24. the exit codes are specified, and so is the file format, by the accepted data-model
  25. spec listed in [the specification][spec]. The format may still change before 1.0,
  26. and a change arrives as a new `schema` value.
  27. ## The loop
  28. ```sh
  29. ank context <path> # what binds this perimeter, and what is takeable
  30. ank claim <id> # take a task and freeze its criterion
  31. ank show <id> # the entity whole
  32. ank log "<message>" # what you learned, while you work
  33. ank done # run the declared verifiers and record the proof
  34. ank release --reason "<why>" # hand the task back
  35. ```
  36. [The quickstart][start] walks it from `ank init` onward, with real output.
  37. ## What it is not
  38. - **Not a tracker.** No cycles, estimates, velocity or roadmap.
  39. - **Not a wiki.** Only what is actionable or binding for an agent goes in.
  40. - **Not a security boundary.** It protects against drift, not against an attacker.
  41. ## Documentation
  42. The documentation is published at <https://haksolot.github.io/ank/>, built from
  43. [`docs/`](https://github.com/haksolot/ank/tree/main/docs) on every merge.
  44. - **Using ank**: [Install][install], [the quickstart][start], [proof and
  45. verifiers](https://haksolot.github.io/ank/proof.html), [claims and
  46. identity](https://haksolot.github.io/ank/claims.html), [reading `ank
  47. check`](https://haksolot.github.io/ank/check.html), [CI](https://haksolot.github.io/ank/ci.html),
  48. [multi-agent work](https://haksolot.github.io/ank/multi-agent.html)
  49. - **Reference**: [exit codes](https://haksolot.github.io/ank/exit-codes.html),
  50. [the file format](https://haksolot.github.io/ank/format.html),
  51. [environment variables](https://haksolot.github.io/ank/environment.html),
  52. [the specification](https://haksolot.github.io/ank/specification.html)
  53. - **Integrating**: [the machine surface](https://haksolot.github.io/ank/integrating.html),
  54. [the MCP server](https://haksolot.github.io/ank/mcp.html),
  55. [the watcher](https://haksolot.github.io/ank/watch.html)
  56. - **Maintaining**: [ratifying](https://haksolot.github.io/ank/ratifying.html),
  57. [releasing](https://haksolot.github.io/ank/releasing.html),
  58. [CI jobs](https://haksolot.github.io/ank/ci-jobs.html)
  59. - [Contributing](https://github.com/haksolot/ank/blob/main/CONTRIBUTING.md) · [Security](https://github.com/haksolot/ank/blob/main/SECURITY.md) · [Code of Conduct](https://github.com/haksolot/ank/blob/main/CODE_OF_CONDUCT.md)
  60. ## Licence
  61. Apache-2.0. See [LICENSE](LICENSE).
  62. [install]: https://haksolot.github.io/ank/install.html
  63. [start]: https://haksolot.github.io/ank/quickstart.html
  64. [spec]: https://haksolot.github.io/ank/specification.html
install.ps1 · Bundled script · 1,332 lines · 6 findings marked
  1. <#
  2. Install ank from a GitHub release.
  3. irm https://raw.githubusercontent.com/haksolot/ank/main/install.ps1 | iex
    • Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
    • Line 4 on GitHub
  4. & ([scriptblock]::Create((irm https://raw.githubusercontent.com/haksolot/ank/main/install.ps1))) -Version v0.2.0
  5. The Windows counterpart of install.sh, and the same contract: fetch the archive
  6. the release published, verify it against the .sha256 published beside it, unpack
  7. it, and never end in silence. What differs is only what Windows spells
  8. differently.
  9. One executable lands: ank.exe. The protocol surface and the watcher are verbs
  10. of it (ADR-1ea31c2f3c5a), so there is no second file for this script to place
  11. and no way for one to fail to arrive.
  12. -Version reaches releases published before that was true, whose archive carries
  13. a second executable beside ank.exe. Nothing here asks: the archive is unpacked,
  14. ank.exe is taken out of it, and whatever else the directory holds goes with the
  15. temporary directory. So an old release installs the one file this script
  16. promises, by the same code path a new one does.
  17. Windows PowerShell 5.1 is the floor, because that is what a clean Windows ships
  18. and this channel exists for the machine that has nothing installed yet. Two
  19. consequences run through the file: TLS 1.2 is turned on explicitly, since 5.1
  20. still defaults to protocols GitHub refuses, and every cmdlet used here is one
  21. 5.1 carries.
  22. Exit codes, so a caller can branch on the failure rather than on the message:
  23. 1 usage, or a directory that cannot be written
  24. 2 unsupported platform
  25. 3 the download failed, or the release does not carry this archive
  26. 4 the checksum did not match the one the release published, or the build
  27. provenance was checked and did not verify
  28. 5 a runtime this script needs is missing, gh included under
  29. -RequireProvenance
  30. -NoWelcome, or ANK_NO_WELCOME in the environment, turns off everything this
  31. script draws for a human and everything it asks one, and leaves only the lines
  32. a machine reads. It is absent from the list above on purpose: the welcome is
  33. drawn before the first request goes out and the offer comes after the binary is
  34. on disk and verified, so neither is on the path to any of them -- a flag able
  35. to change one of these five codes would be a flag that made the install depend
  36. on it.
  37. They are the codes install.sh returns for the same failures, and they reach a
  38. caller who runs this as a file. The one-liner above runs it through `iex`, where
  39. `exit` would close the window the caller is typing in -- so under `iex` a
  40. failure throws instead, after printing the same diagnosis. That branch is the
  41. whole reason $PSCommandPath is read below: it is empty exactly when this text is
  42. not being run as a file.
  43. #>
  44. param(
  45. [string]$Version,
  46. [string]$Dir,
  47. [switch]$NoWelcome,
  48. [switch]$RequireProvenance,
  49. [switch]$Help
  50. )
  51. # No Set-StrictMode here, and it is not an oversight. Under `iex` this text runs
  52. # in the caller's own session, where a strict mode set by an installer would
  53. # outlive it and change how their next commands behave -- and unlike the two
  54. # settings restored in the finally below, there is nothing to read it back from.
  55. $Repo = 'haksolot/ank'
  56. $RawUrl = "https://raw.githubusercontent.com/$Repo/main/install.ps1"
  57. $ReleasesUrl = "https://github.com/$Repo/releases"
  58. $DefaultBaseUrl = "$ReleasesUrl/download"
  59. # The one target release.yml builds for Windows. Written once and read by both
  60. # the refusal and the help text: a list that says one thing when it refuses and
  61. # another when it is asked is worse than no list at all.
  62. $WindowsTarget = 'x86_64-pc-windows-msvc'
  63. # Empty exactly when this text is not running as a file -- `irm | iex`, or a
  64. # scriptblock built from it. Probed rather than assumed, including from inside
  65. # another script, which is the case a CI step is.
  66. $RunningAsFile = -not [string]::IsNullOrEmpty($PSCommandPath)
  67. # ---------------------------------------------------------------------------
  68. # Output
  69. # ---------------------------------------------------------------------------
  70. # Write-Host and not Write-Output, for the reason install.sh sends everything to
  71. # stderr: under `iex` this runs in the caller's own session, and a diagnosis
  72. # written to the pipeline would land in whatever they were assembling.
  73. # -Color is a console attribute set through the host and never an escape
  74. # sequence, which is the same reason Show-Logo moves the cursor through RawUI:
  75. # Windows PowerShell 5.1 in conhost prints an ESC[36m instead of obeying it. So
  76. # a transcript records the words and no sequence at all, on any run.
  77. function Say {
  78. param([string]$Line = '', [switch]$NoNewline, [string]$Color = '')
  79. $paint = @{}
  80. if ($Color) { $paint['ForegroundColor'] = $Color }
  81. if ($NoNewline) { Write-Host -NoNewline $Line @paint } else { Write-Host $Line @paint }
  82. }
  83. # Colour and the marker, behind the gate the logo is drawn behind, exactly as
  84. # install.sh holds them: empty until Enable-Ui runs, so a console-less caller
  85. # reads the bytes it read before this file learned about either.
  86. #
  87. # DarkGray and not a lighter grey for the dim: it is the one shade that reads as
  88. # quieter against a black console and against a white one, which is the whole of
  89. # what "dim" has to survive here. There is no bold to be had -- a console host
  90. # has a foreground and no weight -- so what install.sh writes bold is written in
  91. # the console's own foreground, and the contrast comes from what is dimmed
  92. # around it.
  93. $UiDim = ''
  94. $UiCyan = ''
  95. $UiGreen = ''
  96. $UiPad = ''
  97. $UiTick = ''
  98. function Enable-Ui {
  99. $script:UiPad = ' '
  100. $script:UiTick = if (Test-GlyphSurvives 0x2713) { "$([char]0x2713) " } else { '- ' }
  101. if ($env:NO_COLOR) { return }
  102. $script:UiDim = 'DarkGray'
  103. $script:UiCyan = 'Cyan'
  104. $script:UiGreen = 'Green'
  105. }
  106. # `Ok <line>`: a step that finished. The marker and the indent are drawn for a
  107. # person and for nobody else -- what a transcript reads is the sentence alone,
  108. # written by the one call the line used to be, rather than by three that happen
  109. # to concatenate to it.
  110. function Ok {
  111. param([string]$Line)
  112. if (-not $UiTick) {
  113. Say $Line
  114. return
  115. }
  116. Say -NoNewline $UiPad
  117. Say -NoNewline -Color $UiGreen $UiTick
  118. Say $Line
  119. }
  120. # `Fail <code> <lines>`: the code carries the kind of failure, the lines carry
  121. # what to do next. Nothing here ever ends in silence -- that is the one thing an
  122. # install script cannot do, since the caller is otherwise left with no binary
  123. # and no idea why.
  124. function Fail {
  125. param([int]$Code, [string[]]$Lines)
  126. Say "ank: $($Lines[0])"
  127. for ($i = 1; $i -lt $Lines.Count; $i++) { Say $Lines[$i] }
  128. if ($RunningAsFile) { exit $Code }
  129. # Under `iex` the caller is at their own prompt: `exit` would take the
  130. # session with it, which is a worse outcome than the failed install.
  131. throw "ank: install failed (code $Code)"
  132. }
  133. function Show-Usage {
  134. Say 'install ank from a GitHub release'
  135. Say ''
  136. Say 'One executable lands in the install directory: ank.exe. The protocol'
  137. Say 'surface and the watcher are verbs of it -- ank mcp, ank watch -- so'
  138. Say 'there is nothing further to fetch and nothing further to configure a'
  139. Say 'client against.'
  140. Say ''
  141. Say 'usage:'
  142. Say " irm $RawUrl | iex"
  143. Say ''
  144. Say ' with arguments, since a pipe into iex cannot carry them:'
  145. Say " & ([scriptblock]::Create((irm $RawUrl))) -Version v0.2.0"
  146. Say ''
  147. Say 'options:'
  148. Say ' -Version <version> install this release instead of the latest one;'
  149. Say ' "v0.2.0" and "0.2.0" both work'
  150. Say ' -Dir <path> install into <path> instead of'
  151. Say ' $env:LOCALAPPDATA\Programs\ank'
  152. Say ' -NoWelcome draw nothing and ask nothing; install exactly what an'
  153. Say ' interactive run that declined every offer installs'
  154. Say ' -RequireProvenance refuse unless gh verifies the build provenance of the'
  155. Say ' archive; without it, provenance is checked when a'
  156. Say ' signed-in gh is on PATH and the checksum stands alone'
  157. Say ' otherwise'
  158. Say ' -Help print this and exit'
  159. Say ''
  160. Say 'environment:'
  161. Say ' ANK_VERSION same as -Version'
  162. Say ' ANK_INSTALL_DIR same as -Dir'
  163. Say ' ANK_NO_WELCOME same as -NoWelcome, for a caller that pipes this script'
  164. Say ' into iex and cannot pass a switch to it'
  165. Say ' ANK_BASE_URL where the archives are fetched from, for a mirror or a'
  166. Say ' staged release; requires -Version, since only GitHub'
  167. Say ' can be asked which release is the latest'
  168. Say ' ANK_REQUIRE_PROVENANCE'
  169. Say ' same as -RequireProvenance'
  170. Say ''
  171. Say 'platforms:'
  172. Say " Windows x64 $WindowsTarget"
  173. Say ''
  174. Say ' Linux and macOS are installed by install.sh:'
  175. Say " curl -fsSL https://raw.githubusercontent.com/$Repo/main/install.sh | sh"
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 199 on GitHub
  176. Say ''
  177. Say 'the two questions:'
  178. Say ' With a console attached, once ank is installed and verified, this asks two'
  179. Say ' things and nothing else. The first offers to run:'
  180. Say ' ank skills --install'
  181. Say ' which teaches an agent how to use ank. The second offers to print three'
  182. Say ' prompts that adopt ank in a repository that already has code and no .ank;'
  183. Say ' they are in docs/quickstart.md too, and printing them writes nothing'
  184. Say ' anywhere.'
  185. Say ' Enter accepts each, declining either does nothing at all, and nothing'
  186. Say ' either does can change any of the codes below.'
  187. Say ''
  188. Say 'exit codes:'
  189. Say ' 1 usage 2 unsupported platform 3 download 4 checksum 5 missing runtime'
  190. }
  191. # ---------------------------------------------------------------------------
  192. # Welcome
  193. # ---------------------------------------------------------------------------
  194. # The logo, from assets/ank.svg read as pixels: twenty-four columns by ten rows,
  195. # one cell per pixel column and one row per pair of pixel rows, which is the
  196. # ratio that makes a console cell square. The same shape install.sh holds and
  197. # the same twelve lines, because it is the same logo and two spellings of it
  198. # would drift. That file is the reference and nothing here reads it -- an
  199. # installer that fetches a logo before it fetches the binary is an installer
  200. # with a second way to fail before doing anything useful, so the shape is bytes
  201. # in this file.
  202. #
  203. # The block is not assumed, and it is not refused either. The old reading of
  204. # this was that a Windows PowerShell 5.1 in conhost cannot draw U+2588, and it
  205. # is wrong twice over: codepage 437 carries the full block at 0xDB, and a
  206. # console that is genuinely UTF-8 carries it too. What actually decides is
  207. # whether the encoder the console is using can carry the character at all, and
  208. # that is a question with an answer -- Test-GlyphSurvives asks it rather than
  209. # guessing from a codepage number. The tick is asked the same way and gets a
  210. # different answer on 437, which has no U+2713.
  211. $LogoWidth = 24
  212. # Eleven spaces: columns 0 to 10, what stands left of the stem on a row whose
  213. # leg has not grown yet. Every such row is the same width, so this is a constant
  214. # rather than something measured.
  215. $LogoPad11 = ' '
  216. # Whether a character reaches the console as itself: encoded through whatever
  217. # the console is using and decoded back, and equal to what went in.
  218. #
  219. # The round trip and not a search for a question mark, because measuring it
  220. # showed the question mark is the case that does not happen. .NET best-fits
  221. # instead, and it best-fits to something plausible and wrong: codepage 437 turns
  222. # U+2713 into 0xFB, which is a square root sign, and codepage 1252 turns U+2588
  223. # into 0xA6, which is a broken bar. A check for `?` passes both and ships a logo
  224. # made of broken bars and a tick that is a radical -- worse than the fence of
  225. # hashes this replaced. The round trip refuses both and accepts codepage 437's
  226. # block at 0xDB, which is genuinely the character asked for.
  227. #
  228. # Asked once per run, never inside a frame.
  229. function Test-GlyphSurvives {
  230. param([int]$CodePoint)
  231. try {
  232. $want = [string][char]$CodePoint
  233. $encoding = [Console]::OutputEncoding
  234. return $encoding.GetString($encoding.GetBytes($want)) -eq $want
  235. } catch {
  236. return $false
  237. }
  238. }
  239. # One of rows 6 to 9: <pad><leg><gap><stem><gap><leg>, where a part that has not
  240. # grown yet gives its columns up to the eleven-space pad, so the parts that have
  241. # stay where they are. A segment is its text and whether it is dimmed, because a
  242. # leg and the stem share these rows and can be in different states.
  243. function Get-LogoBand {
  244. param(
  245. [int]$Legs, [int]$LegsAt, [int]$Stem, [int]$StemAt,
  246. [string]$Run, [string]$Gap, [string]$Pair,
  247. [bool]$DimLegs, [bool]$DimStem
  248. )
  249. $hasLegs = $Legs -ge $LegsAt
  250. $hasStem = $Stem -ge $StemAt
  251. if (-not $hasLegs -and -not $hasStem) { return , @() }
  252. $out = @()
  253. if ($hasLegs) {
  254. $out += @{ T = ' '; D = $false }
  255. $out += @{ T = $Run; D = $DimLegs }
  256. $out += @{ T = $Gap; D = $false }
  257. } else {
  258. $out += @{ T = $LogoPad11; D = $false }
  259. }
  260. if ($hasStem) {
  261. $out += @{ T = $Pair; D = $DimStem }
  262. } elseif ($hasLegs) {
  263. $out += @{ T = ' '; D = $false }
  264. }
  265. if ($hasLegs) {
  266. $out += @{ T = $Gap; D = $false }
  267. $out += @{ T = $Run; D = $DimLegs }
  268. }
  269. return , $out
  270. }
  271. # One frame as twelve rows of segments. The arguments are the state of the build
  272. # and not a frame number: base is on or off, legs and stem are how many of their
  273. # rows have grown, loop is on or off, soft names the part still arriving, name is
  274. # the wordmark. A timeline written as states can be re-timed without recomputing
  275. # which row is which.
  276. function Get-LogoFrame {
  277. param(
  278. [int]$Base, [int]$Legs, [int]$Stem, [int]$Loop,
  279. [string]$Soft, [bool]$Name,
  280. [string]$B2, [string]$B4, [string]$B14
  281. )
  282. $dimAll = $Soft -eq 'all'
  283. $dimLoop = $dimAll -or $Soft -eq 'loop'
  284. $dimStem = $dimAll -or $Soft -eq 'stem'
  285. $dimLegs = $dimAll -or $Soft -eq 'legs'
  286. $dimBase = $dimAll -or $Soft -eq 'base'
  287. # Rows 1 and 4, then 2 and 3: the loop is columns 10-13, then 8-9 with 14-15.
  288. if ($Loop) {
  289. $r1 = @(@{ T = ' '; D = $false }, @{ T = $B4; D = $dimLoop })
  290. $r2 = @(
  291. @{ T = ' '; D = $false }, @{ T = $B2; D = $dimLoop },
  292. @{ T = ' '; D = $false }, @{ T = $B2; D = $dimLoop }
  293. )
  294. } else {
  295. $r1 = @()
  296. $r2 = @()
  297. }
  298. # Row 5, the stem alone, the last of its five rows to grow.
  299. if ($Stem -ge 5) {
  300. $r5 = @(@{ T = ' '; D = $false }, @{ T = $B2; D = $dimStem })
  301. } else {
  302. $r5 = @()
  303. }
  304. $r6 = Get-LogoBand $Legs 4 $Stem 4 $B4 ' ' $B2 $dimLegs $dimStem
  305. $r7 = Get-LogoBand $Legs 3 $Stem 3 $B2 ' ' $B2 $dimLegs $dimStem
  306. $r8 = Get-LogoBand $Legs 2 $Stem 2 $B2 ' ' $B2 $dimLegs $dimStem
  307. $r9 = Get-LogoBand $Legs 1 $Stem 1 $B2 ' ' $B2 $dimLegs $dimStem
  308. # Row 10, the base, columns 5-18.
  309. if ($Base) {
  310. $r10 = @(@{ T = ' '; D = $false }, @{ T = $B14; D = $dimBase })
  311. } else {
  312. $r10 = @()
  313. }
  314. if ($Name) {
  315. $r12 = @(@{ T = ' ank'; D = $false })
  316. } else {
  317. $r12 = @()
  318. }
  319. return , @($r1, $r2, $r2, $r1, $r5, $r6, $r7, $r8, $r9, $r10, @(), $r12)
  320. }
  321. # The cursor is moved through $Host.UI.RawUI and not with an escape sequence,
  322. # and that is the Windows half of this decision rather than a preference.
  323. # Windows PowerShell 5.1 in conhost does not turn on virtual terminal
  324. # processing for its own output, so an ESC[12A written there is printed as
  325. # glyphs instead of obeyed: the animation would become exactly the mess it
  326. # exists to avoid, on precisely the shell this file claims as its floor. RawUI
  327. # is the interface both hosts implement, and it emits no escape sequence at
  328. # all, on any run.
  329. function Show-Logo {
  330. $ui = $Host.UI.RawUI
  331. # A window narrower than the art wraps every line, and a block that is
  332. # taller than twelve rows is a block the redraw moves back over the middle
  333. # of. Nothing is written before this is known.
  334. if ($ui.WindowSize.Width -lt $LogoWidth) { return }
  335. # The cell and the three runs the shape is made of, built once. Seventeen
  336. # frames are drawn and none of them may repeat this.
  337. $cell = if (Test-GlyphSurvives 0x2588) { [string][char]0x2588 } else { '#' }
  338. $b2 = $cell * 2
  339. $b4 = $cell * 4
  340. $b14 = $cell * 14
  341. $rows = 12
  342. # The blank lines are written before the position is read, so that a window
  343. # with the prompt at its bottom does its scrolling now: a coordinate saved
  344. # while the buffer is still moving points at the wrong row for every frame
  345. # after it.
  346. for ($i = 0; $i -lt $rows; $i++) { Say '' }
  347. $top = $ui.CursorPosition.Y - $rows
  348. if ($top -lt 0) { return }
  349. $origin = New-Object System.Management.Automation.Host.Coordinates 0, $top
  350. $savedCursor = $true
  351. try {
  352. $savedCursor = [Console]::CursorVisible
  353. [Console]::CursorVisible = $false
  354. } catch {
  355. # A host that will not say whether its cursor is visible still draws.
  356. }
  357. # Bottom up: the base arrives dim and settles, the legs and then the stem
  358. # grow out of it a row at a time, the loop crowns them, and the whole shape
  359. # blinks twice before the name appears. That last beat is what the animation
  360. # exists for -- it costs the time it takes to read the name of the tool and
  361. # not a second more.
  362. #
  363. # The two parts that appear whole come in dim; the two that grow do not,
  364. # since growing a row at a time is already motion and dimming it as well
  365. # would say the same thing twice.
  366. #
  367. # base legs stem loop soft name ms
  368. $script = @(
  369. @(1, 0, 0, 0, 'base', $false, 100),
  370. @(1, 0, 0, 0, 'none', $false, 100),
  371. @(1, 1, 0, 0, 'none', $false, 45),
  372. @(1, 2, 0, 0, 'none', $false, 45),
  373. @(1, 3, 0, 0, 'none', $false, 45),
  374. @(1, 4, 0, 0, 'none', $false, 45),
  375. @(1, 4, 1, 0, 'none', $false, 45),
  376. @(1, 4, 2, 0, 'none', $false, 45),
  377. @(1, 4, 3, 0, 'none', $false, 45),
  378. @(1, 4, 4, 0, 'none', $false, 45),
  379. @(1, 4, 5, 0, 'none', $false, 45),
  380. @(1, 4, 5, 1, 'loop', $false, 100),
  381. @(1, 4, 5, 1, 'none', $false, 100),
  382. @(1, 4, 5, 1, 'all', $false, 45),
  383. @(1, 4, 5, 1, 'none', $false, 45),
  384. @(1, 4, 5, 1, 'all', $false, 45),
  385. @(1, 4, 5, 1, 'none', $true, 450)
  386. )
  387. try {
  388. foreach ($step in $script) {
  389. $ui.CursorPosition = $origin
  390. $frame = Get-LogoFrame $step[0] $step[1] $step[2] $step[3] `
  391. $step[4] $step[5] $b2 $b4 $b14
  392. foreach ($row in $frame) { Write-LogoRow $row }
  393. Start-Sleep -Milliseconds $step[6]
  394. }
  395. } finally {
  396. try { [Console]::CursorVisible = $savedCursor } catch { }
  397. }
  398. # One blank line under the block, so what the install says next does not
  399. # start on the line the name ends on.
  400. Say ''
  401. }
  402. # One row of a frame. Padded to the full width rather than erased: there is no
  403. # clear-to-end-of-line without an escape sequence, and writing the spaces says
  404. # the same thing in the alphabet this function is restricted to.
  405. #
  406. # Adjacent segments in the same state are written as one, and that is not
  407. # tidiness. conhost turns every write that changes an attribute into a console
  408. # API call, and a row is almost always one state throughout: segment by segment
  409. # the seventeen frames cost 649 writes for 94 actual changes of attribute, so
  410. # 555 of them bought nothing. Coalesced, a row in one state is one write.
  411. function Write-LogoRow {
  412. param($Segments)
  413. $runs = @()
  414. $width = 0
  415. foreach ($seg in $Segments) {
  416. $segDim = [bool]($seg.D -and $UiDim)
  417. if ($runs.Count -gt 0 -and $runs[-1].D -eq $segDim) {
  418. $runs[-1].T += $seg.T
  419. } else {
  420. $runs += @{ T = $seg.T; D = $segDim }
  421. }
  422. $width += $seg.T.Length
  423. }
  424. # The padding closes the line and carries no state of its own, so it joins
  425. # the last run when that run is not dimmed and stands alone when it is.
  426. $pad = ''
  427. if ($width -lt $LogoWidth) { $pad = ' ' * ($LogoWidth - $width) }
  428. if ($runs.Count -gt 0 -and -not $runs[-1].D) {
  429. $runs[-1].T += $pad
  430. $pad = $null
  431. }
  432. for ($i = 0; $i -lt $runs.Count; $i++) {
  433. $last = ($i -eq $runs.Count - 1) -and ($null -eq $pad)
  434. if ($runs[$i].D) {
  435. if ($last) { Say -Color $UiDim $runs[$i].T }
  436. else { Say -NoNewline -Color $UiDim $runs[$i].T }
  437. } else {
  438. if ($last) { Say $runs[$i].T }
  439. else { Say -NoNewline $runs[$i].T }
  440. }
  441. }
  442. if ($null -ne $pad) { Say $pad }
  443. }
  444. # ADR-5fbd99bf6fd5 read as an absence: where no human is looking, this script
  445. # draws nothing at all and asks nothing at all.
  446. #
  447. # Both streams are tested and not only one. `irm ... | iex` leaves stdout and
  448. # stderr on the console, which is the case that must animate; redirecting
  449. # either of them into a file is the case that must not, since a transcript full
  450. # of padding and repositioning is the noise this exists to avoid. The host is
  451. # asked last, and by trying rather than by name: a host with no console answers
  452. # the two properties above happily and then throws on the first cursor it is
  453. # asked to place.
  454. #
  455. # The logo and the offer read this same answer, which is what makes -NoWelcome
  456. # and an interactive run that declined everything leave the same machine
  457. # behind: one predicate, so there is no second gate to disagree with this one.
  458. # The width belongs to the block of art alone and is asked inside Show-Logo,
  459. # since a console too narrow to hold the logo is still a console with a person
  460. # in front of it.
  461. function Test-HumanAtTerminal {
  462. if ($NoWelcome) { return $false }
  463. if ($env:ANK_NO_WELCOME) { return $false }
  464. # A runner sets this, and a runner is a machine with no human at it.
  465. if ($env:CI) { return $false }
  466. try {
  467. if ([Console]::IsOutputRedirected) { return $false }
  468. if ([Console]::IsErrorRedirected) { return $false }
  469. $null = $Host.UI.RawUI.CursorPosition
  470. } catch {
  471. return $false
  472. }
  473. return $true
  474. }
  475. # ---------------------------------------------------------------------------
  476. # The skills
  477. # ---------------------------------------------------------------------------
  478. # ADR-5fbd99bf6fd5's offer, and the last thing this script does. Everything
  479. # else has already happened by then: the binary is on disk, verified, reported,
  480. # and the PATH advice given. That ordering is the decision rather than a layout
  481. # -- an installation that stops to ask something is an installation that can be
  482. # abandoned half-done, and half-done is the worst state for a tool whose next
  483. # action is `ank context`.
  484. #
  485. # The question is this script's and the answer is the binary's
  486. # (ADR-e1d750884b82). `ank skills --install` writes out the skills it carries
  487. # and hands them to the skills CLI, which serves every agent it knows about
  488. # rather than one, and the verb already decides what to say when node is
  489. # missing and what a failure means. A second copy of that logic here would be
  490. # a second copy to drift.
  491. #
  492. # Nothing in here is allowed to reach the caller as a failure. The call site
  493. # wraps it, and the exit code is stamped after it returns.
  494. function Invoke-SkillOffer {
  495. param([Parameter(Mandatory = $true)][string]$Ank)
  496. if (-not (Test-HumanAtTerminal)) { return }
  497. Say ''
  498. Say "${UiPad}The skills teach an agent how to use ank: the contract, and one policy"
  499. Say "${UiPad}per activity. They install through the skills CLI, which puts them where"
  500. Say "${UiPad}each agent looks."
  501. Say ''
  502. Say -Color $UiCyan "$UiPad ank skills --install"
  503. Say ''
  504. # [Console]::ReadLine and not Read-Host, which is where Windows differs
  505. # from the /dev/tty install.sh opens and why the two files spell this step
  506. # differently. `irm ... | iex` runs this text through a pipeline in the
  507. # caller's own session: Console.In is the console and never that pipeline,
  508. # so a question asked here cannot consume what they piped. $null is end of
  509. # input -- nothing was typed, so nothing is assumed.
  510. Say -NoNewline "${UiPad}Install them now? [Y/n] "
  511. $answer = $null
  512. try { $answer = [Console]::ReadLine() } catch { $answer = $null }
  513. if ($null -eq $answer) {
  514. Say ''
  515. return
  516. }
  517. # Enter is yes and everything unrecognised is no, in that order: a default
  518. # the criterion names, and a decline for anything else because asking twice
  519. # is asking twice.
  520. $reply = $answer.Trim()
  521. if ($reply -ne '' -and $reply -notmatch '^(y|yes)$') { return }
  522. # The binary just installed, by the path it was installed at: the directory
  523. # may not be on PATH, and a different ank found there would answer for a
  524. # build this script did not place.
  525. #
  526. # Nothing is printed on success, and that is deliberate: the verb exits 0
  527. # both when the skills went in and when node is missing and it printed the
  528. # command to run instead, so a line of this script's own would be claiming
  529. # something only the verb's output knows.
  530. $code = 0
  531. try {
  532. $global:LASTEXITCODE = 0
  533. # Through Say for the reason Say exists: under `iex` output written to
  534. # the pipeline lands in whatever the caller was assembling. 2>&1 so the
  535. # verb's diagnosis arrives as text rather than as error records a
  536. # caller's $ErrorActionPreference could turn into an exception.
  537. & $Ank skills --install 2>&1 | ForEach-Object { Say "$_" }
  538. $code = $LASTEXITCODE
  539. } catch {
  540. Say " $($_.Exception.Message)"
  541. $code = 9
  542. }
  543. if ($code -ne 0) {
  544. Say ''
  545. Say "ank skills --install exited $code, so the skills are not installed."
  546. Say 'ank is, and it is exactly the ank this script installs when nobody is'
  547. Say 'asked anything at all.'
  548. Say ''
  549. Say 'Run it again when you want them:'
  550. Say -Color $UiCyan "$UiPad ank skills --install"
  551. }
  552. }
  553. # ---------------------------------------------------------------------------
  554. # Adopting ank where there is already code
  555. # ---------------------------------------------------------------------------
  556. # ADR-5fbd99bf6fd5's second offer, and the last question this script asks.
  557. # Installing ank is the easy half. The half nobody had written down is what to
  558. # say to an agent so that a repository with two years of history acquires a
  559. # corpus worth having, and the moment after an install is the one moment the
  560. # person is certainly reading.
  561. #
  562. # Three prompts, because the adoption has three moments: state as ADRs what the
  563. # code already decided, so the constraints that exist implicitly become
  564. # readable; turn a list of intentions into tasks carrying a scope and a
  565. # criterion; and check what came out. The first one is the one the reader judges
  566. # the tool on, which is why it is first.
  567. #
  568. # The same three prose blocks live in install.sh and in docs/quickstart.md,
  569. # and a test holds the three copies character for character
  570. # (crates/ank-cli/tests/adopt.rs). Prose duplicated in three files diverges, and
  571. # this is the prose where divergence is worst: an installer teaching a prompt the
  572. # documentation has since corrected. The markers below are what the test reads;
  573. # the block between them is the one to edit, and the other two follow.
  574. #
  575. # A single-quoted here-string, so nothing in it is expanded: the text carries $
  576. # and backticks in no place today, and a literal block is what keeps that from
  577. # becoming a rule somebody has to remember. Its terminator sits at column zero
  578. # because Windows PowerShell 5.1 requires it there.
  579. # adopt-prompts:begin
  580. $AdoptWalkthrough = @'
  581. In a repository that already has code and no .ank, start with:
  582. ank init
  583. Then paste these three into your agent, one at a time, and read what each
  584. one produces before you send the next.
  585. 1. What the code already decided:
  586. Read this repository and write, as ank ADRs, the decisions its code
  587. has already made: the ones a newcomer would break without knowing
  588. they existed. One ADR per decision, each with a scope glob covering
  589. the files it binds and a constraint stated as a rule. Leave them
  590. proposed; I ratify them myself.
  591. 2. What is still owed:
  592. Read the TODOs, the open issues and the README of this repository,
  593. and turn what they promise into ank tasks. Give each one a scope
  594. glob and a done_criteria a test could settle, and use blocked_by
  595. only where a task genuinely waits on another.
  596. 3. What you now have:
  597. Run ank check and ank review here, then read every ADR back against
  598. the code its scope matches. Tell me which constraints the code
  599. already breaks and which scopes match no file, and change nothing
  600. until I have read your answer.
  601. The same three are in docs/quickstart.md, which says what to expect
  602. from each:
  603. https://github.com/haksolot/ank/blob/main/docs/quickstart.md
  604. '@
  605. # adopt-prompts:end
  606. # The second question, asked on the same terms as the first: only with a human
  607. # at a console, through [Console]::ReadLine so that a caller's `iex` pipeline is
  608. # never what answers it, and with a default Enter accepts. Declining prints
  609. # nothing -- not a shortened version, not a pointer to one. An offer that
  610. # answers a no with half of a yes is an offer that was not really asked.
  611. #
  612. # Nothing in here is allowed to reach the caller as a failure. The call site
  613. # wraps it, and the exit code is stamped after it returns.
  614. function Invoke-AdoptionOffer {
  615. if (-not (Test-HumanAtTerminal)) { return }
  616. Say ''
  617. Say -NoNewline "${UiPad}Print the three prompts that adopt ank in a repository you already have? [Y/n] "
  618. $answer = $null
  619. try { $answer = [Console]::ReadLine() } catch { $answer = $null }
  620. if ($null -eq $answer) {
  621. Say ''
  622. return
  623. }
  624. $reply = $answer.Trim()
  625. if ($reply -ne '' -and $reply -notmatch '^(y|yes)$') { return }
  626. Say ''
  627. # Split on either ending rather than on [Environment]::NewLine: this file is
  628. # fetched by `irm` on one machine and checked out by git on another, and the
  629. # bytes between two lines are not the same in both.
  630. foreach ($line in ($AdoptWalkthrough -split "\r?\n")) { Say $line }
  631. Say ''
  632. }
  633. # ---------------------------------------------------------------------------
  634. # Platform
  635. # ---------------------------------------------------------------------------
  636. # Read out of the environment rather than off RuntimeInformation, and that is
  637. # the deliberate half: an environment variable is what lets the refusal below be
  638. # exercised on a machine that is not the platform being refused, so the test
  639. # runs the real code path instead of a flag that bypasses it.
  640. #
  641. # PROCESSOR_ARCHITEW6432 is read first because a 32-bit PowerShell on 64-bit
  642. # Windows reports x86 in the other variable, and installing nothing on a machine
  643. # that is x64 would be a refusal about the process rather than about the
  644. # hardware.
  645. function Get-Architecture {
  646. if ($env:PROCESSOR_ARCHITEW6432) { return $env:PROCESSOR_ARCHITEW6432.ToUpperInvariant() }
  647. if ($env:PROCESSOR_ARCHITECTURE) { return $env:PROCESSOR_ARCHITECTURE.ToUpperInvariant() }
  648. return 'UNKNOWN'
  649. }
  650. # ARM64 takes the x64 archive on purpose. No native arm64 build is published,
  651. # and Windows on ARM runs x64 under emulation transparently -- so refusing there
  652. # would leave a working machine with no install to protect it from nothing. What
  653. # is refused is the architecture that genuinely cannot run this binary: a 32-bit
  654. # x86 Windows, where the emulation runs the other way and does not exist.
  655. function Resolve-Target {
  656. $arch = Get-Architecture
  657. switch ($arch) {
  658. 'AMD64' { return @{ Target = $WindowsTarget; Emulated = $false } }
  659. 'ARM64' { return @{ Target = $WindowsTarget; Emulated = $true } }
  660. default {
  661. Fail 2 @(
  662. "no release archive for Windows/$arch.",
  663. '',
  664. "PROCESSOR_ARCHITECTURE reported: $arch",
  665. '',
  666. 'The release carries one Windows build:',
  667. " Windows x64 $WindowsTarget",
  668. '',
  669. 'A 64-bit Windows runs it natively and Windows on ARM runs it under',
  670. 'emulation; a 32-bit Windows runs neither.',
  671. '',
  672. 'Everything the release carries is listed at:',
  673. " $ReleasesUrl",
  674. '',
  675. 'Nothing was installed.'
  676. )
  677. }
  678. }
  679. }
  680. # ---------------------------------------------------------------------------
  681. # Hashing and unpacking
  682. # ---------------------------------------------------------------------------
  683. # Get-FileHash and Expand-Archive would both read better here, and neither is
  684. # used, for a reason worth recording: they live in modules PowerShell autoloads,
  685. # and autoloading is the part of this that can be broken by the environment
  686. # rather than by the machine. Measured while writing this file -- a 5.1 started
  687. # from a session whose PSModulePath pointed at PowerShell 7's module directories
  688. # resolved neither cmdlet, and the install died after downloading the archive,
  689. # on the step that exists to verify it.
  690. #
  691. # The .NET types below are in the runtime itself. Nothing is searched for, so
  692. # there is nothing to shadow, and the two operations this script must never
  693. # skip are the two that stop depending on a lookup.
  694. function Get-Sha256 {
  695. param([string]$Path)
  696. $sha = [System.Security.Cryptography.SHA256]::Create()
  697. $stream = [System.IO.File]::OpenRead($Path)
  698. try {
  699. $bytes = $sha.ComputeHash($stream)
  700. } finally {
  701. $stream.Dispose()
  702. $sha.Dispose()
  703. }
  704. return ([System.BitConverter]::ToString($bytes) -replace '-', '').ToLowerInvariant()
  705. }
  706. function Expand-Zip {
  707. param([string]$Path, [string]$Destination)
  708. # Built into PowerShell 7; on 5.1 the assembly is present and simply has to
  709. # be asked for. Loading one already loaded is a no-op, so this is not
  710. # guarded by a version test that would be one more thing to be wrong.
  711. Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction SilentlyContinue
  712. [System.IO.Compression.ZipFile]::ExtractToDirectory($Path, $Destination)
  713. }
  714. # Windows locks a running executable, so an upgrade run while another shell has
  715. # one of these open cannot write over the file -- but it can rename it, which is
  716. # the one thing Windows does allow. The old binary is moved aside and the new
  717. # one takes the name; the stale copies are swept on the next run, since the
  718. # process holding one is still holding it now.
  719. #
  720. # A function rather than an inlined block: what it does is subtle enough to be
  721. # worth reading on its own, and its one caller is easier to read for not
  722. # carrying it. Returns the message of the failure it could not work around, or
  723. # $null.
  724. function Move-IntoPlace {
  725. param([string]$Source, [string]$Destination, [string]$Name)
  726. # Out-Null and not for tidiness: what this function returns is read as a
  727. # message, so a pipeline above it that emitted anything would turn that
  728. # message into an array and the caller's `if` into a lie.
  729. Get-ChildItem -Path (Split-Path -Parent $Destination) -Filter "$Name.old-*" `
  730. -ErrorAction SilentlyContinue |
  731. ForEach-Object { Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue } |
  732. Out-Null
  733. try {
  734. Move-Item -Path $Source -Destination $Destination -Force -ErrorAction Stop
  735. return $null
  736. } catch {
  737. $aside = "$Destination.old-" + [System.IO.Path]::GetRandomFileName()
  738. try {
  739. Move-Item -Path $Destination -Destination $aside -Force -ErrorAction Stop
  740. Move-Item -Path $Source -Destination $Destination -Force -ErrorAction Stop
  741. Say "the running $Name was moved aside; it is swept on the next install"
  742. return $null
  743. } catch {
  744. return "$($_.Exception.Message)"
  745. }
  746. }
  747. }
  748. # ---------------------------------------------------------------------------
  749. # Downloading
  750. # ---------------------------------------------------------------------------
  751. # Returns the HTTP status when the request produced one, so that "this release
  752. # does not carry that archive" and "the network is down" stay different
  753. # messages: the 404 is what tells them apart.
  754. function Get-File {
  755. param([string]$Url, [string]$OutFile)
  756. try {
  757. Invoke-WebRequest -Uri $Url -OutFile $OutFile -UseBasicParsing -ErrorAction Stop
  758. return @{ Ok = $true; Status = '' }
  759. } catch [System.Net.WebException] {
  760. $status = ''
  761. if ($_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode }
  762. return @{ Ok = $false; Status = "$status" }
  763. } catch {
  764. # PowerShell 7 wraps the failure in HttpResponseException instead, and
  765. # keeps the status on the same property.
  766. $status = ''
  767. if (($_.Exception | Get-Member -Name Response) -and $_.Exception.Response) {
  768. $status = [int]$_.Exception.Response.StatusCode
  769. }
  770. return @{ Ok = $false; Status = "$status" }
  771. }
  772. }
  773. # The tag of the latest release, read off the redirect rather than through the
  774. # API: /releases/latest redirects to /releases/tag/<tag>, which costs no rate
  775. # limit, where api.github.com allows sixty unauthenticated calls an hour per
  776. # address and an office NAT can be out of them before anyone types this.
  777. #
  778. # HttpWebRequest and not Invoke-WebRequest, because -MaximumRedirection 0 is one
  779. # of the places 5.1 and 7 disagree: one returns the response and the other
  780. # throws, and reading the Location header off the raw request behaves the same
  781. # on both.
  782. function Resolve-LatestTag {
  783. $tag = ''
  784. try {
  785. $request = [System.Net.HttpWebRequest]::Create("$ReleasesUrl/latest")
  786. $request.AllowAutoRedirect = $false
  787. $request.Method = 'HEAD'
  788. $request.UserAgent = 'ank-install.ps1'
  789. $response = $request.GetResponse()
  790. $location = $response.Headers['Location']
  791. $response.Close()
  792. if ($location) { $tag = $location.Split('/')[-1] }
  793. } catch {
  794. $tag = ''
  795. }
  796. if ($tag -notmatch '^v') {
  797. Fail 3 @(
  798. 'could not work out which release is the latest.',
  799. '',
  800. 'Name one instead:',
  801. " & ([scriptblock]::Create((irm $RawUrl))) -Version v0.2.0",
  802. '',
  803. 'The releases are listed at:',
  804. " $ReleasesUrl"
  805. )
  806. }
  807. return $tag
  808. }
  809. # ---------------------------------------------------------------------------
  810. # Arguments
  811. # ---------------------------------------------------------------------------
  812. if ($Help) {
  813. Show-Usage
  814. return
  815. }
  816. # 5.1 is what a clean Windows 10 or 11 ships and what CI runs this against, so
  817. # it is the floor this file claims. Older is refused rather than attempted: the
  818. # .NET types above reach back further, but nothing here has ever been run there
  819. # and an install that half works is worse than one that says no. Checked before
  820. # anything is downloaded, so a machine that cannot finish is told before it
  821. # spends the bytes.
  822. if ($PSVersionTable.PSVersion.Major -lt 5) {
  823. Fail 5 @(
  824. "this script needs PowerShell 5.1 or newer, and this is $($PSVersionTable.PSVersion).",
  825. '',
  826. 'Windows 10 and 11 ship 5.1. On an older Windows, install either:',
  827. ' Windows Management Framework 5.1, or',
  828. ' PowerShell 7: https://aka.ms/powershell',
  829. '',
  830. 'Nothing was installed.'
  831. )
  832. }
  833. if (-not $Version -and $env:ANK_VERSION) { $Version = $env:ANK_VERSION }
  834. if (-not $Dir -and $env:ANK_INSTALL_DIR) { $Dir = $env:ANK_INSTALL_DIR }
  835. $BaseUrl = $env:ANK_BASE_URL
  836. if ($env:ANK_REQUIRE_PROVENANCE) { $RequireProvenance = $true }
  837. if ($BaseUrl) {
  838. if ($BaseUrl -notmatch '^https?://') {
  839. Fail 1 @(
  840. "ANK_BASE_URL must start with http:// or https://, got: $BaseUrl",
  841. '',
  842. 'Unset it to fetch from the GitHub release:',
  843. ' $env:ANK_BASE_URL = $null'
  844. )
  845. }
  846. if (-not $Version) {
  847. Fail 1 @(
  848. 'ANK_BASE_URL is set, so the version has to be named.',
  849. '',
  850. 'Only GitHub can be asked which release is the latest; a mirror cannot.',
  851. " & ([scriptblock]::Create((irm $RawUrl))) -Version v0.2.0"
  852. )
  853. }
  854. }
  855. # ---------------------------------------------------------------------------
  856. # Welcome, then install
  857. # ---------------------------------------------------------------------------
  858. # Before anything is asked of the network, which is what "before the download
  859. # starts" has to mean here: the first request this script makes is the HEAD
  860. # that resolves the latest tag, and it is below.
  861. #
  862. # Wrapped, because a host that cannot place a cursor is not a reason to fail an
  863. # install: nothing has been downloaded yet and nothing below depends on a frame
  864. # having been drawn.
  865. if (Test-HumanAtTerminal) {
  866. # The colour is turned on by the presence of a human and not by the width of
  867. # their window, which is why this is here and the width test is inside
  868. # Show-Logo: a console too narrow for the logo is still a console with a
  869. # person in front of it.
  870. Enable-Ui
  871. try { Show-Logo } catch { }
  872. }
  873. # Both of these are session state, and under `iex` the session belongs to the
  874. # caller: they are restored in the finally below rather than left changed by an
  875. # install. TLS 1.2 because 5.1 defaults to protocols GitHub no longer accepts,
  876. # and the progress bar because on 5.1 it costs more time than the download.
  877. $savedProtocol = [Net.ServicePointManager]::SecurityProtocol
  878. $savedProgress = $ProgressPreference
  879. $tmp = ''
  880. try {
  881. [Net.ServicePointManager]::SecurityProtocol = `
  882. [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
  883. $ProgressPreference = 'SilentlyContinue'
  884. $resolved = Resolve-Target
  885. $target = $resolved.Target
  886. if ($Version) {
  887. # "v0.2.0" and "0.2.0" are the same request. The tag carries the v and
  888. # the archive name does not, and making the caller know which is which
  889. # is the kind of detail a released script gets to absorb.
  890. $tag = 'v' + ($Version -replace '^v', '')
  891. } else {
  892. $tag = Resolve-LatestTag
  893. }
  894. $bare = $tag -replace '^v', ''
  895. $archive = "ank-$bare-$target.zip"
  896. $root = if ($BaseUrl) { $BaseUrl } else { $DefaultBaseUrl }
  897. $url = "$root/$tag/$archive"
  898. Say -NoNewline "$UiPad" ; Say -NoNewline "ank $tag "
  899. Say -Color $UiDim "$target"
  900. if ($resolved.Emulated) {
  901. Say 'no native arm64 build is published; Windows runs this one under emulation'
  902. }
  903. $tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("ank-install-" + [System.IO.Path]::GetRandomFileName())
  904. New-Item -ItemType Directory -Path $tmp -Force | Out-Null
  905. # The checksum first: it is the smaller of the two files, so a release that
  906. # does not carry this target says so before megabytes move. It is also the
  907. # request that answers "is this platform in this release", which is a
  908. # question the caller deserves answered rather than left as a stalled
  909. # download.
  910. $shaPath = Join-Path $tmp 'sha256'
  911. $got = Get-File -Url "$url.sha256" -OutFile $shaPath
  912. if (-not $got.Ok) {
  913. if ($got.Status -eq '404') {
  914. Fail 3 @(
  915. "$tag does not carry an archive for this platform.",
  916. '',
  917. " looked for: $archive",
  918. " at: $url",
  919. '',
  920. 'The platform is one this project builds for, so this is about the',
  921. "release and not about the machine. What $tag carries is listed at:",
  922. " $ReleasesUrl/tag/$tag",
  923. '',
  924. 'Pick a release that carries it:',
  925. " & ([scriptblock]::Create((irm $RawUrl))) -Version <version>",
  926. '',
  927. 'Nothing was installed.'
  928. )
  929. }
  930. $suffix = if ($got.Status) { " (HTTP $($got.Status))" } else { '' }
  931. Fail 3 @(
  932. "could not download the checksum for $archive$suffix.",
  933. '',
  934. " $url.sha256",
  935. '',
  936. 'Nothing was installed.'
  937. )
  938. }
  939. # sha256sum's own format, which is what release.yml publishes: the hash,
  940. # whitespace, the file name.
  941. $firstLine = (Get-Content -Path $shaPath -TotalCount 1)
  942. $expected = ''
  943. if ($firstLine) { $expected = ($firstLine.Trim() -split '\s+')[0].ToLowerInvariant() }
  944. # A captive portal answering every request with a login page is a real way
  945. # to get a .sha256 that parses into something. Sixty-four hex characters, or
  946. # this was not the release answering.
  947. if ($expected -notmatch '^[0-9a-f]{64}$') {
  948. $readBack = if ($expected) { $expected } else { '<empty>' }
  949. Fail 4 @(
  950. "the published checksum for $archive is not a SHA-256.",
  951. '',
  952. " $url.sha256",
  953. " read back: $readBack",
  954. '',
  955. 'Something other than the release answered that request. Nothing was',
  956. 'unpacked and nothing was installed.'
  957. )
  958. }
  959. $archivePath = Join-Path $tmp $archive
  960. $got = Get-File -Url $url -OutFile $archivePath
  961. if (-not $got.Ok) {
  962. $suffix = if ($got.Status) { " (HTTP $($got.Status))" } else { '' }
  963. Fail 3 @(
  964. "could not download $archive$suffix.",
  965. '',
  966. " $url",
  967. '',
  968. 'Nothing was installed.'
  969. )
  970. }
  971. $actual = Get-Sha256 -Path $archivePath
  972. # Before unpacking, and this is what the file is for. A script that
  973. # downloads an executable over the network and runs it without checking the
  974. # hash published beside it is a supply chain with a hole in the middle.
  975. #
  976. # What the check buys, stated honestly: it catches a truncated or corrupted
  977. # download, a mirror serving the wrong file, and an archive that is not the
  978. # one the release recorded. It is not a signature -- the hash comes from the
  979. # same host as the archive -- which is why the default host is GitHub over
  980. # TLS and why ANK_BASE_URL is documented as a mirror rather than as a
  981. # default.
  982. if ($expected -ne $actual) {
  983. Fail 4 @(
  984. "checksum mismatch, refusing to unpack $archive.",
  985. '',
  986. " expected: $expected",
  987. " actual: $actual",
  988. " published: $url.sha256",
  989. '',
  990. 'The download does not match the hash the release published beside it.',
  991. 'Nothing was unpacked and nothing was installed.',
  992. '',
  993. 'Retry once, in case the transfer was truncated. If it happens again, do',
  994. 'not install this archive, and say so:',
  995. " https://github.com/$Repo/security"
  996. )
  997. }
  998. Ok "checksum ok $actual"
  999. # Build provenance, which is what the checksum is not, on the terms
  1000. # install.sh states at the same place: whoever can replace an archive on
  1001. # the release page can replace its .sha256, and cannot forge the
  1002. # attestation GitHub signs for the workflow run that built it. A signed-in
  1003. # gh is asked, pinned to this repository and to that workflow, and a failure
  1004. # refuses with or without -RequireProvenance. A release at or below 0.9.4
  1005. # predates the attestations. Which check was made is said in one line.
  1006. $attestedAfter = [version]'0.9.4'
  1007. $signer = "$Repo/.github/workflows/release.yml"
  1008. $releaseNumber = $null
  1009. try { $releaseNumber = [version](($bare -split '[-+]')[0]) } catch { }
  1010. $provenance = ''
  1011. if (-not $releaseNumber -or $releaseNumber -le $attestedAfter) {
  1012. $provenance = "$tag predates build provenance"
  1013. } elseif (-not (Get-Command gh -ErrorAction SilentlyContinue)) {
  1014. $provenance = 'gh is not on PATH, so provenance was not checked'
  1015. } else {
  1016. $global:LASTEXITCODE = 0
  1017. try { & gh auth status 2>&1 | Out-Null } catch { }
  1018. if ($LASTEXITCODE -ne 0) {
  1019. $provenance = 'gh is not signed in, so provenance was not checked'
  1020. } else {
  1021. $global:LASTEXITCODE = 0
  1022. $said = @()
  1023. try {
  1024. $said = @(& gh attestation verify $archivePath --repo $Repo --signer-workflow $signer 2>&1 |
  1025. ForEach-Object { "$_" })
  1026. } catch {
  1027. $said += "$($_.Exception.Message)"
  1028. $global:LASTEXITCODE = 1
  1029. }
  1030. if ($LASTEXITCODE -ne 0) {
  1031. Say ''
  1032. foreach ($line in $said) { Say " $line" }
  1033. Fail 4 @(
  1034. "the build provenance of $archive did not verify, refusing to unpack it.",
  1035. '',
  1036. " gh attestation verify $archive --repo $Repo --signer-workflow $signer",
  1037. '',
  1038. 'The archive matches the checksum published beside it, and no attestation',
  1039. "of this repository's release workflow vouches for it. Nothing was",
  1040. 'unpacked and nothing was installed. Do not install this archive, and say so:',
  1041. " https://github.com/$Repo/security"
  1042. )
  1043. }
  1044. }
  1045. }
  1046. if ($provenance -and $RequireProvenance) {
  1047. if ($provenance -like '*predates*') {
  1048. Fail 4 @(
  1049. "-RequireProvenance: $provenance.",
  1050. '',
  1051. "Releases above v$attestedAfter carry an attestation per archive. Pick one:",
  1052. " & ([scriptblock]::Create((irm $RawUrl))) -Version <version> -RequireProvenance",
  1053. '',
  1054. 'Nothing was installed.'
  1055. )
  1056. }
  1057. Fail 5 @(
  1058. "-RequireProvenance: $provenance.",
  1059. '',
  1060. 'The check is gh attestation verify, which needs gh signed in:',
  1061. ' https://cli.github.com',
  1062. ' gh auth login',
  1063. '',
  1064. 'Nothing was installed.'
  1065. )
  1066. }
  1067. if ($provenance) {
  1068. Ok "verified: sha256 only ($provenance)"
  1069. } else {
  1070. Ok 'verified: sha256 and provenance'
  1071. }
  1072. try {
  1073. Expand-Zip -Path $archivePath -Destination $tmp
  1074. } catch {
  1075. Fail 3 @(
  1076. "could not unpack $archive.",
  1077. '',
  1078. " $($_.Exception.Message)",
  1079. '',
  1080. 'Nothing was installed.'
  1081. )
  1082. }
  1083. # The layout release.yml packages: one directory named after the archive,
  1084. # carrying the executable beside README.md, LICENSE and SKILL.md.
  1085. #
  1086. # ank.exe is required and the rest of the directory is not read at all. An
  1087. # archive published before ADR-1ea31c2f3c5a carries a second executable
  1088. # there, and the answer to it is the same as the answer to README.md: it is
  1089. # not what was asked for, so it is not moved anywhere. A check that refused
  1090. # an archive holding more than this would refuse every release published so
  1091. # far.
  1092. $unpacked = Join-Path $tmp "ank-$bare-$target"
  1093. $binary = Join-Path $unpacked 'ank.exe'
  1094. if (-not (Test-Path -Path $binary -PathType Leaf)) {
  1095. Fail 3 @(
  1096. "$archive does not contain ank.exe where this script expected it.",
  1097. '',
  1098. " looked for: ank-$bare-$target\ank.exe",
  1099. '',
  1100. 'Nothing was installed.'
  1101. )
  1102. }
  1103. if (-not $Dir) {
  1104. if (-not $env:LOCALAPPDATA) {
  1105. Fail 1 @(
  1106. 'LOCALAPPDATA is not set, so there is no default install directory.',
  1107. '',
  1108. 'Name one:',
  1109. " & ([scriptblock]::Create((irm $RawUrl))) -Dir C:\tools\ank"
  1110. )
  1111. }
  1112. $Dir = Join-Path $env:LOCALAPPDATA 'Programs\ank'
  1113. }
  1114. try {
  1115. New-Item -ItemType Directory -Path $Dir -Force -ErrorAction Stop | Out-Null
  1116. } catch {
  1117. Fail 1 @(
  1118. "could not create $Dir.",
  1119. '',
  1120. " $($_.Exception.Message)",
  1121. '',
  1122. 'Install somewhere writable, or run this from a shell that can write there:',
  1123. " & ([scriptblock]::Create((irm $RawUrl))) -Dir `$env:LOCALAPPDATA\Programs\ank"
  1124. )
  1125. }
  1126. $destination = Join-Path $Dir 'ank.exe'
  1127. $failure = Move-IntoPlace -Source $binary -Destination $destination -Name 'ank.exe'
  1128. if ($failure) {
  1129. Fail 1 @(
  1130. "could not write $destination.",
  1131. '',
  1132. " $failure",
  1133. '',
  1134. 'Something is holding the file open and it could not be renamed either.',
  1135. 'Close any shell running ank and try again.',
  1136. '',
  1137. 'Nothing was installed.'
  1138. )
  1139. }
  1140. $installedVersion = ''
  1141. try {
  1142. $installedVersion = (& $destination --version 2>$null | Select-Object -First 1)
  1143. } catch {
  1144. $installedVersion = ''
  1145. }
  1146. Say ''
  1147. Ok "installed $destination"
  1148. if ($installedVersion) { Say -Color $UiDim "$UiPad$UiPad $installedVersion" }
  1149. # The last way left to leave a caller without a working `ank`: a binary in a
  1150. # directory nothing looks in. Naming the command to run is the difference
  1151. # between an install that worked and an install that appears not to have
  1152. # run. The user PATH is not written by this script: it is a persistent
  1153. # change to the caller's account, and an installer that makes one without
  1154. # being asked is one they cannot undo by deleting what it installed.
  1155. $userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
  1156. $onPath = ($env:Path -split ';' | Where-Object { $_.TrimEnd('\') -ieq $Dir.TrimEnd('\') })
  1157. if ($onPath) {
  1158. Say ''
  1159. Say -NoNewline "$UiPad$Dir is on your PATH. Run: "
  1160. Say -Color $UiCyan 'ank help'
  1161. } else {
  1162. Say ''
  1163. Say "$UiPad$Dir is not on your PATH, so ``ank`` is not a command yet."
  1164. Say "${UiPad}Add it for your account by running this once:"
  1165. Say ''
  1166. Say -Color $UiCyan "$UiPad [Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path','User') + ';$Dir', 'User')"
  1167. Say ''
  1168. Say "${UiPad}then open a new terminal. In this one:"
  1169. Say ''
  1170. Say -Color $UiCyan "$UiPad `$env:Path += ';$Dir'"
  1171. if ($userPath -and $userPath.Length -gt 1800) {
  1172. Say ''
  1173. Say "${UiPad}Your user PATH is close to the length Windows truncates at, so check it"
  1174. Say "${UiPad}after adding: a truncated PATH loses entries other tools put there."
  1175. }
  1176. }
  1177. # Wrapped, and it is the whole guarantee in two lines rather than one.
  1178. #
  1179. # The try is the half install.sh spells `offer_skills || :`: a question
  1180. # asked after a successful install may not turn that install into a
  1181. # failure, so nothing thrown in there gets out of here.
  1182. #
  1183. # The stamp is the half that has no counterpart in install.sh, and it is
  1184. # the one that would have been missed by reading. `pwsh -File install.ps1`
  1185. # exits with $LASTEXITCODE, which every native command run above sets: with
  1186. # nothing here, a skill step that failed would silently become this script's
  1187. # exit code and the caller would read a green install as red. Assigned in the
  1188. # global scope, because an assignment inside a script writes a script-local
  1189. # variable that shadows it and changes nothing the host reads.
  1190. try { Invoke-SkillOffer -Ank $destination } catch { }
  1191. try { Invoke-AdoptionOffer } catch { }
  1192. $global:LASTEXITCODE = 0
  1193. } finally {
  1194. if ($tmp -and (Test-Path -Path $tmp)) {
  1195. Remove-Item -Path $tmp -Recurse -Force -ErrorAction SilentlyContinue
  1196. }
  1197. $ProgressPreference = $savedProgress
  1198. [Net.ServicePointManager]::SecurityProtocol = $savedProtocol
  1199. }
install.sh · Bundled script · 1,221 lines · 2 findings marked
  1. #!/bin/sh
  2. #
  3. # Install ank from a GitHub release.
  4. #
  5. # curl -fsSL https://raw.githubusercontent.com/haksolot/ank/main/install.sh | sh
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 5 on GitHub
  6. # curl -fsSL https://raw.githubusercontent.com/haksolot/ank/main/install.sh | sh -s -- --version v0.2.0
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 6 on GitHub
  7. #
  8. # One executable lands: `ank`. The protocol surface and the watcher are verbs of
  9. # it (ADR-1ea31c2f3c5a), so there is no second file for this script to place and
  10. # no way for one to fail to arrive.
  11. #
  12. # `--version` reaches releases published before that was true, whose archive
  13. # carries a second executable beside `ank`. Nothing here asks: the archive is
  14. # unpacked, `ank` is taken out of it, and whatever else the directory holds goes
  15. # with the temporary directory. So an old release installs the one file this
  16. # script promises, by the same code path a new one does -- an installer that
  17. # only worked on releases that do not exist yet would not be a working
  18. # installer.
  19. #
  20. # POSIX sh and no bashisms, deliberately. This is the channel for the Linux
  21. # distribution that will never have a native package, and the smallest of those
  22. # ship busybox ash with no bash at all. The binary is a static musl build, so
  23. # one archive covers every distribution -- but only if the script that fetches
  24. # it runs there too.
  25. #
  26. # Exit codes, so a caller can branch on the failure rather than on the message:
  27. #
  28. # 1 usage, or a directory that cannot be written
  29. # 2 unsupported platform
  30. # 3 the download failed, or the release does not carry this archive
  31. # 4 the checksum did not match the one the release published, or the
  32. # build provenance was checked and did not verify
  33. # 5 a tool this script needs is missing, gh included under
  34. # --require-provenance
  35. #
  36. # --no-welcome, or ANK_NO_WELCOME in the environment, turns off everything this
  37. # script draws for a human and everything it asks one, and leaves only the
  38. # lines a machine reads. It is absent from the list above on purpose: the
  39. # welcome is drawn before the first request goes out and the offer comes after
  40. # the binary is on disk and verified, so neither is on the path to any of them
  41. # -- a flag able to change one of these five codes would be a flag that made
  42. # the install depend on it.
  43. #
  44. set -eu
  45. repo="haksolot/ank"
  46. raw_url="https://raw.githubusercontent.com/${repo}/main/install.sh"
  47. releases_url="https://github.com/${repo}/releases"
  48. default_base_url="${releases_url}/download"
  49. # --------------------------------------------------------------------------
  50. # Output
  51. # --------------------------------------------------------------------------
  52. # Everything informational goes to stderr, because the interesting use of this
  53. # script is `curl ... | sh` and the caller may well be reading stdout.
  54. say() {
  55. printf '%s\n' "$*" >&2
  56. }
  57. # Colour and the marker, behind the gate the logo is drawn behind. Empty until
  58. # ui_enable runs, which is what keeps ADR-5fbd99bf6fd5's promise to a caller
  59. # with nobody at the end of it: a pipe reads the bytes it read before this file
  60. # learned about either.
  61. #
  62. # Every call site below spells the sequences out rather than asking a function
  63. # for them, so a line that is half plain and half painted is one string and not
  64. # a concatenation of three -- and the plain reading of it, with every variable
  65. # empty, is the line that used to be there.
  66. ui_off="" ui_bold="" ui_dim="" ui_cyan="" ui_green=""
  67. ui_pad="" ui_tick=""
  68. # `ok <line>`: a step that finished. The marker and the indent are drawn for a
  69. # person and for nobody else -- what a pipe reads is the sentence alone, which
  70. # is why the two live in variables rather than in the format string.
  71. ok() {
  72. say "${ui_pad}${ui_green}${ui_tick}${ui_off}$*"
  73. }
  74. # `die <code> <line>...`: the code carries the kind of failure, the lines carry
  75. # what to do next. Nothing here ever ends in silence -- that is the one thing
  76. # an install script cannot do, since the caller is otherwise left with no
  77. # binary and no idea why.
  78. die() {
  79. die_code=$1
  80. shift
  81. say "ank: $1"
  82. shift
  83. for die_line in "$@"; do
  84. say "$die_line"
  85. done
  86. exit "$die_code"
  87. }
  88. # --------------------------------------------------------------------------
  89. # Welcome
  90. # --------------------------------------------------------------------------
  91. # The logo, from assets/ank.svg read as pixels: twenty-four columns by ten
  92. # rows, one cell per pixel column and one row per pair of pixel rows, which is
  93. # the ratio that makes a terminal cell square. That file is the reference for
  94. # the shape and nothing here reads it: an installer that fetches a logo before
  95. # it fetches the binary is an installer with a second way to fail before doing
  96. # anything useful, so the shape is bytes in this file.
  97. #
  98. # U+2588 where the locale says UTF-8, `#` where it does not, decided once in
  99. # logo_charset. The hedge is the one the shebang makes -- this runs on busybox
  100. # under a locale nobody chose, and a logo that arrives as question marks is
  101. # worse than no logo at all -- but a locale that announces UTF-8 is a locale
  102. # that can draw a block, and the block is the whole difference between a logo
  103. # and a fence of hashes.
  104. #
  105. # \033 and not \e: the octal escape is the one POSIX printf guarantees, and \e
  106. # is a bashism in a file that has none.
  107. logo_esc=$(printf '\033')
  108. # Eleven spaces: columns 0 to 10, which is what stands to the left of the stem
  109. # on a row whose leg has not grown yet. Every such row is the same width, so
  110. # the padding is a constant rather than something measured -- ${#s} counts
  111. # bytes, and the moment the cell is U+2588 that is three times the answer.
  112. logo_pad11=" "
  113. # The cell, and the three runs the shape is made of, built once. A frame is
  114. # drawn seventeen times and must not repeat this work inside the loop.
  115. logo_charset() {
  116. case "${LC_ALL:-${LC_CTYPE:-${LANG:-}}}" in
  117. *UTF-8* | *utf-8* | *UTF8* | *utf8*) logo_cell='█' ;;
  118. *) logo_cell='#' ;;
  119. esac
  120. logo_b2=$(logo_run 2)
  121. logo_b4=$(logo_run 4)
  122. logo_b14=$(logo_run 14)
  123. }
  124. logo_run() {
  125. logo_run_n=$1
  126. logo_run_s=""
  127. while [ "$logo_run_n" -gt 0 ]; do
  128. logo_run_s="${logo_run_s}${logo_cell}"
  129. logo_run_n=$((logo_run_n - 1))
  130. done
  131. printf '%s' "$logo_run_s"
  132. }
  133. # The mark carries no colour of its own. assets/ank.svg is #1f2328 and
  134. # assets/ank-dark.svg is #e6edf3 -- the same shape, black on a light ground and
  135. # white on a dark one -- and \033[39m is how a terminal spells that: the
  136. # foreground the reader already chose. A hue picked here would be a third logo
  137. # neither asset agrees with, and would be the one thing on the screen that does
  138. # not belong to the person running the installer.
  139. #
  140. # So the animation is built on the one axis that survives not knowing the
  141. # background: dim against normal. Brighter does not survive it -- bold on a
  142. # glyph that is already a solid block does nothing at all in a terminal that
  143. # does not render bold as bright, and white on a light ground is invisible. A
  144. # part therefore arrives dim and settles, and the shape blinks by going dim,
  145. # which reads the same on either ground.
  146. #
  147. # NO_COLOR empties all four rather than branching at each of the places they are
  148. # used, so a run without colour draws the same shape through the same code, on
  149. # the growth alone.
  150. logo_palette() {
  151. if [ -n "${NO_COLOR:-}" ]; then
  152. logo_lit="" logo_soft="" logo_name="" logo_off=""
  153. return
  154. fi
  155. logo_lit="${logo_esc}[39m"
  156. logo_soft="${logo_esc}[2;39m"
  157. logo_name="${logo_esc}[1m"
  158. logo_off="${logo_esc}[0m"
  159. }
  160. # The lines the install prints after the logo, which are not the mark and may
  161. # therefore carry a hue: bold for what landed, dim for what is incidental, cyan
  162. # for a command the reader is meant to run, green for a step that finished. Five
  163. # of the eight the binary allows itself, and the mark still uses none of them.
  164. #
  165. # The marker is U+2713 where the locale says
  166. # UTF-8 and `- ` where it does not, on the reasoning logo_charset is written
  167. # out for: a tick that arrives as a question mark is worse than no tick.
  168. #
  169. # The marker survives NO_COLOR, and that is the point of it being a character.
  170. # Nothing here is carried by colour alone -- take every sequence away and the
  171. # steps are still marked, and still say what they say.
  172. ui_enable() {
  173. ui_pad=" "
  174. ui_tick="- "
  175. case "${LC_ALL:-${LC_CTYPE:-${LANG:-}}}" in
  176. *UTF-8* | *utf-8* | *UTF8* | *utf8*) ui_tick="✓ " ;;
  177. esac
  178. [ -z "${NO_COLOR:-}" ] || return 0
  179. ui_off="${logo_esc}[0m"
  180. ui_bold="${logo_esc}[1m"
  181. ui_dim="${logo_esc}[2m"
  182. ui_cyan="${logo_esc}[36m"
  183. ui_green="${logo_esc}[32m"
  184. }
  185. # One of rows 6 to 9: `<pad><leg><gap><stem><gap><leg>`, where a part that has
  186. # not grown yet gives up its columns to the eleven-space pad, so the parts that
  187. # have stay where they are. The trailing pad is never drawn -- \033[K ends the
  188. # line, and spaces that reach the right edge of a narrow window wrap it.
  189. logo_band() {
  190. lb_legs=$1 lb_legs_at=$2 lb_stem=$3 lb_stem_at=$4
  191. lb_run=$5 lb_gap=$6 lb_legs_c=$7 lb_stem_c=$8
  192. if [ "$lb_legs" -ge "$lb_legs_at" ]; then
  193. lb_left=" ${lb_legs_c}${lb_run}${logo_off}${lb_gap}"
  194. lb_right="${lb_gap}${lb_legs_c}${lb_run}${logo_off}"
  195. else
  196. lb_left=$logo_pad11
  197. lb_right=""
  198. fi
  199. if [ "$lb_stem" -ge "$lb_stem_at" ]; then
  200. lb_mid="${lb_stem_c}${logo_b2}${logo_off}"
  201. elif [ -n "$lb_right" ]; then
  202. lb_mid=" "
  203. else
  204. lb_left="" lb_mid=""
  205. fi
  206. printf '%s%s%s' "$lb_left" "$lb_mid" "$lb_right"
  207. }
  208. # One frame, whole, in one write. Twelve separate writes to a terminal are
  209. # twelve chances for a person to catch the logo half-drawn, and that flicker is
  210. # what makes an animation look cheap.
  211. #
  212. # The arguments are the state of the build and not a frame number: base is on or
  213. # off, legs and stem are how many of their rows have grown, loop is on or off,
  214. # soft names the part still arriving this frame, name is the wordmark. A
  215. # timeline written as states can be re-timed without recomputing which row is
  216. # which.
  217. #
  218. # Every sequence is closed on the run that opened it. A frame that ends with one
  219. # still open is a terminal somebody has to repair with `reset`.
  220. logo_frame() {
  221. lf_base=$1 lf_legs=$2 lf_stem=$3 lf_loop=$4 lf_soft=$5 lf_name=$6
  222. lf_loop_c=$logo_lit lf_stem_c=$logo_lit lf_legs_c=$logo_lit lf_base_c=$logo_lit
  223. case $lf_soft in
  224. loop) lf_loop_c=$logo_soft ;;
  225. stem) lf_stem_c=$logo_soft ;;
  226. legs) lf_legs_c=$logo_soft ;;
  227. base) lf_base_c=$logo_soft ;;
  228. all)
  229. lf_loop_c=$logo_soft lf_stem_c=$logo_soft
  230. lf_legs_c=$logo_soft lf_base_c=$logo_soft
  231. ;;
  232. esac
  233. # Rows 1 and 4, then 2 and 3: the loop is columns 10-13, then 8-9 with 14-15.
  234. if [ "$lf_loop" = 1 ]; then
  235. lf_r1=" ${lf_loop_c}${logo_b4}${logo_off}"
  236. lf_r2=" ${lf_loop_c}${logo_b2}${logo_off} ${lf_loop_c}${logo_b2}${logo_off}"
  237. else
  238. lf_r1="" lf_r2=""
  239. fi
  240. # Row 5, the stem alone, the last of its five rows to grow.
  241. if [ "$lf_stem" -ge 5 ]; then
  242. lf_r5=" ${lf_stem_c}${logo_b2}${logo_off}"
  243. else
  244. lf_r5=""
  245. fi
  246. # Rows 6-9 carry a leg on each side and the stem between them, and the three
  247. # arrive at different moments.
  248. lf_r6=$(logo_band "$lf_legs" 4 "$lf_stem" 4 "$logo_b4" " " "$lf_legs_c" "$lf_stem_c")
  249. lf_r7=$(logo_band "$lf_legs" 3 "$lf_stem" 3 "$logo_b2" " " "$lf_legs_c" "$lf_stem_c")
  250. lf_r8=$(logo_band "$lf_legs" 2 "$lf_stem" 2 "$logo_b2" " " "$lf_legs_c" "$lf_stem_c")
  251. lf_r9=$(logo_band "$lf_legs" 1 "$lf_stem" 1 "$logo_b2" " " "$lf_legs_c" "$lf_stem_c")
  252. # Row 10, the base, columns 5-18.
  253. if [ "$lf_base" = 1 ]; then
  254. lf_r10=" ${lf_base_c}${logo_b14}${logo_off}"
  255. else
  256. lf_r10=""
  257. fi
  258. if [ "$lf_name" = 1 ]; then
  259. lf_r12=" ${logo_name}ank${logo_off}"
  260. else
  261. lf_r12=""
  262. fi
  263. # \033[K clears what the previous frame left to the right of each line, which
  264. # is what lets a row shrink. Twelve lines every time, including the empty
  265. # ones: the redraw moves back over a fixed block, and a frame that were
  266. # shorter would leave the tail of the one before it on the screen.
  267. printf '%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n\033[K\n%s\033[K\n' \
  268. "$lf_r1" "$lf_r2" "$lf_r2" "$lf_r1" "$lf_r5" \
  269. "$lf_r6" "$lf_r7" "$lf_r8" "$lf_r9" "$lf_r10" "$lf_r12" >&2
  270. }
  271. # A frame, its delay, and the move back over the block it drew, so the caller's
  272. # timeline reads as states and never as cursor arithmetic. The last frame is
  273. # drawn by the caller instead, because it is the one that has to stay.
  274. logo_step() {
  275. logo_frame "$1" "$2" "$3" "$4" "$5" 0
  276. [ -z "$logo_delay" ] || sleep "$logo_delay"
  277. printf '\033[12A' >&2
  278. }
  279. # Bottom up: the base arrives dim and settles, the legs and then the stem grow
  280. # out of it a row at a time, the loop crowns them, and the whole shape blinks
  281. # twice before the name appears. That last beat is what the animation exists for
  282. # -- it costs the time it takes to read the name of the tool and not a second
  283. # more.
  284. draw_logo() {
  285. logo_charset
  286. logo_palette
  287. # POSIX sleep takes an integer, and every sleep this script is likely to meet
  288. # -- coreutils, BSD, busybox built with the fancy option -- takes a fraction.
  289. # The ones that do not are told apart by asking rather than by guessing:
  290. # without a delay the frames still draw, in the order they draw, as fast as
  291. # the terminal will take them.
  292. logo_fast=0.045 logo_beat=0.10 logo_hold=0.45
  293. sleep 0.01 2>/dev/null || { logo_fast="" logo_beat="" logo_hold=""; }
  294. # The cursor would otherwise blink in the middle of the drawing. Restored on
  295. # the way out and on the two signals a human sends, because a terminal left
  296. # with an invisible cursor is a terminal somebody has to repair with `reset`.
  297. # The reset travels with it: a ^C between the opening of a colour and its
  298. # close would otherwise leave the shell prompt dim.
  299. trap 'printf "%s[0m%s[?25h\n" "$logo_esc" "$logo_esc" >&2; exit 130' INT
  300. trap 'printf "%s[0m%s[?25h\n" "$logo_esc" "$logo_esc" >&2; exit 143' TERM
  301. printf '\033[?25l' >&2
  302. # The two parts that appear whole -- the base and the loop -- come in dim and
  303. # settle. The two that grow do not: growing a row at a time is already motion,
  304. # and dimming it as well would say the same thing twice.
  305. #
  306. # base legs stem loop soft
  307. logo_delay=$logo_beat
  308. logo_step 1 0 0 0 base
  309. logo_step 1 0 0 0 none
  310. logo_delay=$logo_fast
  311. logo_step 1 1 0 0 none
  312. logo_step 1 2 0 0 none
  313. logo_step 1 3 0 0 none
  314. logo_step 1 4 0 0 none
  315. logo_step 1 4 1 0 none
  316. logo_step 1 4 2 0 none
  317. logo_step 1 4 3 0 none
  318. logo_step 1 4 4 0 none
  319. logo_step 1 4 5 0 none
  320. logo_delay=$logo_beat
  321. logo_step 1 4 5 1 loop
  322. logo_step 1 4 5 1 none
  323. logo_delay=$logo_fast
  324. logo_step 1 4 5 1 all
  325. logo_step 1 4 5 1 none
  326. logo_step 1 4 5 1 all
  327. # The name, on the frame that stays. No move back after it, so what the
  328. # install says next begins under the logo rather than over it.
  329. logo_frame 1 4 5 1 none 1
  330. [ -z "$logo_hold" ] || sleep "$logo_hold"
  331. # The cursor comes back first and the blank line after it, so the last byte
  332. # this function writes is a newline: whatever the install says next starts on
  333. # a line of its own rather than behind an escape sequence.
  334. printf '\033[?25h\n' >&2
  335. trap - INT TERM
  336. }
  337. # ADR-5fbd99bf6fd5 read as an absence: where no human is looking, this script
  338. # draws nothing at all and asks nothing at all.
  339. #
  340. # Both streams are tested and not only one. Under `curl ... | sh` stdin is the
  341. # script and both of the others are the terminal, which is the case that must
  342. # animate; under `sh install.sh > install.log` stderr is still a terminal, and
  343. # a log file full of cursor movements is exactly the noise this must never
  344. # produce. /dev/tty is the third test and the one the decision names: no
  345. # controlling terminal means a provisioning script, a Dockerfile or a runner,
  346. # whatever the streams happen to say.
  347. #
  348. # The logo and the offer read this same answer, which is what makes
  349. # --no-welcome and an interactive run that declined everything leave the same
  350. # machine behind: one predicate, so there is no second gate to disagree with
  351. # this one.
  352. human_at_terminal() {
  353. [ "$no_welcome" = no ] || return 1
  354. [ -t 1 ] || return 1
  355. [ -t 2 ] || return 1
  356. # A runner sets this, and some runner images hand their steps a pty.
  357. [ -z "${CI:-}" ] || return 1
  358. # A terminal that says it cannot move a cursor is taken at its word.
  359. case "${TERM:-}" in
  360. "" | dumb) return 1 ;;
  361. esac
  362. # A subshell: a redirection that fails on a special builtin is fatal to the
  363. # shell itself, and this test exists to be answered no.
  364. ( : > /dev/tty ) 2>/dev/null || return 1
  365. }
  366. # The width is about the block of art and about nothing else, so it is here and
  367. # not above: a window too narrow to hold the logo is still a window with a
  368. # person in front of it, and a question fits in twenty columns.
  369. welcome_wanted() {
  370. human_at_terminal || return 1
  371. # A window narrower than the art wraps every line, and a block that is taller
  372. # than twelve rows is a block the redraw moves back over the middle of. Asked
  373. # of tput, and only believed when it answers a number: a machine without it
  374. # is a machine this refuses to guess about in the direction of drawing.
  375. logo_cols=$(tput cols 2>/dev/null) || logo_cols=""
  376. case "$logo_cols" in
  377. "" | *[!0-9]*) : ;;
  378. *) [ "$logo_cols" -ge 24 ] || return 1 ;;
  379. esac
  380. }
  381. # --------------------------------------------------------------------------
  382. # Platforms
  383. # --------------------------------------------------------------------------
  384. # The targets release.yml builds, minus Windows, which ships a .zip that this
  385. # script has no business unpacking. Written once and read by both the refusal
  386. # and the help text: a list that says one thing when it refuses and another
  387. # when it is asked is worse than no list at all.
  388. supported_lines() {
  389. cat <<'EOF'
  390. Linux x86_64 x86_64-unknown-linux-musl
  391. Linux arm64 aarch64-unknown-linux-musl
  392. Darwin arm64 aarch64-apple-darwin
  393. Darwin x86_64 x86_64-apple-darwin
  394. EOF
  395. }
  396. usage() {
  397. cat >&2 <<EOF
  398. install ank from a GitHub release
  399. One executable lands in the install directory: ank. The protocol surface and
  400. the watcher are verbs of it -- ank mcp, ank watch -- so there is nothing
  401. further to fetch and nothing further to configure a client against.
  402. usage:
  403. install.sh [--version <version>] [--dir <path>]
  404. curl -fsSL ${raw_url} | sh
  405. curl -fsSL ${raw_url} | sh -s -- --version v0.2.0
  406. options:
  407. --version <version> install this release instead of the latest one;
  408. "v0.2.0" and "0.2.0" both work
  409. --dir <path> install into <path> instead of \$HOME/.local/bin
  410. --no-welcome draw nothing and ask nothing; install exactly what an
  411. interactive run that declined every offer installs
  412. --require-provenance refuse unless gh verifies the archive's build
  413. provenance; without it, provenance is checked when a
  414. signed-in gh is on PATH and the checksum stands alone
  415. otherwise
  416. -h, --help print this and exit
  417. environment:
  418. ANK_VERSION same as --version
  419. ANK_INSTALL_DIR same as --dir
  420. ANK_NO_WELCOME same as --no-welcome, for a caller that pipes this
  421. script into sh and cannot pass an argument to it
  422. ANK_BASE_URL where the archives are fetched from, for a mirror or a
  423. staged release; requires --version, since only GitHub
  424. can be asked which release is the latest
  425. ANK_REQUIRE_PROVENANCE
  426. same as --require-provenance
  427. platforms:
  428. $(supported_lines)
  429. Windows is published as a .zip and this script does not install it:
  430. ${releases_url}
  431. the two questions:
  432. With a terminal attached, once ank is installed and verified, this asks
  433. two things and nothing else. The first offers to run:
  434. ank skills --install
  435. which teaches an agent how to use ank. The second offers to print three
  436. prompts that adopt ank in a repository that already has code and no
  437. .ank; they are in docs/quickstart.md too, and printing them writes
  438. nothing anywhere.
  439. Enter accepts each, declining either does nothing at all, and nothing
  440. either does can change any of the codes below.
  441. exit codes:
  442. 1 usage 2 unsupported platform 3 download 4 checksum or provenance
  443. 5 missing tool
  444. EOF
  445. }
  446. # Sets \$target, or refuses naming the pair it saw. uname -m is normalised
  447. # first, because one machine answers differently depending on the distribution:
  448. # amd64 and x86_64 are one target, aarch64 and arm64 are another.
  449. detect_target() {
  450. detect_os=$(uname -s 2>/dev/null) || detect_os=unknown
  451. detect_raw=$(uname -m 2>/dev/null) || detect_raw=unknown
  452. detect_arch=$detect_raw
  453. case "$detect_arch" in
  454. x86_64 | amd64) detect_arch=x86_64 ;;
  455. aarch64 | arm64) detect_arch=arm64 ;;
  456. esac
  457. case "${detect_os}/${detect_arch}" in
  458. Linux/x86_64) target=x86_64-unknown-linux-musl ;;
  459. Linux/arm64) target=aarch64-unknown-linux-musl ;;
  460. Darwin/arm64) target=aarch64-apple-darwin ;;
  461. Darwin/x86_64) target=x86_64-apple-darwin ;;
  462. *)
  463. say "ank: no release archive for ${detect_os}/${detect_arch}."
  464. say ""
  465. say "uname reported: ${detect_os} ${detect_raw}"
  466. say ""
  467. say "The release carries these:"
  468. supported_lines >&2
  469. say ""
  470. say "Windows is published as a .zip and this script does not install it."
  471. say "Everything the release carries is listed at:"
  472. say " ${releases_url}"
  473. say ""
  474. say "Nothing was installed."
  475. exit 2
  476. ;;
  477. esac
  478. }
  479. # --------------------------------------------------------------------------
  480. # Tools
  481. # --------------------------------------------------------------------------
  482. have() {
  483. command -v "$1" >/dev/null 2>&1
  484. }
  485. # curl or wget, whichever is there. Both are missing often enough on a minimal
  486. # container image that naming the two that would work is worth the lines.
  487. pick_downloader() {
  488. if have curl; then
  489. downloader=curl
  490. elif have wget; then
  491. downloader=wget
  492. else
  493. die 5 "neither curl nor wget is installed, so nothing can be downloaded." \
  494. "" \
  495. "Install one of them and run this again:" \
  496. " apt-get install -y curl # debian, ubuntu" \
  497. " apk add curl # alpine" \
  498. " dnf install -y curl # fedora, rhel"
  499. fi
  500. }
  501. # sha256sum on Linux, shasum on macOS, openssl as the fallback that is on
  502. # nearly everything else. If none of the three is present the script stops
  503. # here rather than installing unverified: skipping the check is the failure
  504. # this whole file is shaped to avoid, so it is not allowed to be the thing
  505. # that degrades quietly.
  506. pick_sha_tool() {
  507. if have sha256sum; then
  508. sha_tool=sha256sum
  509. elif have shasum; then
  510. sha_tool=shasum
  511. elif have openssl; then
  512. sha_tool=openssl
  513. else
  514. die 5 "no way to compute a SHA-256 on this machine." \
  515. "" \
  516. "The release publishes a .sha256 beside every archive and this script" \
  517. "refuses to unpack one it could not verify. Install any of these:" \
  518. " sha256sum (coreutils), shasum (perl), openssl" \
  519. "" \
  520. "Nothing was installed."
  521. fi
  522. }
  523. sha256_of() {
  524. case "$sha_tool" in
  525. sha256sum) sha256sum "$1" | awk '{print $1}' ;;
  526. shasum) shasum -a 256 "$1" | awk '{print $1}' ;;
  527. openssl) openssl dgst -sha256 "$1" | awk '{print $NF}' ;;
  528. esac
  529. }
  530. lower() {
  531. printf '%s' "$1" | tr '[:upper:]' '[:lower:]'
  532. }
  533. # `newer_than <a> <b>`: whether release a is above release b, read as
  534. # MAJOR.MINOR.PATCH with any prerelease or build suffix set aside. awk rather
  535. # than `sort -V`, which busybox and macOS do not both have.
  536. newer_than() {
  537. awk -v a="${1%%[-+]*}" -v b="${2%%[-+]*}" 'BEGIN {
  538. split(a, x, "."); split(b, y, ".")
  539. for (i = 1; i <= 3; i++) {
  540. if (x[i] + 0 > y[i] + 0) exit 0
  541. if (x[i] + 0 < y[i] + 0) exit 1
  542. }
  543. exit 1
  544. }'
  545. }
  546. # --------------------------------------------------------------------------
  547. # Downloading
  548. # --------------------------------------------------------------------------
  549. # `fetch <url> <path>`. Returns non-zero on failure and leaves the HTTP status
  550. # in \$fetch_status when it has one, because "this release does not carry that
  551. # archive" and "the network is down" are different messages and the 404 is
  552. # what tells them apart.
  553. fetch() {
  554. fetch_url=$1
  555. fetch_out=$2
  556. fetch_status=""
  557. if [ "$downloader" = curl ]; then
  558. # No -f: with it curl returns non-zero and the status is harder to read
  559. # back out. The status is checked here instead, which is the same
  560. # guarantee with a better message.
  561. fetch_status=$(curl -sSL --retry 3 --retry-delay 1 \
  562. -o "$fetch_out" -w '%{http_code}' "$fetch_url" 2>/dev/null) || fetch_status=""
  563. case "$fetch_status" in
  564. 2??) return 0 ;;
  565. *) return 1 ;;
  566. esac
  567. else
  568. # wget does not hand the status back, so the caller falls through to the
  569. # general message. Parsing wget's stderr for it is not more reliable than
  570. # saying less.
  571. wget -q -O "$fetch_out" "$fetch_url" 2>/dev/null || return 1
  572. return 0
  573. fi
  574. }
  575. # The tag of the latest release, read off the redirect rather than through the
  576. # API: /releases/latest redirects to /releases/tag/<tag>, which costs no rate
  577. # limit, where api.github.com allows sixty unauthenticated calls an hour per
  578. # address and a shared CI runner or an office NAT can be out of them before
  579. # anyone types this.
  580. resolve_latest() {
  581. if [ "$downloader" = curl ]; then
  582. resolved=$(curl -sSL -o /dev/null -w '%{url_effective}' \
  583. "${releases_url}/latest" 2>/dev/null) || resolved=""
  584. tag=${resolved##*/}
  585. else
  586. # wget does not report the URL it landed on, so the one place the API is
  587. # called is here, on the machine that has no curl.
  588. tag=$(wget -q -O - "https://api.github.com/repos/${repo}/releases/latest" 2>/dev/null |
  589. sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' |
  590. head -1) || tag=""
  591. fi
  592. case "$tag" in
  593. v*) : ;;
  594. *)
  595. die 3 "could not work out which release is the latest." \
  596. "" \
  597. "Name one instead:" \
  598. " install.sh --version v0.2.0" \
  599. "" \
  600. "The releases are listed at:" \
  601. " ${releases_url}"
  602. ;;
  603. esac
  604. }
  605. # --------------------------------------------------------------------------
  606. # Arguments
  607. # --------------------------------------------------------------------------
  608. version=${ANK_VERSION:-}
  609. install_dir=${ANK_INSTALL_DIR:-}
  610. base_url=${ANK_BASE_URL:-}
  611. no_welcome=no
  612. [ -z "${ANK_NO_WELCOME:-}" ] || no_welcome=yes
  613. require_provenance=no
  614. [ -z "${ANK_REQUIRE_PROVENANCE:-}" ] || require_provenance=yes
  615. while [ $# -gt 0 ]; do
  616. case "$1" in
  617. --version)
  618. [ $# -ge 2 ] ||
  619. die 1 "--version needs a value." "" " install.sh --version v0.2.0"
  620. version=$2
  621. shift 2
  622. ;;
  623. --version=*)
  624. version=${1#--version=}
  625. shift
  626. ;;
  627. --dir)
  628. [ $# -ge 2 ] ||
  629. die 1 "--dir needs a value." "" " install.sh --dir \$HOME/.local/bin"
  630. install_dir=$2
  631. shift 2
  632. ;;
  633. --dir=*)
  634. install_dir=${1#--dir=}
  635. shift
  636. ;;
  637. --no-welcome)
  638. no_welcome=yes
  639. shift
  640. ;;
  641. --require-provenance)
  642. require_provenance=yes
  643. shift
  644. ;;
  645. -h | --help)
  646. usage
  647. exit 0
  648. ;;
  649. *)
  650. die 1 "unknown option: $1" \
  651. "" \
  652. "Run it with --help to see what it takes:" \
  653. " install.sh --help"
  654. ;;
  655. esac
  656. done
  657. if [ -n "$base_url" ]; then
  658. case "$base_url" in
  659. http://* | https://*) : ;;
  660. *)
  661. die 1 "ANK_BASE_URL must start with http:// or https://, got: ${base_url}" \
  662. "" \
  663. "Unset it to fetch from the GitHub release:" \
  664. " unset ANK_BASE_URL"
  665. ;;
  666. esac
  667. if [ -z "$version" ]; then
  668. die 1 "ANK_BASE_URL is set, so the version has to be named." \
  669. "" \
  670. "Only GitHub can be asked which release is the latest; a mirror cannot." \
  671. " install.sh --version v0.2.0"
  672. fi
  673. fi
  674. # --------------------------------------------------------------------------
  675. # Install
  676. # --------------------------------------------------------------------------
  677. # Before anything is asked of the network, which is what "before the download
  678. # starts" has to mean here: the first request this script makes is the redirect
  679. # that resolves the latest tag, and it is below.
  680. # The colour is turned on by the presence of a human and not by the width of
  681. # their window: a terminal too narrow for the logo is still a terminal, and the
  682. # sentence it is too narrow for is the one nobody wrote yet.
  683. if human_at_terminal; then
  684. ui_enable
  685. fi
  686. if welcome_wanted; then
  687. draw_logo
  688. fi
  689. pick_downloader
  690. pick_sha_tool
  691. detect_target
  692. # The second form is BSD mktemp's, which wants a template where GNU's is happy
  693. # without one. Both spellings rather than the one that works on the machine
  694. # this was written on.
  695. tmp=$(mktemp -d 2>/dev/null) || tmp=$(mktemp -d -t ank 2>/dev/null) || tmp=""
  696. [ -n "$tmp" ] || die 5 "could not create a temporary directory."
  697. # On the ordinary exit as well, so a refusal below leaves nothing behind.
  698. trap 'rm -rf "$tmp"' EXIT
  699. trap 'rm -rf "$tmp"; exit 130' INT
  700. trap 'rm -rf "$tmp"; exit 143' TERM
  701. if [ -n "$version" ]; then
  702. # "v0.2.0" and "0.2.0" are the same request. The tag carries the v and the
  703. # archive name does not, and making the caller know which is which is the
  704. # kind of detail a released script gets to absorb.
  705. tag=v${version#v}
  706. else
  707. resolve_latest
  708. fi
  709. bare=${tag#v}
  710. archive="ank-${bare}-${target}.tar.gz"
  711. url="${base_url:-$default_base_url}/${tag}/${archive}"
  712. say "${ui_pad}${ui_bold}ank ${tag}${ui_off} ${ui_dim}${target}${ui_off}"
  713. # The checksum first: it is the smaller of the two files, so a release that
  714. # does not carry this target says so before megabytes move. It is also the
  715. # request that answers "is this platform in this release", which is a question
  716. # the caller deserves answered rather than left as a stalled download.
  717. if ! fetch "${url}.sha256" "${tmp}/sha256"; then
  718. if [ "$fetch_status" = 404 ]; then
  719. die 3 "${tag} does not carry an archive for this platform." \
  720. "" \
  721. " looked for: ${archive}" \
  722. " at: ${url}" \
  723. "" \
  724. "The platform is one this project builds for, so this is about the" \
  725. "release and not about the machine. What ${tag} carries is listed at:" \
  726. " ${releases_url}/tag/${tag}" \
  727. "" \
  728. "Pick a release that carries it:" \
  729. " install.sh --version <version>" \
  730. "" \
  731. "Nothing was installed."
  732. fi
  733. die 3 "could not download the checksum for ${archive}${fetch_status:+ (HTTP ${fetch_status})}." \
  734. "" \
  735. " ${url}.sha256" \
  736. "" \
  737. "Nothing was installed."
  738. fi
  739. expected=$(lower "$(awk 'NR==1 {print $1}' "${tmp}/sha256")")
  740. # A captive portal answering every request with a login page is a real way to
  741. # get a .sha256 that parses into something. Sixty-four hex characters, or this
  742. # was not the release answering.
  743. case "$expected" in
  744. *[!0-9a-f]* | "") expected_ok=no ;;
  745. *) [ "${#expected}" -eq 64 ] && expected_ok=yes || expected_ok=no ;;
  746. esac
  747. if [ "$expected_ok" = no ]; then
  748. die 4 "the published checksum for ${archive} is not a SHA-256." \
  749. "" \
  750. " ${url}.sha256" \
  751. " read back: ${expected:-<empty>}" \
  752. "" \
  753. "Something other than the release answered that request. Nothing was" \
  754. "unpacked and nothing was installed."
  755. fi
  756. if ! fetch "$url" "${tmp}/${archive}"; then
  757. die 3 "could not download ${archive}${fetch_status:+ (HTTP ${fetch_status})}." \
  758. "" \
  759. " ${url}" \
  760. "" \
  761. "Nothing was installed."
  762. fi
  763. actual=$(lower "$(sha256_of "${tmp}/${archive}")")
  764. # Before unpacking, and this is what the file is for. A script that downloads
  765. # an executable over the network and runs it without checking the hash
  766. # published beside it is a supply chain with a hole in the middle.
  767. #
  768. # What the check buys, stated honestly: it catches a truncated or corrupted
  769. # download, a mirror serving the wrong file, and an archive that is not the
  770. # one the release recorded. It is not a signature -- the hash comes from the
  771. # same host as the archive -- which is why the default host is GitHub over TLS
  772. # and why ANK_BASE_URL is documented as a mirror rather than as a default.
  773. if [ "$expected" != "$actual" ]; then
  774. die 4 "checksum mismatch, refusing to unpack ${archive}." \
  775. "" \
  776. " expected: ${expected}" \
  777. " actual: ${actual}" \
  778. " published: ${url}.sha256" \
  779. "" \
  780. "The download does not match the hash the release published beside it." \
  781. "Nothing was unpacked and nothing was installed." \
  782. "" \
  783. "Retry once, in case the transfer was truncated. If it happens again, do" \
  784. "not install this archive, and say so:" \
  785. " https://github.com/${repo}/security"
  786. fi
  787. ok "checksum ok ${ui_dim}${actual}${ui_off}"
  788. # Build provenance, which is what the checksum is not. Whoever can replace an
  789. # archive on the release page can replace the .sha256 beside it; neither can
  790. # forge the attestation release.yml records for every archive it builds,
  791. # because that is signed by GitHub for the workflow run that built the file.
  792. # So a gh that can ask the API is asked, pinned to this repository and to the
  793. # workflow that builds, and a failure is a refusal whether or not the caller
  794. # asked for the check: an archive that matched its hash and failed the
  795. # stronger test is the one case this exists for.
  796. #
  797. # A release at or below 0.9.4 was published before the attestations, so for it
  798. # the question has no answer to ask for. Which check was made is said in one
  799. # line, every time, so a log shows what an install rested on.
  800. attested_after=0.9.4
  801. signer="${repo}/.github/workflows/release.yml"
  802. if ! newer_than "$bare" "$attested_after"; then
  803. provenance="${tag} predates build provenance"
  804. elif ! have gh; then
  805. provenance="gh is not on PATH, so provenance was not checked"
  806. elif ! gh auth status >/dev/null 2>&1; then
  807. provenance="gh is not signed in, so provenance was not checked"
  808. elif gh attestation verify "${tmp}/${archive}" --repo "$repo" \
  809. --signer-workflow "$signer" >"${tmp}/attestation" 2>&1; then
  810. provenance=""
  811. else
  812. say ""
  813. sed 's/^/ /' "${tmp}/attestation" >&2
  814. die 4 "the build provenance of ${archive} did not verify, refusing to unpack it." \
  815. "" \
  816. " gh attestation verify ${archive} --repo ${repo} --signer-workflow ${signer}" \
  817. "" \
  818. "The archive matches the checksum published beside it, and no attestation" \
  819. "of this repository's release workflow vouches for it. Nothing was" \
  820. "unpacked and nothing was installed. Do not install this archive, and say so:" \
  821. " https://github.com/${repo}/security"
  822. fi
  823. if [ -n "$provenance" ] && [ "$require_provenance" = yes ]; then
  824. case "$provenance" in
  825. *predates*)
  826. die 4 "--require-provenance: ${provenance}." \
  827. "" \
  828. "Releases above v${attested_after} carry an attestation per archive. Pick one:" \
  829. " install.sh --version <version> --require-provenance" \
  830. "" \
  831. "Nothing was installed."
  832. ;;
  833. *)
  834. die 5 "--require-provenance: ${provenance}." \
  835. "" \
  836. "The check is gh attestation verify, which needs gh signed in:" \
  837. " https://cli.github.com" \
  838. " gh auth login" \
  839. "" \
  840. "Nothing was installed."
  841. ;;
  842. esac
  843. fi
  844. if [ -n "$provenance" ]; then
  845. ok "verified: sha256 only ${ui_dim}(${provenance})${ui_off}"
  846. else
  847. ok "verified: sha256 and provenance"
  848. fi
  849. tar xzf "${tmp}/${archive}" -C "$tmp" ||
  850. die 3 "could not unpack ${archive}." "" "Nothing was installed."
  851. # The layout release.yml packages: one directory named after the archive,
  852. # carrying the executable beside README.md, LICENSE and SKILL.md.
  853. #
  854. # `ank` is required and the rest of the directory is not read at all. An
  855. # archive published before ADR-1ea31c2f3c5a carries a second executable there,
  856. # and the answer to it is the same as the answer to README.md: it is not what
  857. # was asked for, so it is not moved anywhere. A check that refused an archive
  858. # holding more than this would refuse every release published so far.
  859. unpacked="${tmp}/ank-${bare}-${target}"
  860. binary="${unpacked}/ank"
  861. if [ ! -f "$binary" ]; then
  862. die 3 "${archive} does not contain ank where this script expected it." \
  863. "" \
  864. " looked for: ank-${bare}-${target}/ank" \
  865. "" \
  866. "Nothing was installed."
  867. fi
  868. if [ -z "$install_dir" ]; then
  869. [ -n "${HOME:-}" ] ||
  870. die 1 "HOME is not set, so there is no default install directory." \
  871. "" \
  872. "Name one:" \
  873. " install.sh --dir /usr/local/bin"
  874. install_dir="${HOME}/.local/bin"
  875. fi
  876. mkdir -p "$install_dir" 2>/dev/null ||
  877. die 1 "could not create ${install_dir}." \
  878. "" \
  879. "Install somewhere writable, or run this with the rights to write there:" \
  880. " install.sh --dir \$HOME/.local/bin"
  881. [ -w "$install_dir" ] ||
  882. die 1 "${install_dir} is not writable." \
  883. "" \
  884. "Install somewhere writable, or run this with the rights to write there:" \
  885. " install.sh --dir \$HOME/.local/bin"
  886. chmod +x "$binary"
  887. # A rename into place rather than a copy over the file: on Linux, replacing a
  888. # binary that is currently running is fine, writing into it is not.
  889. mv -f "$binary" "${install_dir}/ank" ||
  890. die 1 "could not write ${install_dir}/ank." "" "Nothing was installed."
  891. installed_version=$("${install_dir}/ank" --version 2>/dev/null | head -1) ||
  892. installed_version=""
  893. say ""
  894. ok "installed ${ui_bold}${install_dir}/ank${ui_off}"
  895. if [ -n "$installed_version" ]; then
  896. say "${ui_pad}${ui_pad} ${ui_dim}${installed_version}${ui_off}"
  897. fi
  898. # The last way left to leave a caller without a working `ank`: a binary in a
  899. # directory nothing looks in. Naming the line to add is the difference between
  900. # an install that worked and an install that appears not to have run.
  901. case ":${PATH}:" in
  902. *":${install_dir}:"*)
  903. say ""
  904. say "${ui_pad}${install_dir} is on your PATH. Run: ${ui_cyan}ank help${ui_off}"
  905. ;;
  906. *)
  907. case "${SHELL:-}" in
  908. */fish)
  909. path_line="fish_add_path ${install_dir}"
  910. path_file="~/.config/fish/config.fish"
  911. ;;
  912. */zsh)
  913. path_line="export PATH=\"${install_dir}:\$PATH\""
  914. path_file="~/.zshrc"
  915. ;;
  916. */bash)
  917. path_line="export PATH=\"${install_dir}:\$PATH\""
  918. path_file="~/.bashrc"
  919. ;;
  920. *)
  921. path_line="export PATH=\"${install_dir}:\$PATH\""
  922. path_file="your shell's startup file"
  923. ;;
  924. esac
  925. say ""
  926. say "${ui_pad}${install_dir} is not on your PATH, so \`ank\` is not a command yet."
  927. say "${ui_pad}Add this line to ${ui_bold}${path_file}${ui_off}:"
  928. say ""
  929. say "${ui_pad} ${ui_cyan}${path_line}${ui_off}"
  930. say ""
  931. say "${ui_pad}then open a new shell, or run that line now in this one."
  932. ;;
  933. esac
  934. # --------------------------------------------------------------------------
  935. # The skills
  936. # --------------------------------------------------------------------------
  937. # ADR-5fbd99bf6fd5's offer, and the last thing this script does. Everything
  938. # above has already happened: the binary is on disk, verified, reported, and
  939. # the PATH advice given. That ordering is the decision rather than a layout --
  940. # an installation that stops to ask something is an installation that can be
  941. # abandoned half-done, and half-done is the worst state for a tool whose next
  942. # action is `ank context`.
  943. #
  944. # The question is this script's and the answer is the binary's
  945. # (ADR-e1d750884b82). `ank skills --install` writes out the skills it carries
  946. # and hands them to the skills CLI, which serves every agent it knows about
  947. # rather than one, and the verb already decides what to say when node is
  948. # missing and what a failure means. A second copy of that logic here would be
  949. # a second copy to drift.
  950. offer_skills() {
  951. human_at_terminal || return 0
  952. say ""
  953. say "${ui_pad}The skills teach an agent how to use ank: the contract, and one policy"
  954. say "${ui_pad}per activity. They install through the skills CLI, which puts them where"
  955. say "${ui_pad}each agent looks."
  956. say ""
  957. say "${ui_pad} ${ui_cyan}ank skills --install${ui_off}"
  958. say ""
  959. # /dev/tty and nowhere else, which is the trap ADR-5fbd99bf6fd5 exists to
  960. # name. Under `curl ... | sh` standard input is this script: a plain `read`
  961. # would consume the rest of the file and execute none of it, and it would do
  962. # so only on the route people actually use, having worked in every local test
  963. # where the script was run from a file.
  964. # Three calls, and the question is a literal in the middle one. Written as a
  965. # single format string with the emphasis as placeholders, the sentence is
  966. # split across them and stops being a sentence anyone can find: the tests
  967. # count this string in this file to know it is asked exactly once, and a
  968. # question that cannot be counted is a question that can quietly be asked
  969. # twice. What a pipe reads is unchanged either way -- the first and last call
  970. # write nothing at all until ui_enable has run.
  971. printf '%s%s' "$ui_pad" "$ui_bold" >&2
  972. printf 'Install them now? [Y/n] ' >&2
  973. printf '%s' "$ui_off" >&2
  974. if ! IFS= read -r offer_answer < /dev/tty; then
  975. # End of input rather than an answer. Nothing was typed, so nothing is
  976. # assumed, and the newline is ours because no Enter was pressed to echo
  977. # one.
  978. say ""
  979. return 0
  980. fi
  981. # Enter is yes and everything unrecognised is no, in that order: a default
  982. # the criterion names, and a decline for anything else because asking twice
  983. # is asking twice.
  984. case "$offer_answer" in
  985. "" | y | Y | yes | Yes | YES) : ;;
  986. *) return 0 ;;
  987. esac
  988. # The binary just installed, by the path it was installed at: the directory
  989. # may not be on PATH, and a different `ank` found there would answer for a
  990. # build this script did not place.
  991. #
  992. # Two redirections, each doing something this cannot work without.
  993. #
  994. # `< /dev/null` because standard input is still this script under
  995. # `curl ... | sh`: the verb asks nothing and reads nothing, and this is what
  996. # makes that a guarantee rather than a property of one build of it.
  997. #
  998. # `>&2` for the reason `say` writes there: stdout belongs to whoever is
  999. # reading `curl ... | sh`. A redirection and not a pipe, so nothing is
  1000. # buffered and the terminal shows the skills CLI working while it works.
  1001. #
  1002. # Nothing is printed on success, and that is deliberate: the verb exits 0
  1003. # both when the skills went in and when node is missing and it printed the
  1004. # command to run instead, so a line of this script's own would be claiming
  1005. # something only the verb's output knows.
  1006. offer_code=0
  1007. "${install_dir}/ank" skills --install < /dev/null >&2 || offer_code=$?
  1008. if [ "$offer_code" -ne 0 ]; then
  1009. say ""
  1010. say "ank skills --install exited ${offer_code}, so the skills are not"
  1011. say "installed. ank is, and it is exactly the ank this script installs when"
  1012. say "nobody is asked anything at all."
  1013. say ""
  1014. say "Run it again when you want them:"
  1015. say "${ui_pad} ${ui_cyan}ank skills --install${ui_off}"
  1016. fi
  1017. }
  1018. # --------------------------------------------------------------------------
  1019. # Adopting ank where there is already code
  1020. # --------------------------------------------------------------------------
  1021. # ADR-5fbd99bf6fd5's second offer, and the last question this script asks.
  1022. # Installing ank is the easy half. The half nobody had written down is what to
  1023. # say to an agent so that a repository with two years of history acquires a
  1024. # corpus worth having, and the moment after an install is the one moment the
  1025. # person is certainly reading.
  1026. #
  1027. # Three prompts, because the adoption has three moments: state as ADRs what the
  1028. # code already decided, so the constraints that exist implicitly become
  1029. # readable; turn a list of intentions into tasks carrying a scope and a
  1030. # criterion; and check what came out. The first one is the one the reader
  1031. # judges the tool on, which is why it is first.
  1032. #
  1033. # The same three prose blocks live in install.ps1 and in docs/quickstart.md,
  1034. # and a test holds the three copies character for character
  1035. # (crates/ank-cli/tests/adopt.rs). Prose duplicated in three files diverges, and
  1036. # this is the prose where divergence is worst: an installer teaching a prompt
  1037. # the documentation has since corrected. The markers below are what the test
  1038. # reads; the block between them is the one to edit, and the other two follow.
  1039. # adopt-prompts:begin
  1040. adopt_walkthrough() {
  1041. cat >&2 <<'ADOPT_EOF'
  1042. In a repository that already has code and no .ank, start with:
  1043. ank init
  1044. Then paste these three into your agent, one at a time, and read what each
  1045. one produces before you send the next.
  1046. 1. What the code already decided:
  1047. Read this repository and write, as ank ADRs, the decisions its code
  1048. has already made: the ones a newcomer would break without knowing
  1049. they existed. One ADR per decision, each with a scope glob covering
  1050. the files it binds and a constraint stated as a rule. Leave them
  1051. proposed; I ratify them myself.
  1052. 2. What is still owed:
  1053. Read the TODOs, the open issues and the README of this repository,
  1054. and turn what they promise into ank tasks. Give each one a scope
  1055. glob and a done_criteria a test could settle, and use blocked_by
  1056. only where a task genuinely waits on another.
  1057. 3. What you now have:
  1058. Run ank check and ank review here, then read every ADR back against
  1059. the code its scope matches. Tell me which constraints the code
  1060. already breaks and which scopes match no file, and change nothing
  1061. until I have read your answer.
  1062. The same three are in docs/quickstart.md, which says what to expect
  1063. from each:
  1064. https://github.com/haksolot/ank/blob/main/docs/quickstart.md
  1065. ADOPT_EOF
  1066. }
  1067. # adopt-prompts:end
  1068. # The second question, asked on the same terms as the first: only with a human
  1069. # at a terminal, from /dev/tty and nowhere else, with a default Enter accepts.
  1070. # Declining prints nothing -- not a shortened version, not a pointer to one.
  1071. # An offer that answers a no with half of a yes is an offer that was not really
  1072. # asked.
  1073. offer_adoption() {
  1074. human_at_terminal || return 0
  1075. say ""
  1076. # One literal in one call, for the reason the skills question is: the tests
  1077. # count this sentence in this file, and emphasis written as placeholders cuts
  1078. # it in half.
  1079. printf '%s%s' "$ui_pad" "$ui_bold" >&2
  1080. printf 'Print the three prompts that adopt ank in a repository you already have? [Y/n] ' >&2
  1081. printf '%s' "$ui_off" >&2
  1082. if ! IFS= read -r adopt_answer < /dev/tty; then
  1083. # End of input rather than an answer. The newline is ours because no Enter
  1084. # was pressed to echo one.
  1085. say ""
  1086. return 0
  1087. fi
  1088. case "$adopt_answer" in
  1089. "" | y | Y | yes | Yes | YES) : ;;
  1090. *) return 0 ;;
  1091. esac
  1092. say ""
  1093. # To stderr, for the reason `say` writes there: the interesting use of this
  1094. # script is `curl ... | sh`, and stdout belongs to whoever is reading it.
  1095. adopt_walkthrough
  1096. say ""
  1097. }
  1098. # `|| :` on each and not a bare call, and it is the whole guarantee in two
  1099. # lines. These are the last commands in the file, so the script's status is the
  1100. # status of the last of them: with `set -e` in force a single failure anywhere
  1101. # inside either would become the exit code of an install that has already
  1102. # succeeded. Called this way, the failure is tested rather than fatal, `set -e`
  1103. # is suspended for the duration, and the status this script leaves with is the
  1104. # status it had before the first question was asked.
  1105. offer_skills || :
  1106. offer_adoption || :

Ratings and comments

Sign in to rate this skill.

Sign in

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