param( [ValidateSet('Setup','Send')][string]$Mode = 'Setup', [ValidateSet('Complete','Input')][string]$Event = 'Complete', [string]$Agent = 'AI Agent' ) $ErrorActionPreference = 'Stop' $dir = Join-Path $env:LOCALAPPDATA 'AgentBark' $keyPath = Join-Path $dir 'device-key.dpapi' function Send-Bark([Security.SecureString]$Key, [string]$Message) { $payload = @{ device_key = [Net.NetworkCredential]::new('', $Key).Password title = $Agent body = $Message group = $Agent } | ConvertTo-Json -Compress try { $response = Invoke-RestMethod -Uri 'https://api.day.app/push' -Method Post -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes($payload)) -TimeoutSec 8 } catch { throw 'Bark 傳送失敗。請確認網路與配對。' } if ($response.code -ne 200) { throw 'Bark 拒絕推播。請重新配對。' } } if ($Mode -eq 'Setup') { $entered = Read-Host '請貼上 Bark 裝置金鑰或 api.day.app 推播網址' -AsSecureString $value = [Net.NetworkCredential]::new('', $entered).Password.Trim() if ($value -match '^https://api\.day\.app/([A-Za-z0-9_-]+)(?:[/?#].*)?$') { $value = $Matches[1] } if ($value -cnotmatch '^[A-Za-z0-9_-]+$') { throw '請輸入有效的 Bark 裝置金鑰。' } $key = ConvertTo-SecureString -String $value -AsPlainText -Force Send-Bark $key 'Bark 測試成功。' New-Item -ItemType Directory -Force -Path $dir | Out-Null ConvertFrom-SecureString -SecureString $key | Set-Content -LiteralPath $keyPath -Encoding Ascii -NoNewline Write-Output 'Bark 已接受測試推播。請在 iPhone 確認。' return } if (!(Test-Path -LiteralPath $keyPath)) { throw '請先執行 -Mode Setup 配對。' } $key = Get-Content -LiteralPath $keyPath -Raw | ConvertTo-SecureString $message = switch ($Event) { 'Complete' { '任務已完成,請查看對話。' } 'Input' { '任務需要你的回覆或決定,請查看對話。' } } Send-Bark $key $message Write-Output 'Bark 已接受推播。'