env_check.ps1 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. # docx strict environment check (Windows PowerShell mirror of env_check.sh)
  2. # Authoritative for whether the skill may run on Windows.
  3. # Supports -Level Read|Render|Full (default Full). Output format and exit codes
  4. # match env_check.sh so the daemon's gate hook can compare them line-by-line.
  5. #Requires -Version 5.1
  6. [CmdletBinding()]
  7. param(
  8. # NOTE: intentionally NOT using [ValidateSet]. ValidateSet rejects with PowerShell exit 1
  9. # which would conflate "NOT READY" with "bad CLI args". env_check.sh exits 2 for bad args
  10. # and 1 for NOT READY; we mirror that with manual validation below.
  11. [string]$Level = 'Full'
  12. )
  13. $ErrorActionPreference = 'Stop'
  14. # Same UTF-8 enforcement as setup.ps1: chcp first (so child processes inherit UTF-8 code page),
  15. # then [Console]::OutputEncoding (so PowerShell's view of stdout/stderr matches).
  16. try { & chcp.com 65001 *> $null } catch { }
  17. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
  18. [Console]::InputEncoding = [System.Text.Encoding]::UTF8
  19. $OutputEncoding = [System.Text.UTF8Encoding]::new()
  20. $env:DOTNET_CLI_UI_LANGUAGE = 'en'
  21. # Manual validation (mirror env_check.sh exit codes).
  22. $ValidLevels = @('Read', 'Render', 'Full')
  23. if ($ValidLevels -notcontains $Level) {
  24. [Console]::Error.WriteLine("Invalid -Level value: '$Level'. Must be one of: Read, Render, Full")
  25. exit 2
  26. }
  27. $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
  28. $ProjectDir = Split-Path -Parent $ScriptDir
  29. $DotnetDir = Join-Path $ScriptDir 'dotnet'
  30. $DotnetRequiredMajor = 9
  31. function Test-Command($Name) { [bool](Get-Command $Name -ErrorAction SilentlyContinue) }
  32. function Resolve-SofficePath {
  33. foreach ($n in @('soffice.exe', 'soffice')) {
  34. $cmd = Get-Command $n -ErrorAction SilentlyContinue
  35. if ($cmd) { return $cmd.Source }
  36. }
  37. $candidates = @(
  38. (Join-Path $env:ProgramFiles 'LibreOffice\program\soffice.exe'),
  39. (Join-Path ${env:ProgramFiles(x86)} 'LibreOffice\program\soffice.exe'),
  40. (Join-Path $env:LOCALAPPDATA 'Programs\LibreOffice\program\soffice.exe'),
  41. (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Links\soffice.exe'),
  42. (Join-Path $env:USERPROFILE 'scoop\apps\libreoffice\current\program\soffice.exe')
  43. ) | Where-Object { $_ }
  44. foreach ($p in $candidates) { if (Test-Path $p) { return (Resolve-Path $p).Path } }
  45. return $null
  46. }
  47. function Resolve-PdftoppmPath {
  48. foreach ($n in @('pdftoppm.exe', 'pdftoppm', 'pdftocairo.exe', 'pdftocairo')) {
  49. $cmd = Get-Command $n -ErrorAction SilentlyContinue
  50. if ($cmd) { return $cmd.Source }
  51. }
  52. $candidates = @(
  53. (Join-Path $env:USERPROFILE 'scoop\apps\poppler\current\bin\pdftoppm.exe'),
  54. (Join-Path $env:ProgramData 'chocolatey\bin\pdftoppm.exe')
  55. ) | Where-Object { $_ }
  56. foreach ($p in $candidates) { if (Test-Path $p) { return (Resolve-Path $p).Path } }
  57. return $null
  58. }
  59. function Resolve-PythonCommand {
  60. foreach ($name in @('python', 'python3', 'py')) {
  61. $cmd = Get-Command $name -ErrorAction SilentlyContinue
  62. if (-not $cmd) { continue }
  63. if ($name -eq 'py') {
  64. try {
  65. & $cmd.Source -3 --version *> $null
  66. if ($LASTEXITCODE -eq 0) { return @{ Cmd = $cmd.Source; Args = @('-3') } }
  67. } catch { continue }
  68. } else {
  69. return @{ Cmd = $cmd.Source; Args = @() }
  70. }
  71. }
  72. return $null
  73. }
  74. Write-Host "=== docx Environment Check (level: $Level) ==="
  75. Write-Host ""
  76. $Status = 'READY'
  77. # Failure buckets — populated by CheckFail-style helpers, rendered at the end
  78. # so the remediation section can speak in categories instead of one line per tool.
  79. $script:MissingTools = New-Object System.Collections.Generic.List[string]
  80. $script:LocaleBroken = $false
  81. $script:LocaleHealed = $false # set when console was forced to UTF-8 for this
  82. # session; READY path still emits an Advisory so
  83. # the "forced for this session" message points
  84. # the user at a persistent fix.
  85. $script:LocaleHealedFrom = ''
  86. $script:PermsBroken = $false
  87. $script:ProjectBroken = $false
  88. # Match env_check.sh's `printf '[OK] %-14s %s\n'` — 14-char left-justified column,
  89. # ONE space separator, then the value. Without the explicit space, the format string
  90. # `{0,-14}{1}` collapses when the name is exactly 14 chars wide.
  91. function CheckOk { param([string]$Name, [string]$Detail) Write-Host ("[OK] {0,-14} {1}" -f $Name, $Detail) }
  92. function CheckFail { param([string]$Name, [string]$Detail) Write-Host ("[FAIL] {0,-14} {1}" -f $Name, $Detail); $script:Status = 'NOT READY' }
  93. function MarkMissingTool { param([string]$Name) $script:MissingTools.Add($Name) | Out-Null }
  94. # --- read-level checks (always run) ---
  95. $py = Resolve-PythonCommand
  96. if (-not $py) {
  97. CheckFail 'python3' 'not found'
  98. MarkMissingTool 'python (3.x)'
  99. } else {
  100. $verLine = & $py.Cmd @($py.Args + '--version') 2>&1
  101. $verNum = ($verLine -join ' ') -replace '.*?(\d+\.\d+(?:\.\d+)?).*', '$1'
  102. CheckOk 'python3' $verNum
  103. }
  104. # unzip OR tar.exe (Windows 10 1803+) OR built-in Expand-Archive — any of them counts
  105. if (Test-Command unzip) {
  106. CheckOk 'unzip' 'available'
  107. } elseif (Test-Command tar) {
  108. CheckOk 'unzip' 'tar.exe (Windows 10+ native, handles .zip)'
  109. } elseif (Get-Command Expand-Archive -ErrorAction SilentlyContinue) {
  110. CheckOk 'unzip' 'Expand-Archive (PowerShell built-in)'
  111. } else {
  112. CheckFail 'unzip' 'no zip extractor found (unzip / tar.exe / Expand-Archive)'
  113. MarkMissingTool 'unzip'
  114. }
  115. # Locale / encoding — UTF-8 console required for CJK
  116. $enc = [Console]::OutputEncoding.WebName
  117. if ($enc -match '^utf-?8$') {
  118. CheckOk 'locale' "console=$enc"
  119. } else {
  120. # Try to force UTF-8 for this session and re-check
  121. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
  122. $enc2 = [Console]::OutputEncoding.WebName
  123. if ($enc2 -match '^utf-?8$') {
  124. CheckOk 'locale' "console=$enc2 (forced for this session — see advisory below to persist)"
  125. $script:LocaleHealed = $true
  126. $script:LocaleHealedFrom = $enc
  127. } else {
  128. CheckFail 'locale' "console=$enc — UTF-8 required, cannot force"
  129. $script:LocaleBroken = $true
  130. }
  131. }
  132. # Permission analogue on Windows: scripts unblocked (no Mark-of-the-Web).
  133. # A blocked script will throw on Get-Item with -Stream Zone.Identifier.
  134. $blocked = 0
  135. foreach ($s in (Get-ChildItem -Path $ScriptDir -File -Filter '*.ps1' -ErrorAction SilentlyContinue)) {
  136. try {
  137. $null = Get-Item -LiteralPath $s.FullName -Stream 'Zone.Identifier' -ErrorAction Stop
  138. $blocked++
  139. } catch {
  140. # No Zone.Identifier stream means NOT blocked — that's the desired state.
  141. }
  142. }
  143. if ($blocked -eq 0) {
  144. CheckOk 'permissions' 'all .ps1 scripts unblocked'
  145. } else {
  146. CheckFail 'permissions' "$blocked .ps1 script(s) carry Mark-of-the-Web (run setup.ps1 to unblock)"
  147. $script:PermsBroken = $true
  148. }
  149. # --- render-level checks (render + full) ---
  150. if ($Level -in @('Render', 'Full')) {
  151. $sof = Resolve-SofficePath
  152. if ($sof) { CheckOk 'soffice' $sof } else { CheckFail 'soffice' 'not found'; MarkMissingTool 'soffice.exe' }
  153. $pp = Resolve-PdftoppmPath
  154. if ($pp) { CheckOk 'pdftoppm' $pp } else { CheckFail 'pdftoppm' 'not found'; MarkMissingTool 'pdftoppm.exe' }
  155. }
  156. # --- full-level checks (full only) ---
  157. if ($Level -eq 'Full') {
  158. if (-not (Test-Command dotnet)) {
  159. CheckFail 'dotnet' 'not found'
  160. MarkMissingTool 'dotnet'
  161. } else {
  162. $ver = (& dotnet --version 2>$null)
  163. if (-not $ver) { $ver = '0.0.0' }
  164. try {
  165. $major = [int](($ver -split '\.')[0])
  166. } catch { $major = 0 }
  167. if ($major -ge $DotnetRequiredMajor) {
  168. CheckOk 'dotnet' "$ver (>= $DotnetRequiredMajor.0)"
  169. } else {
  170. CheckFail 'dotnet' "$ver (requires >= $DotnetRequiredMajor.0)"
  171. MarkMissingTool "dotnet>=$DotnetRequiredMajor"
  172. }
  173. }
  174. if (-not (Test-Command pandoc)) {
  175. CheckFail 'pandoc' 'not found'
  176. MarkMissingTool 'pandoc'
  177. } else {
  178. $pv = ((& pandoc --version 2>$null | Select-Object -First 1) -replace '.*?(\d+\.\d+(?:\.\d+)?).*', '$1')
  179. CheckOk 'pandoc' $pv
  180. }
  181. if (Test-Command zip) {
  182. CheckOk 'zip' 'available'
  183. } elseif (Get-Command Compress-Archive -ErrorAction SilentlyContinue) {
  184. CheckOk 'zip' 'Compress-Archive (PowerShell built-in)'
  185. } else {
  186. CheckFail 'zip' 'no zip writer (zip.exe / Compress-Archive)'
  187. MarkMissingTool 'zip'
  188. }
  189. if (-not (Test-Path $DotnetDir -PathType Container)) {
  190. CheckFail 'project' "directory not found: $DotnetDir"
  191. $script:ProjectBroken = $true
  192. } else {
  193. $built = $false
  194. foreach ($tfm in @('net10.0', 'net9.0', 'net8.0')) {
  195. $dll = Join-Path $DotnetDir "MiniMaxAIDocx.Cli\bin\Debug\$tfm\MiniMaxAIDocx.Cli.dll"
  196. if (Test-Path $dll) { $built = $true; break }
  197. }
  198. if ($built) {
  199. CheckOk 'project' 'built'
  200. } else {
  201. try {
  202. & dotnet restore $DotnetDir --verbosity quiet *> $null
  203. if ($LASTEXITCODE -eq 0) {
  204. & dotnet build $DotnetDir --verbosity quiet --no-restore *> $null
  205. if ($LASTEXITCODE -eq 0) {
  206. CheckOk 'project' 'restore+build succeeded'
  207. } else {
  208. CheckFail 'project' 'restore succeeded but build failed'
  209. $script:ProjectBroken = $true
  210. }
  211. } else {
  212. CheckFail 'project' 'restore failed'
  213. $script:ProjectBroken = $true
  214. }
  215. } catch {
  216. CheckFail 'project' "restore/build threw: $_"
  217. $script:ProjectBroken = $true
  218. }
  219. }
  220. }
  221. }
  222. Write-Host ""
  223. if ($Status -eq 'READY') {
  224. Write-Host 'Status: READY'
  225. # Advisory — fulfils the "see advisory below to persist" promise on the
  226. # OK line. Not a failure (we keep exit 0 and READY status), just a nudge so
  227. # the next subprocess does not have to force UTF-8 again.
  228. if ($script:LocaleHealed) {
  229. Write-Host ''
  230. Write-Host '----- Advisory -----'
  231. Write-Host ''
  232. Write-Host "[locale] Console encoding was forced to UTF-8 for this session (was console=$($script:LocaleHealedFrom))."
  233. Write-Host ' Skill scripts in THIS PowerShell session will keep working — no further action needed.'
  234. Write-Host ' But every NEW process starts from scratch and must force again.'
  235. Write-Host ' To make UTF-8 sticky system-wide (Windows 10 1903+):'
  236. Write-Host ' Settings -> Time & Language -> Language & region ->'
  237. Write-Host ' Administrative language settings -> Change system locale ->'
  238. Write-Host ' check "Beta: Use Unicode UTF-8 for worldwide language support" -> reboot.'
  239. Write-Host ' Per-shell alternative, add to your $PROFILE so every PowerShell starts UTF-8:'
  240. Write-Host ' chcp.com 65001 | Out-Null'
  241. Write-Host ' [Console]::OutputEncoding = [System.Text.Encoding]::UTF8'
  242. }
  243. exit 0
  244. } else {
  245. Write-Host 'Status: NOT READY'
  246. Write-Host ''
  247. Write-Host '----- Remediation -----'
  248. # Locale block — most common subprocess pitfall, surface first.
  249. if ($script:LocaleBroken) {
  250. Write-Host ''
  251. Write-Host '[locale] PowerShell console is not UTF-8 and could not be forced.'
  252. Write-Host ' Caller (one-shot for this session, no system changes):'
  253. Write-Host ' chcp.com 65001 | Out-Null'
  254. Write-Host ' [Console]::OutputEncoding = [System.Text.Encoding]::UTF8'
  255. Write-Host ' Persist (System-wide UTF-8 — Windows 10 1903+):'
  256. Write-Host ' Settings -> Time & Language -> Language & region ->'
  257. Write-Host ' Administrative language settings -> Change system locale ->'
  258. Write-Host ' check "Beta: Use Unicode UTF-8 for worldwide language support" -> reboot.'
  259. Write-Host ' Or, per-shell, add the two lines above to your $PROFILE.'
  260. }
  261. # Permissions / MOTW
  262. if ($script:PermsBroken) {
  263. Write-Host ''
  264. Write-Host '[permissions] Some .ps1 scripts carry Mark-of-the-Web. Fix:'
  265. Write-Host " Get-ChildItem -Path '$ScriptDir' -Filter '*.ps1' | Unblock-File"
  266. Write-Host ' Or run scripts/setup.ps1 which unblocks as part of setup.'
  267. }
  268. # Missing tools — composite hint
  269. if ($script:MissingTools.Count -gt 0) {
  270. $toolList = ($script:MissingTools | Sort-Object -Unique) -join ' '
  271. Write-Host ''
  272. Write-Host "[missing tools] $toolList"
  273. Write-Host " Recommended: powershell -ExecutionPolicy Bypass -File `"$ScriptDir\setup.ps1`""
  274. Write-Host ' setup.ps1 handles winget/scoop/choco fallbacks automatically.'
  275. }
  276. # dotnet project build failure
  277. if ($script:ProjectBroken) {
  278. Write-Host ''
  279. Write-Host '[dotnet project] build/restore failed. To diagnose:'
  280. Write-Host " dotnet restore `"$DotnetDir`" --verbosity normal"
  281. Write-Host " dotnet build `"$DotnetDir`" --verbosity normal --no-restore"
  282. Write-Host " Common causes: dotnet SDK < $DotnetRequiredMajor.0, blocked NuGet feed,"
  283. Write-Host ' or a clobbered intermediate build. Try removing all bin/obj dirs under'
  284. Write-Host ' the dotnet project tree, then rebuild.'
  285. }
  286. Write-Host ''
  287. if ($Level -eq 'Read') {
  288. Write-Host 'The read-level gate requires: python (3.x), zip extractor, UTF-8 console, unblocked scripts.'
  289. Write-Host "Re-check: powershell -ExecutionPolicy Bypass -File `"$($MyInvocation.MyCommand.Path)`" -Level Read"
  290. } elseif ($Level -eq 'Render') {
  291. Write-Host 'The render-level gate requires read-level items plus: soffice.exe, pdftoppm.exe.'
  292. Write-Host "Re-check: powershell -ExecutionPolicy Bypass -File `"$($MyInvocation.MyCommand.Path)`" -Level Render"
  293. } else {
  294. Write-Host "The full-level gate requires render-level items plus: dotnet>=$DotnetRequiredMajor, pandoc, zip writer, built dotnet project."
  295. Write-Host "Re-check: powershell -ExecutionPolicy Bypass -File `"$($MyInvocation.MyCommand.Path)`" -Level Full"
  296. }
  297. exit 1
  298. }