| author | |
| committer | |
| log | 67f5fa76f24bfe7b46c5bb0f0ebc48ebea1b0473 |
| tree | 0eed902545d67446fb746363758c42ac31c22ee3 |
| parent | bc97ccbb76c079f855e64b943306227f3cf9e5ce |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
Retire the local-agent catalog, pairing and transport routes, installers, UI, and build dependency now that The Knife provides this functionality. Reject token exchanges for retired catalogs while preserving stored account data.
Assisted-by: gpt-6-astra18 files changed, 49 insertions(+), 1762 deletions(-)
dashboard/.gitignore-1| ... | ... | @@ -3,4 +3,3 @@ dist/ |
| 3 | 3 | .cache/ |
| 4 | 4 | data/ |
| 5 | 5 | target/ |
| 6 | agent/relay.mjs |
dashboard/agent/install.ps1 deleted-41| ... | ... | @@ -1,41 +0,0 @@ |
| 1 | $ErrorActionPreference = 'Stop' | |
| 2 | $Server = __SERVER__ | |
| 3 | ||
| 4 | function Install-Agent { | |
| 5 | $Identity = [Security.Principal.WindowsIdentity]::GetCurrent() | |
| 6 | $Principal = New-Object Security.Principal.WindowsPrincipal($Identity) | |
| 7 | if ($Principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { | |
| 8 | throw 'Run this installer from your usual PowerShell window, without administrator privileges.' | |
| 9 | } | |
| 10 | $Base = Join-Path $env:LOCALAPPDATA 'AgentRelay' | |
| 11 | $Stage = Join-Path $Base ('.install.' + [guid]::NewGuid().ToString('N')) | |
| 12 | New-Item -ItemType Directory -Force $Base | Out-Null | |
| 13 | & icacls.exe $Base /inheritance:r /grant:r ('*' + $Identity.User.Value + ':(OI)(CI)F') '*S-1-5-18:(OI)(CI)F' | Out-Null | |
| 14 | if ($LASTEXITCODE -ne 0) { throw 'Unable to protect the agent folder. Check its permissions and retry.' } | |
| 15 | try { | |
| 16 | New-Item -ItemType Directory -Force $Stage | Out-Null | |
| 17 | $Node = Join-Path $Base 'node.exe' | |
| 18 | if (!(Test-Path $Node)) { | |
| 19 | Write-Host 'Downloading the agent runtime…' | |
| 20 | $Arch = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64' -or $env:PROCESSOR_ARCHITEW6432 -eq 'ARM64') { 'arm64' } else { 'x64' } | |
| 21 | $Checksums = (Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 'https://nodejs.org/dist/latest-v24.x/SHASUMS256.txt').Content | |
| 22 | $Match = [regex]::Match($Checksums, "(?m)^([a-f0-9]{64})\s+(node-(v24\.[0-9]+\.[0-9]+)-win-$Arch\.zip)\s*$") | |
| 23 | if (!$Match.Success) { throw 'No runtime download is available for this machine.' } | |
| 24 | $Archive = Join-Path $Stage $Match.Groups[2].Value | |
| 25 | Invoke-WebRequest -UseBasicParsing -TimeoutSec 120 ("https://nodejs.org/dist/" + $Match.Groups[3].Value + '/' + $Match.Groups[2].Value) -OutFile $Archive | |
| 26 | if ((Get-FileHash $Archive -Algorithm SHA256).Hash.ToLowerInvariant() -ne $Match.Groups[1].Value) { | |
| 27 | throw 'The runtime checksum did not match. Run the installer again.' | |
| 28 | } | |
| 29 | Expand-Archive $Archive $Stage | |
| 30 | Copy-Item (Join-Path $Stage ($Match.Groups[2].Value.Replace('.zip', '') + '\node.exe')) $Node | |
| 31 | } | |
| 32 | Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 "$Server/agent/relay.mjs" -OutFile (Join-Path $Stage 'relay.mjs') | |
| 33 | Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 "$Server/agent/setup.mjs" -OutFile (Join-Path $Stage 'setup.mjs') | |
| 34 | & $Node (Join-Path $Stage 'setup.mjs') install $Server $Base | |
| 35 | if ($LASTEXITCODE -ne 0) { throw 'Installation stopped. Correct the problem above, then run the installer again.' } | |
| 36 | } finally { | |
| 37 | Remove-Item -Recurse -Force $Stage | |
| 38 | } | |
| 39 | } | |
| 40 | ||
| 41 | Install-Agent |
dashboard/agent/install.sh deleted-53| ... | ... | @@ -1,53 +0,0 @@ |
| 1 | #!/bin/sh | |
| 2 | set -eu | |
| 3 | umask 077 | |
| 4 | server=__SERVER__ | |
| 5 | ||
| 6 | install_agent() { | |
| 7 | [ "$(id -u)" != 0 ] || { echo 'Run this installer as your login user, without sudo.' >&2; return 1; } | |
| 8 | case $(uname -s) in | |
| 9 | Linux) os=linux; base=${XDG_DATA_HOME:-"$HOME/.local/share"}/agent-relay | |
| 10 | command -v systemctl >/dev/null || { echo 'This installer needs a systemd user session.' >&2; return 1; } | |
| 11 | systemctl --user show-environment >/dev/null || { echo 'Sign in to a systemd user session, then run the installer again.' >&2; return 1; } ;; | |
| 12 | Darwin) os=darwin; base="$HOME/Library/Application Support/AgentRelay" ;; | |
| 13 | *) echo "Use $server/agent/install.ps1 from Windows PowerShell." >&2; return 1 ;; | |
| 14 | esac | |
| 15 | case $(uname -m) in | |
| 16 | x86_64|amd64) arch=x64 ;; | |
| 17 | aarch64|arm64) arch=arm64 ;; | |
| 18 | *) echo 'This installer supports x64 and arm64 machines.' >&2; return 1 ;; | |
| 19 | esac | |
| 20 | command -v curl >/dev/null || { echo 'Install curl, then run this installer again.' >&2; return 1; } | |
| 21 | mkdir -p "$base" | |
| 22 | chmod 700 "$base" | |
| 23 | stage=$(mktemp -d "$base/.install.XXXXXX") | |
| 24 | trap 'rm -rf "$stage"' EXIT HUP INT TERM | |
| 25 | if [ ! -x "$base/node" ] && [ -f /etc/NIXOS ]; then | |
| 26 | echo 'Installing the agent runtime…' | |
| 27 | nix --extra-experimental-features 'nix-command flakes' build nixpkgs#nodejs_24 --out-link "$base/node-runtime" | |
| 28 | ln -sf "$base/node-runtime/bin/node" "$base/node" | |
| 29 | elif [ ! -x "$base/node" ]; then | |
| 30 | echo 'Downloading the agent runtime…' | |
| 31 | curl -fsSL https://nodejs.org/dist/latest-v24.x/SHASUMS256.txt -o "$stage/checksums" | |
| 32 | archive=$(awk -v suffix="-$os-$arch.tar.gz" '$2 ~ /^node-v24\./ && substr($2, length($2)-length(suffix)+1) == suffix {print $2}' "$stage/checksums") | |
| 33 | [ -n "$archive" ] || { echo 'No runtime download is available for this machine.' >&2; return 1; } | |
| 34 | version=${archive#node-}; version=${version%%-$os-*} | |
| 35 | curl -fsSL "https://nodejs.org/dist/$version/$archive" -o "$stage/$archive" | |
| 36 | expected=$(awk -v file="$archive" '$2 == file {print $1}' "$stage/checksums") | |
| 37 | if command -v sha256sum >/dev/null; then | |
| 38 | actual=$(sha256sum "$stage/$archive"); actual=${actual%% *} | |
| 39 | else | |
| 40 | actual=$(shasum -a 256 "$stage/$archive"); actual=${actual%% *} | |
| 41 | fi | |
| 42 | [ "$actual" = "$expected" ] || { echo 'The runtime checksum did not match. Run the installer again.' >&2; return 1; } | |
| 43 | tar -xzf "$stage/$archive" -C "$stage" | |
| 44 | cp "$stage/${archive%.tar.gz}/bin/node" "$base/node" | |
| 45 | chmod 700 "$base/node" | |
| 46 | fi | |
| 47 | curl -fsSL "$server/agent/relay.mjs" -o "$stage/relay.mjs" | |
| 48 | curl -fsSL "$server/agent/setup.mjs" -o "$stage/setup.mjs" | |
| 49 | "$base/node" "$stage/setup.mjs" install "$server" "$base" </dev/tty | |
| 50 | } | |
| 51 | ||
| 52 | # The shell must read the whole script before the installer opens the terminal. | |
| 53 | install_agent |
dashboard/agent/setup.mjs deleted-192| ... | ... | @@ -1,192 +0,0 @@ |
| 1 | import { execFileSync, spawn, spawnSync } from 'node:child_process'; | |
| 2 | import { copyFile, mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'; | |
| 3 | import { homedir, hostname } from 'node:os'; | |
| 4 | import { delimiter, dirname, join, resolve } from 'node:path'; | |
| 5 | import { createInterface } from 'node:readline/promises'; | |
| 6 | import { setTimeout as sleep } from 'node:timers/promises'; | |
| 7 | ||
| 8 | const [action = 'status', server, installDir] = process.argv.slice(2); | |
| 9 | const base = installDir ?? dirname(process.argv[1]); | |
| 10 | const windows = process.platform === 'win32'; | |
| 11 | const mac = process.platform === 'darwin'; | |
| 12 | const data = windows ? join(base, 'config') : join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'agent-relay'); | |
| 13 | const unit = mac ? join(homedir(), 'Library/LaunchAgents/net.paperclover.agent-relay.plist') : | |
| 14 | join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'systemd/user/agent-relay.service'); | |
| 15 | const task = windows ? 'AgentRelay-' + execFileSync('whoami.exe', ['/user', '/fo', 'csv', '/nh'], { encoding: 'utf8' }).match(/S-1-5-[\d-]+/)[0] : ''; | |
| 16 | const domain = mac ? `gui/${process.getuid()}` : ''; | |
| 17 | const ps = (script) => execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { stdio: 'inherit' }); | |
| 18 | const psQuote = (text) => "'" + text.replaceAll("'", "''") + "'"; | |
| 19 | const shellQuote = (text) => "'" + text.replaceAll("'", "'\\''") + "'"; | |
| 20 | ||
| 21 | async function stop() { | |
| 22 | if (windows) ps(`$ErrorActionPreference = 'Stop' | |
| 23 | if (Get-ScheduledTask -TaskName ${psQuote(task)} -ErrorAction SilentlyContinue) { Stop-ScheduledTask -TaskName ${psQuote(task)} } | |
| 24 | Get-CimInstance Win32_Process -Filter "Name = 'node.exe'" | Where-Object { | |
| 25 | $_.ExecutablePath -eq ${psQuote(join(base, 'node.exe'))} -and $_.CommandLine.Contains(${psQuote(join(base, 'relay.mjs'))}) | |
| 26 | } | ForEach-Object { | |
| 27 | & taskkill.exe /PID $_.ProcessId /T /F | Out-Null | |
| 28 | if ($LASTEXITCODE -ne 0 -and (Get-Process -Id $_.ProcessId -ErrorAction SilentlyContinue)) { throw 'Unable to stop the previous agent. Close it and run the installer again.' } | |
| 29 | }`); | |
| 30 | else if (mac) { | |
| 31 | if (spawnSync('launchctl', ['print', `${domain}/net.paperclover.agent-relay`], { stdio: 'ignore' }).status !== 0) return; | |
| 32 | execFileSync('launchctl', ['bootout', `${domain}/net.paperclover.agent-relay`]); | |
| 33 | for (let attempt = 0; attempt < 40; attempt++) { | |
| 34 | try { execFileSync('launchctl', ['print', `${domain}/net.paperclover.agent-relay`], { stdio: 'ignore' }); } | |
| 35 | catch { return; } | |
| 36 | await sleep(250); | |
| 37 | } | |
| 38 | throw new Error('The previous agent is still stopping. Wait and run the installer again.'); | |
| 39 | } | |
| 40 | else if (spawnSync('systemctl', ['--user', 'show', '-P', 'LoadState', 'agent-relay.service'], { encoding: 'utf8' }).stdout.trim() === 'loaded') { | |
| 41 | execFileSync('systemctl', ['--user', 'stop', 'agent-relay.service']); | |
| 42 | } | |
| 43 | } | |
| 44 | ||
| 45 | async function main() { | |
| 46 | if (action === 'stop') { await stop(); return; } | |
| 47 | if (action === 'start') { | |
| 48 | if (windows) ps(`$ErrorActionPreference = 'Stop'; Start-ScheduledTask -TaskName ${psQuote(task)}`); | |
| 49 | else if (mac) { | |
| 50 | if (spawnSync('launchctl', ['print', `${domain}/net.paperclover.agent-relay`], { stdio: 'ignore' }).status === 0) { | |
| 51 | execFileSync('launchctl', ['kickstart', `${domain}/net.paperclover.agent-relay`], { stdio: 'inherit' }); | |
| 52 | } else execFileSync('launchctl', ['bootstrap', domain, unit], { stdio: 'inherit' }); | |
| 53 | } | |
| 54 | else execFileSync('systemctl', ['--user', 'start', 'agent-relay.service'], { stdio: 'inherit' }); | |
| 55 | return; | |
| 56 | } | |
| 57 | if (action === 'status') { | |
| 58 | if (windows) ps(`$ErrorActionPreference = 'Stop'; Get-ScheduledTask -TaskName ${psQuote(task)} | Select-Object TaskName,State`); | |
| 59 | else if (mac) execFileSync('launchctl', ['print', `${domain}/net.paperclover.agent-relay`], { stdio: 'inherit' }); | |
| 60 | else execFileSync('systemctl', ['--user', 'status', '--no-pager', 'agent-relay.service'], { stdio: 'inherit' }); | |
| 61 | return; | |
| 62 | } | |
| 63 | if (action === 'uninstall') { | |
| 64 | await stop(); | |
| 65 | if (windows) ps(`$ErrorActionPreference = 'Stop'; Unregister-ScheduledTask -TaskName ${psQuote(task)} -Confirm:$false`); | |
| 66 | else { | |
| 67 | if (!mac) execFileSync('systemctl', ['--user', 'disable', 'agent-relay.service'], { stdio: 'inherit' }); | |
| 68 | await rm(unit, { force: true }); | |
| 69 | if (!mac) execFileSync('systemctl', ['--user', 'daemon-reload']); | |
| 70 | } | |
| 71 | console.log(`Startup removed. Pairing and files remain in ${base} and ${data}.`); | |
| 72 | return; | |
| 73 | } | |
| 74 | if (action !== 'install' || !server || !installDir) throw new Error('Use install, status, start, stop, or uninstall.'); | |
| 75 | const origin = new URL(server); | |
| 76 | if (origin.origin !== server || (origin.protocol !== 'https:' && !(origin.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(origin.hostname)))) { | |
| 77 | throw new Error('Use an HTTPS dashboard origin, or localhost for a preview.'); | |
| 78 | } | |
| 79 | const staged = dirname(process.argv[1]); | |
| 80 | let previous; | |
| 81 | try { previous = JSON.parse(await readFile(join(data, 'agent.json'), 'utf8')); } | |
| 82 | catch (error) { if (error.code !== 'ENOENT') throw error; } | |
| 83 | if (previous && previous.server !== server) throw new Error(`This machine is paired to ${previous.server}. Unlink it there before changing dashboards.`); | |
| 84 | const input = createInterface({ input: process.stdin, output: process.stdout }); | |
| 85 | const closed = new AbortController(); | |
| 86 | input.once('close', () => closed.abort()); | |
| 87 | const ask = (text) => input.question(text, { signal: closed.signal }); | |
| 88 | let name, desktopWrite; | |
| 89 | const roots = []; | |
| 90 | try { | |
| 91 | console.log(`Agent Relay · ${server}\nCodex and Claude Code must already be installed and signed in.`); | |
| 92 | console.log('Linked clients can read saved Codex and Claude Code chats on this machine.'); | |
| 93 | name = previous ? 'this machine' : (await ask(`Machine name [${hostname()}]: `)).trim() || hostname(); | |
| 94 | if (previous) console.log('The existing machine pairing will be kept.'); | |
| 95 | if (name.length > 100) throw new Error('Enter a machine name up to 100 characters.'); | |
| 96 | console.log('Allowed folders apply to new chats. Existing chats keep their own permissions.'); | |
| 97 | if (previous?.roots?.length) console.log(`Current folders: ${previous.roots.join(', ')}`); | |
| 98 | console.log('Enter one project folder at a time. Leave blank to finish.'); | |
| 99 | if (previous) console.log('Leave the first answer blank to keep the current folders. Enter - to clear them.'); | |
| 100 | while (true) { | |
| 101 | const answer = (await ask('Project folder: ')).trim(); | |
| 102 | if (!answer) { if (!roots.length && previous) roots.push(...previous.roots); break; } | |
| 103 | if (answer === '-' && !roots.length) break; | |
| 104 | const path = await realpath(resolve(answer === '~' ? homedir() : answer.startsWith('~/') ? join(homedir(), answer.slice(2)) : answer)); | |
| 105 | if (!(await stat(path)).isDirectory()) throw new Error('Choose an existing project folder.'); | |
| 106 | if (!roots.includes(path)) roots.push(path); | |
| 107 | } | |
| 108 | if (!windows) { | |
| 109 | console.log('Experimental Codex desktop control lets linked clients send messages and interrupt chats. App updates may break it.'); | |
| 110 | const answer = (await ask(`Enable desktop control? [${previous?.desktopWrite ? 'Y/n' : 'y/N'}]: `)).trim().toLowerCase(); | |
| 111 | if (answer && !['y', 'yes', 'n', 'no'].includes(answer)) throw new Error('Answer yes or no.'); | |
| 112 | desktopWrite = answer ? ['y', 'yes'].includes(answer) : previous?.desktopWrite ?? false; | |
| 113 | } else desktopWrite = false; | |
| 114 | } catch (error) { | |
| 115 | if (closed.signal.aborted) throw new Error('Keep the terminal open to answer the install prompts, then run the installer again.'); | |
| 116 | throw error; | |
| 117 | } finally { input.close(); } | |
| 118 | await mkdir(data, { recursive: true, mode: 0o700 }); | |
| 119 | if (previous) { | |
| 120 | const response = await fetch(`${server}/pairing`, { headers: { Authorization: `Bearer ${previous.token}` }, signal: AbortSignal.timeout(10_000) }); | |
| 121 | if (!response.ok) throw new Error(`The saved pairing is unavailable (${response.status}). Check the dashboard before reinstalling.`); | |
| 122 | } else { | |
| 123 | await new Promise((accept, reject) => { | |
| 124 | const child = spawn(process.execPath, [join(staged, 'relay.mjs'), 'pair', '--server', server, '--name', name, '--data-dir', data, | |
| 125 | ...roots.flatMap((root) => ['--allow-root', root]), ...(desktopWrite ? ['--codex-desktop-write'] : [])], { stdio: 'inherit' }); | |
| 126 | child.on('error', reject); | |
| 127 | child.on('exit', (code) => code === 0 ? accept() : reject(new Error('Pairing stopped. Run the installer again for a new code.'))); | |
| 128 | }); | |
| 129 | previous = JSON.parse(await readFile(join(data, 'agent.json'), 'utf8')); | |
| 130 | } | |
| 131 | const config = { ...previous, roots, desktopWrite }; | |
| 132 | const binaries = {}; | |
| 133 | for (const cli of ['codex', 'claude']) { | |
| 134 | try { | |
| 135 | const found = windows ? execFileSync('where.exe', [cli], { encoding: 'utf8' }).trim().split(/\r?\n/)[0] : | |
| 136 | execFileSync('/bin/sh', ['-c', 'command -v "$1"', 'sh', cli], { encoding: 'utf8' }).trim(); | |
| 137 | if (found) binaries[cli] = found; | |
| 138 | } catch { console.log(`${cli} was not found. Install it and rerun this installer to enable its chats.`); } | |
| 139 | } | |
| 140 | await stop(); | |
| 141 | await writeFile(join(data, 'agent.json.pending'), JSON.stringify(config) + '\n', { mode: 0o600 }); | |
| 142 | await rename(join(data, 'agent.json.pending'), join(data, 'agent.json')); | |
| 143 | for (const file of ['relay.mjs', 'setup.mjs']) await copyFile(join(staged, file), join(base, file)); | |
| 144 | const args = [join(base, 'relay.mjs'), 'run', '--data-dir', data, | |
| 145 | ...Object.entries(binaries).flatMap(([cli, path]) => [`--${cli}-bin`, path])]; | |
| 146 | const environment = Object.fromEntries(['PATH', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR'].flatMap((key) => process.env[key] ? [[key, process.env[key]]] : [])); | |
| 147 | environment.PATH = [base, environment.PATH].filter(Boolean).join(delimiter); | |
| 148 | if (windows) { | |
| 149 | const runner = join(base, 'run.ps1'); | |
| 150 | await writeFile(runner, "$ErrorActionPreference = 'Stop'\n" + Object.entries(environment).map(([key, value]) => `$env:${key} = ${psQuote(value)}`).join('\n') + | |
| 151 | `\n& ${psQuote(process.execPath)} ${args.map(psQuote).join(' ')} *>> ${psQuote(join(base, 'agent.log'))}\nexit $LASTEXITCODE\n`); | |
| 152 | ps(`$ErrorActionPreference = 'Stop' | |
| 153 | $user = [Security.Principal.WindowsIdentity]::GetCurrent().Name | |
| 154 | $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument ${psQuote(`-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File "${runner}"`)} | |
| 155 | $trigger = New-ScheduledTaskTrigger -AtLogOn -User $user | |
| 156 | $principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited | |
| 157 | $settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries | |
| 158 | Register-ScheduledTask -TaskName ${psQuote(task)} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null | |
| 159 | Start-ScheduledTask -TaskName ${psQuote(task)} | |
| 160 | if ((Get-ScheduledTask -TaskName ${psQuote(task)}).State -eq 'Disabled') { throw 'Enable the Agent Relay task and run the installer again.' }`); | |
| 161 | await writeFile(join(base, 'agent-relay.cmd'), `@echo off\r\n"${process.execPath}" "${join(base, 'setup.mjs')}" %*\r\n`); | |
| 162 | } else { | |
| 163 | await mkdir(dirname(unit), { recursive: true }); | |
| 164 | if (mac) { | |
| 165 | const xml = (text) => text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&apos;'); | |
| 166 | await writeFile(unit, `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict> | |
| 167 | <key>Label</key><string>net.paperclover.agent-relay</string> | |
| 168 | <key>ProgramArguments</key><array>${[process.execPath, ...args].map((arg) => `<string>${xml(arg)}</string>`).join('')}</array> | |
| 169 | <key>EnvironmentVariables</key><dict>${Object.entries(environment).map(([key, value]) => `<key>${key}</key><string>${xml(value)}</string>`).join('')}</dict> | |
| 170 | <key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>30</integer> | |
| 171 | <key>StandardOutPath</key><string>${xml(join(base, 'agent.log'))}</string> | |
| 172 | <key>StandardErrorPath</key><string>${xml(join(base, 'agent.log'))}</string> | |
| 173 | </dict></plist>\n`); | |
| 174 | execFileSync('launchctl', ['bootstrap', domain, unit], { stdio: 'inherit' }); | |
| 175 | execFileSync('launchctl', ['print', `${domain}/net.paperclover.agent-relay`], { stdio: 'ignore' }); | |
| 176 | } else { | |
| 177 | const quote = (text) => '"' + text.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('\n', '\\n').replaceAll('\r', '\\r').replaceAll('%', '%%') + '"'; | |
| 178 | await writeFile(unit, `[Unit]\nDescription=Agent Relay\n\n[Service]\nExecStart=${[process.execPath, ...args].map((arg) => quote(arg).replaceAll('$', '$$')).join(' ')}\n` + | |
| 179 | Object.entries(environment).map(([key, value]) => `Environment=${quote(`${key}=${value}`)}`).join('\n') + | |
| 180 | '\nRestart=on-failure\nRestartSec=30\nUMask=0077\n\n[Install]\nWantedBy=default.target\n'); | |
| 181 | execFileSync('systemctl', ['--user', 'daemon-reload']); | |
| 182 | execFileSync('systemctl', ['--user', 'enable', '--now', 'agent-relay.service'], { stdio: 'inherit' }); | |
| 183 | execFileSync('systemctl', ['--user', 'is-active', '--quiet', 'agent-relay.service']); | |
| 184 | } | |
| 185 | await writeFile(join(base, 'agent-relay'), `#!/bin/sh\nexec ${shellQuote(process.execPath)} ${shellQuote(join(base, 'setup.mjs'))} "$@"\n`, { mode: 0o700 }); | |
| 186 | } | |
| 187 | console.log(`Installed. Agent Relay starts at login.\nOpen ${server}/mcp/settings/agents and check that ${name} is online.`); | |
| 188 | const manage = join(base, windows ? 'agent-relay.cmd' : 'agent-relay'); | |
| 189 | console.log(`Check startup: ${windows ? '& ' + psQuote(manage) : shellQuote(manage)} status\nUse start, stop, or uninstall in place of status.`); | |
| 190 | } | |
| 191 | ||
| 192 | main().catch((error) => { console.error(error.message); process.exitCode = 1; }); |
dashboard/agent/source.json deleted-4| ... | ... | @@ -1,4 +0,0 @@ |
| 1 | { | |
| 2 | "source": "../../../agent-relay", | |
| 3 | "entry": "src/agent.ts" | |
| 4 | } |
dashboard/src/main.rs-4| ... | ... | @@ -14,7 +14,6 @@ mod index; |
| 14 | 14 | mod mcp; |
| 15 | 15 | mod observability; |
| 16 | 16 | mod oidc; |
| 17 | mod relay; | |
| 18 | 17 | mod shale; |
| 19 | 18 | mod shale_page; |
| 20 | 19 | mod shares; |
| ... | ... | @@ -94,7 +93,6 @@ impl Document { |
| 94 | 93 | struct App { |
| 95 | 94 | auth: auth::Store, |
| 96 | 95 | mcp: mcp::Store, |
| 97 | relay: relay::Broker, | |
| 98 | 96 | shale: shale::Backend, |
| 99 | 97 | http: reqwest::Client, |
| 100 | 98 | shale_http: reqwest::Client, |
| ... | ... | @@ -538,7 +536,6 @@ async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { |
| 538 | 536 | auth, |
| 539 | 537 | mcp: mcp::Store::new(&PathBuf::from(env("SNOWGLOBE_DATA_DIR", "data")), &origin) |
| 540 | 538 | .map_err(|error| std::io::Error::other(error.message))?, |
| 541 | relay: relay::Broker::default(), | |
| 542 | 539 | shale: shale::Backend::new( |
| 543 | 540 | &env( |
| 544 | 541 | "SNOWGLOBE_SHALE_URL", |
| ... | ... | @@ -596,7 +593,6 @@ async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { |
| 596 | 593 | .merge(observability::router(app.clone())) |
| 597 | 594 | .merge(computer::router(app.clone())) |
| 598 | 595 | .merge(shale::router(app.clone())) |
| 599 | .merge(relay::router(app.clone())) | |
| 600 | 596 | .fallback_service( |
| 601 | 597 | ServeDir::new(&dist).fallback(ServeFile::new(format!("{dist}/index.html"))), |
| 602 | 598 | ) |
dashboard/src/mcp.rs+40-50| ... | ... | @@ -14,11 +14,6 @@ const CATALOGS: &[(&str, &str, &[&str])] = &[ |
| 14 | 14 | "Logs and traces", |
| 15 | 15 | &["observability:read", "offline_access"], |
| 16 | 16 | ), |
| 17 | ( | |
| 18 | "agents", | |
| 19 | "Local agents", | |
| 20 | &["sessions:read", "sessions:write", "offline_access"], | |
| 21 | ), | |
| 22 | 17 | ( |
| 23 | 18 | "shale", |
| 24 | 19 | "Shale", |
| ... | ... | @@ -329,6 +324,12 @@ impl Store { |
| 329 | 324 | } |
| 330 | 325 | _ => return Err(fail("unsupported_grant_type")), |
| 331 | 326 | }; |
| 327 | if !CATALOGS | |
| 328 | .iter() | |
| 329 | .any(|(id, _, _)| grant["resource"] == self.resource(id)) | |
| 330 | { | |
| 331 | return Err(fail("invalid_grant")); | |
| 332 | } | |
| 332 | 333 | Ok((key, grant)) |
| 333 | 334 | } |
| 334 | 335 | fn oauth( |
| ... | ... | @@ -606,13 +607,6 @@ pub fn public(path: &str) -> bool { |
| 606 | 607 | path == format!("/mcp/{id}") || path.starts_with(&format!("/mcp/{id}/")) |
| 607 | 608 | }) |
| 608 | 609 | || path.starts_with("/.well-known/oauth-") |
| 609 | || path == "/pairing" | |
| 610 | || path == "/agent/connect" | |
| 611 | || matches!( | |
| 612 | path, | |
| 613 | "/agent/install.sh" | "/agent/install.ps1" | "/agent/setup.mjs" | "/agent/relay.mjs" | |
| 614 | ) | |
| 615 | || path.starts_with("/api/v1/") | |
| 616 | 610 | } |
| 617 | 611 | pub async fn oauth(State(app): State<Arc<App>>, request: Request) -> Response { |
| 618 | 612 | if request.uri().path().starts_with("/oauth/shale/") { |
| ... | ... | @@ -720,19 +714,6 @@ pub async fn manage( |
| 720 | 714 | if parts == ["shale"] { |
| 721 | 715 | return shale::manage(app, method, &owner, &body).await; |
| 722 | 716 | } |
| 723 | if parts == ["relay", "live"] && method == Method::GET { | |
| 724 | let owner = owner_id.to_owned(); | |
| 725 | let stream = WatchStream::new(app.relay.changes.subscribe()).map(move |_| { | |
| 726 | let machines = relay::machines(&app.mcp.db.lock().unwrap(), &owner) | |
| 727 | .map(|machines| app.relay.view(machines, None)); | |
| 728 | machines | |
| 729 | .map(|machines| Event::default().json_data(machines).unwrap()) | |
| 730 | .map_err(|error| std::io::Error::other(error.message)) | |
| 731 | }); | |
| 732 | return Ok(Sse::new(stream) | |
| 733 | .keep_alive(axum::response::sse::KeepAlive::default()) | |
| 734 | .into_response()); | |
| 735 | } | |
| 736 | 717 | let consent_resource = if let ["connections", id] = parts |
| 737 | 718 | && method != Method::DELETE |
| 738 | 719 | { |
| ... | ... | @@ -762,21 +743,18 @@ pub async fn manage( |
| 762 | 743 | } else { |
| 763 | 744 | String::new() |
| 764 | 745 | }; |
| 765 | let agent_consent = consent_resource == app.mcp.resource("agents"); | |
| 766 | 746 | let shale_consent = consent_resource == app.mcp.resource("shale"); |
| 767 | 747 | let catalog = CATALOGS |
| 768 | 748 | .iter() |
| 769 | 749 | .find(|(id, _, _)| consent_resource == app.mcp.resource(id)) |
| 770 | 750 | .map(|(id, _, _)| *id); |
| 751 | if !consent_resource.is_empty() && catalog.is_none() { | |
| 752 | return Err(Error::new(404, "No connector here.")); | |
| 753 | } | |
| 771 | 754 | let mut linked = true; |
| 772 | 755 | let mut resource_error = None; |
| 773 | 756 | let resources: Vec<Value> = if body["deny"] == true { |
| 774 | 757 | Vec::new() |
| 775 | } else if agent_consent { | |
| 776 | relay::machines(&app.mcp.db.lock().unwrap(), owner_id)? | |
| 777 | .into_iter() | |
| 778 | .map(|m| json!({"id":m["id"],"name":m["name"]})) | |
| 779 | .collect() | |
| 780 | 758 | } else if shale_consent { |
| 781 | 759 | let available = if body["resources"] == "all" { |
| 782 | 760 | shale::verified_session(&app, owner_id) |
| ... | ... | @@ -824,19 +802,18 @@ pub async fn manage( |
| 824 | 802 | [] if method == Method::GET => { |
| 825 | 803 | let mut grants = list(&tx, "grant:")?; |
| 826 | 804 | grants.retain(|g| g["user"] == owner_id); |
| 827 | let machines = relay::machines(&tx, owner_id)?; | |
| 828 | let connections = grants.iter().map(|grant| { | |
| 829 | let name = if grant["client"].is_null() {grant["name"].clone()} else {get(&tx, &format!("client:{}", string(&grant["client"])))?["client_name"].clone()}; | |
| 830 | let resources = if grant["resource"] == app.mcp.resource("shale") && grant["resources"] == "all" {json!("all")} else {json!(array(&grant["resources"]).iter().map(|id| if grant["resource"] == app.mcp.resource("agents") {machines.iter().find(|m| m["id"] == *id).map(|m| m["name"].clone()).unwrap_or_else(|| json!("Unlinked machine"))} else {id.clone()}).collect::<Vec<_>>())}; | |
| 831 | let catalog = CATALOGS.iter().find(|(id, _, _)| grant["resource"] == app.mcp.resource(id)).map(|(id, _, _)| *id); | |
| 832 | Ok(json!({"id":grant["id"],"name":name,"catalog":catalog,"resources":resources,"scopes":grant["scopes"],"createdAt":grant["createdAt"]})) | |
| 805 | let connections = grants.iter().filter_map(|grant| { | |
| 806 | let (catalog, _, _) = CATALOGS.iter().find(|(id, _, _)| grant["resource"] == app.mcp.resource(id))?; | |
| 807 | Some(get(&tx, &format!("client:{}", string(&grant["client"]))).map(|client| { | |
| 808 | json!({"id":grant["id"],"name":client["client_name"],"catalog":catalog,"resources":grant["resources"],"scopes":grant["scopes"],"createdAt":grant["createdAt"]}) | |
| 809 | })) | |
| 833 | 810 | }).collect::<Result<Vec<_>>>()?; |
| 834 | 811 | let shale = get(&tx, &format!("shale-session:{owner_id}"))?; |
| 835 | 812 | let catalogs: Vec<_> = CATALOGS |
| 836 | 813 | .iter() |
| 837 | 814 | .map(|(id, name, _)| json!({"id":id,"name":name,"endpoint":app.mcp.resource(id)})) |
| 838 | 815 | .collect(); |
| 839 | json!({"catalogs":catalogs,"connections":connections,"machines":app.relay.view(machines,None),"shale":if shale["origin"] != app.shale.origin.as_str() {Value::Null} else {json!({"linkedAt":shale["linkedAt"]})}}) | |
| 816 | json!({"catalogs":catalogs,"connections":connections,"shale":if shale["origin"] != app.shale.origin.as_str() {Value::Null} else {json!({"linkedAt":shale["linkedAt"]})}}) | |
| 840 | 817 | } |
| 841 | 818 | ["consent", id] if method == Method::GET || method == Method::POST => { |
| 842 | 819 | let key = format!("pending:{}", hash(id)); |
| ... | ... | @@ -897,10 +874,7 @@ pub async fn manage( |
| 897 | 874 | )); |
| 898 | 875 | } |
| 899 | 876 | let grant_id = uuid::Uuid::new_v4().to_string(); |
| 900 | let mut grant = json!({"id":grant_id,"user":owner_id,"client":pending["client"],"resource":pending["resource"],"scopes":pending["scopes"],"resources":chosen,"createdAt":now()}); | |
| 901 | if agent_consent { | |
| 902 | grant["targets"] = json!(chosen); | |
| 903 | } | |
| 877 | let grant = json!({"id":grant_id,"user":owner_id,"client":pending["client"],"resource":pending["resource"],"scopes":pending["scopes"],"resources":chosen,"createdAt":now()}); | |
| 904 | 878 | put(&tx, &format!("grant:{grant_id}"), &grant, 0)?; |
| 905 | 879 | let code = secret(); |
| 906 | 880 | pending["grant"] = json!(grant_id); |
| ... | ... | @@ -917,7 +891,6 @@ pub async fn manage( |
| 917 | 891 | json!({"redirect":target.as_str()}) |
| 918 | 892 | } |
| 919 | 893 | } |
| 920 | ["relay", rest @ ..] => relay::manage(&app, &tx, rest, method, owner_id, &body)?, | |
| 921 | 894 | ["connections", id] |
| 922 | 895 | if method == Method::GET || method == Method::POST || method == Method::DELETE => |
| 923 | 896 | { |
| ... | ... | @@ -940,9 +913,6 @@ pub async fn manage( |
| 940 | 913 | } |
| 941 | 914 | let chosen = chosen_resources(&body, &resources, shale_consent)?; |
| 942 | 915 | grant["resources"] = json!(chosen); |
| 943 | if agent_consent { | |
| 944 | grant["targets"] = json!(chosen); | |
| 945 | } | |
| 946 | 916 | tx.execute( |
| 947 | 917 | "UPDATE records SET value=? WHERE key=?", |
| 948 | 918 | rusqlite::params![grant.to_string(), key], |
| ... | ... | @@ -953,9 +923,6 @@ pub async fn manage( |
| 953 | 923 | _ => return Err(Error::new(404, "No endpoint here.")), |
| 954 | 924 | }; |
| 955 | 925 | tx.commit()?; |
| 956 | if matches!(parts, ["relay", "pair"] | ["relay", "machines", _]) { | |
| 957 | app.relay.changes.send_replace(()); | |
| 958 | } | |
| 959 | 926 | Ok(if value.is_null() { |
| 960 | 927 | StatusCode::NO_CONTENT.into_response() |
| 961 | 928 | } else { |
| ... | ... | @@ -1069,7 +1036,7 @@ mod tests { |
| 1069 | 1036 | json!({"client_name":"Codex","redirect_uris":[uri]})).unwrap()).await; |
| 1070 | 1037 | let mut request = fields(json!({"response_type":"code","client_id":client["client_id"],"state":"fixture-state", |
| 1071 | 1038 | "code_challenge":"AdJpfUsRa6XMg54f2khmgo2onMwePN3vmU9DOOoaTzo","code_challenge_method":"S256", |
| 1072 | "redirect_uri":uri,"scope":"observability:read offline_access sessions:read sessions:write shale:read shale:write computer:read computer:control"})); | |
| 1039 | "redirect_uri":uri,"scope":"observability:read offline_access shale:read shale:write computer:read computer:control"})); | |
| 1073 | 1040 | for (catalog, _, allowed) in CATALOGS { |
| 1074 | 1041 | request.insert("resource".into(), fixture.store.resource(catalog)); |
| 1075 | 1042 | let response = fixture.store.oauth("authorize", &Method::GET, &request, &HeaderMap::new(), Value::Null).unwrap(); |
| ... | ... | @@ -1102,6 +1069,29 @@ mod tests { |
| 1102 | 1069 | request.insert("redirect_uri".into(), uri.replace("H9rAWI-8eQbv", "different")); |
| 1103 | 1070 | assert_eq!(fixture.store.oauth("authorize", &Method::GET, &request, &HeaderMap::new(), Value::Null).unwrap_err().message, "invalid_redirect_uri"); |
| 1104 | 1071 | } |
| 1072 | #[test] | |
| 1073 | fn removed_catalogs_cannot_authorize_or_exchange_tokens() { | |
| 1074 | let fixture = Fixture::new(); | |
| 1075 | let mut input = fixture.code("one", "owned-code"); | |
| 1076 | let resource = fixture.store.resource("agents"); | |
| 1077 | let tokens = { | |
| 1078 | let db = fixture.store.db.lock().unwrap(); | |
| 1079 | let key = format!("code:{}", hash("owned-code")); | |
| 1080 | let mut code = get(&db, &key).unwrap(); | |
| 1081 | let mut grant = get(&db, &format!("grant:{}", string(&code["grant"]))).unwrap(); | |
| 1082 | code["resource"] = json!(resource); | |
| 1083 | grant["resource"] = json!(resource); | |
| 1084 | put(&db, &key, &code, 300).unwrap(); | |
| 1085 | put(&db, &format!("grant:{}", string(&grant["id"])), &grant, 0).unwrap(); | |
| 1086 | fixture.store.issue(&db, &grant).unwrap() | |
| 1087 | }; | |
| 1088 | input.insert("resource".into(), resource.clone()); | |
| 1089 | let refresh = fields(json!({"grant_type":"refresh_token","client_id":"one","refresh_token":tokens["refresh_token"]})); | |
| 1090 | for request in [&input, &refresh] { | |
| 1091 | assert_eq!(fixture.store.oauth("token", &Method::POST, request, &HeaderMap::new(), Value::Null).unwrap_err().message, "invalid_grant"); | |
| 1092 | } | |
| 1093 | assert_eq!(fixture.store.oauth("authorize", &Method::GET, &fields(json!({"resource":resource})), &HeaderMap::new(), Value::Null).unwrap_err().message, "invalid_target"); | |
| 1094 | } | |
| 1105 | 1095 | #[tokio::test] |
| 1106 | 1096 | async fn code_binds_pkce_client_redirect_and_audience_without_consuming_on_failure() { |
| 1107 | 1097 | let fixture = Fixture::new(); |
dashboard/src/relay.rs deleted-1111| ... | ... | @@ -1,1111 +0,0 @@ |
| 1 | use crate::*; | |
| 2 | use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; | |
| 3 | use futures::SinkExt; | |
| 4 | use mcp::{delete, get, hash, list, put, secret}; | |
| 5 | use rmcp::{ | |
| 6 | ErrorData, RoleServer, ServerHandler, | |
| 7 | model::{ | |
| 8 | CacheScope, CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, | |
| 9 | ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerConfig, Tool, | |
| 10 | ToolAnnotations, | |
| 11 | }, | |
| 12 | service::RequestContext, | |
| 13 | }; | |
| 14 | use tokio::sync::{mpsc, oneshot}; | |
| 15 | ||
| 16 | pub struct Broker { | |
| 17 | connections: Mutex<HashMap<String, Arc<Connection>>>, | |
| 18 | pending_slots: Semaphore, | |
| 19 | pub(crate) changes: watch::Sender<()>, | |
| 20 | } | |
| 21 | impl Default for Broker { | |
| 22 | fn default() -> Self { | |
| 23 | Self { | |
| 24 | connections: Mutex::new(HashMap::new()), | |
| 25 | pending_slots: Semaphore::new(128), | |
| 26 | changes: watch::channel(()).0, | |
| 27 | } | |
| 28 | } | |
| 29 | } | |
| 30 | struct Connection { | |
| 31 | messages: mpsc::Sender<Message>, | |
| 32 | pending: Mutex<HashMap<String, oneshot::Sender<Result<Value>>>>, | |
| 33 | closed: watch::Sender<bool>, | |
| 34 | } | |
| 35 | struct Pending { | |
| 36 | connection: Arc<Connection>, | |
| 37 | id: String, | |
| 38 | } | |
| 39 | impl Drop for Pending { | |
| 40 | fn drop(&mut self) { | |
| 41 | self.connection.pending.lock().unwrap().remove(&self.id); | |
| 42 | } | |
| 43 | } | |
| 44 | fn unknown() -> Error { | |
| 45 | Error::new( | |
| 46 | 409, | |
| 47 | "Command outcome is unknown. Read the thread before retrying.", | |
| 48 | ) | |
| 49 | } | |
| 50 | impl Broker { | |
| 51 | pub fn disconnect(&self, id: &str) { | |
| 52 | if let Some(connection) = self.connections.lock().unwrap().remove(id) { | |
| 53 | self.changes.send_replace(()); | |
| 54 | connection.closed.send_replace(true); | |
| 55 | for (_, response) in connection.pending.lock().unwrap().drain() { | |
| 56 | let _ = response.send(Err(unknown())); | |
| 57 | } | |
| 58 | } | |
| 59 | } | |
| 60 | fn remove(&self, id: &str, connection: &Arc<Connection>) { | |
| 61 | let mut connections = self.connections.lock().unwrap(); | |
| 62 | if connections | |
| 63 | .get(id) | |
| 64 | .is_some_and(|current| Arc::ptr_eq(current, connection)) | |
| 65 | { | |
| 66 | connections.remove(id); | |
| 67 | self.changes.send_replace(()); | |
| 68 | } | |
| 69 | connection.closed.send_replace(true); | |
| 70 | for (_, response) in connection.pending.lock().unwrap().drain() { | |
| 71 | let _ = response.send(Err(unknown())); | |
| 72 | } | |
| 73 | } | |
| 74 | pub fn view(&self, machines: Vec<Value>, grant: Option<&Value>) -> Vec<Value> { | |
| 75 | let connections = self.connections.lock().unwrap(); | |
| 76 | machines | |
| 77 | .into_iter() | |
| 78 | .filter(|machine| grant.is_none_or(|g| array(&g["resources"]).contains(&machine["id"]))) | |
| 79 | .map(|mut machine| { | |
| 80 | machine.as_object_mut().unwrap().remove("tokenHash"); | |
| 81 | machine.as_object_mut().unwrap().remove("user"); | |
| 82 | machine["online"] = json!(connections.contains_key(string(&machine["id"]))); | |
| 83 | if let Some(grant) = grant { | |
| 84 | machine["selected"] = json!(array(&grant["targets"]).contains(&machine["id"])); | |
| 85 | } | |
| 86 | machine | |
| 87 | }) | |
| 88 | .collect() | |
| 89 | } | |
| 90 | async fn dispatch( | |
| 91 | &self, | |
| 92 | store: &mcp::Store, | |
| 93 | grant_id: &str, | |
| 94 | machine_id: &str, | |
| 95 | method: &str, | |
| 96 | params: Value, | |
| 97 | deadline: Duration, | |
| 98 | ) -> Result<Value> { | |
| 99 | let params = command(method, params)?; | |
| 100 | let (pending, receive, slot) = { | |
| 101 | let db = store.db.lock().unwrap(); | |
| 102 | let grant = get(&db, &format!("grant:{grant_id}"))?; | |
| 103 | let machine = get(&db, &format!("machine:{machine_id}"))?; | |
| 104 | if grant.is_null() | |
| 105 | || grant["resource"] != store.resource("agents") | |
| 106 | || machine.is_null() | |
| 107 | || machine["user"] != grant["user"] | |
| 108 | || !array(&grant["resources"]).iter().any(|id| id == machine_id) | |
| 109 | { | |
| 110 | return Err(Error::new( | |
| 111 | 403, | |
| 112 | "Choose a machine granted to this connection.", | |
| 113 | )); | |
| 114 | } | |
| 115 | let scope = if matches!(method, "send_message" | "interrupt_thread" | "start_thread") { | |
| 116 | "sessions:write" | |
| 117 | } else { | |
| 118 | "sessions:read" | |
| 119 | }; | |
| 120 | if !array(&grant["scopes"]).iter().any(|s| s == scope) { | |
| 121 | return Err(Error::new( | |
| 122 | 403, | |
| 123 | "This connection has read access only. Connect again to request control.", | |
| 124 | )); | |
| 125 | } | |
| 126 | let slot = self.pending_slots.try_acquire().map_err(|_| { | |
| 127 | Error::new( | |
| 128 | 429, | |
| 129 | "The relay has too many pending commands. Try again shortly.", | |
| 130 | ) | |
| 131 | })?; | |
| 132 | let connection = self | |
| 133 | .connections | |
| 134 | .lock() | |
| 135 | .unwrap() | |
| 136 | .get(machine_id) | |
| 137 | .cloned() | |
| 138 | .ok_or_else(|| Error::new(409, "Machine is offline. Start its local agent."))?; | |
| 139 | let (send, receive) = oneshot::channel(); | |
| 140 | let id = uuid::Uuid::new_v4().to_string(); | |
| 141 | { | |
| 142 | let mut pending = connection.pending.lock().unwrap(); | |
| 143 | if *connection.closed.borrow() { | |
| 144 | return Err(Error::new( | |
| 145 | 409, | |
| 146 | "Machine is offline. Start its local agent.", | |
| 147 | )); | |
| 148 | } | |
| 149 | if pending.len() >= 8 { | |
| 150 | return Err(Error::new( | |
| 151 | 429, | |
| 152 | "Machine has eight pending commands. Wait for one to finish.", | |
| 153 | )); | |
| 154 | } | |
| 155 | pending.insert(id.clone(), send); | |
| 156 | } | |
| 157 | let pending = Pending { | |
| 158 | connection: connection.clone(), | |
| 159 | id: id.clone(), | |
| 160 | }; | |
| 161 | let frame = json!({"id":id,"method":method,"params":params}).to_string(); | |
| 162 | if frame.len() > 256 * 1024 { | |
| 163 | return Err(Error::new( | |
| 164 | 413, | |
| 165 | "Send a shorter message. Local agent commands are limited to 256 KB.", | |
| 166 | )); | |
| 167 | } | |
| 168 | let frame = Message::Text(frame.into()); | |
| 169 | if connection.messages.try_send(frame).is_err() { | |
| 170 | return Err(unknown()); | |
| 171 | } | |
| 172 | (pending, receive, slot) | |
| 173 | }; | |
| 174 | let result = tokio::time::timeout(deadline, receive) | |
| 175 | .await | |
| 176 | .map_err(|_| unknown())? | |
| 177 | .map_err(|_| unknown())?; | |
| 178 | drop(pending); | |
| 179 | drop(slot); | |
| 180 | result | |
| 181 | } | |
| 182 | } | |
| 183 | pub(crate) fn machines(db: &rusqlite::Connection, user: &str) -> Result<Vec<Value>> { | |
| 184 | Ok(list(db, "machine:")? | |
| 185 | .into_iter() | |
| 186 | .filter(|m| m["user"] == user) | |
| 187 | .collect()) | |
| 188 | } | |
| 189 | fn device(db: &rusqlite::Connection, headers: &HeaderMap) -> Result<Value> { | |
| 190 | let token = headers | |
| 191 | .get("authorization") | |
| 192 | .and_then(|v| v.to_str().ok()) | |
| 193 | .and_then(|s| s.strip_prefix("Bearer ")) | |
| 194 | .filter(|s| !s.is_empty() && s.len() <= 256) | |
| 195 | .ok_or_else(|| Error::new(401, "Pair this machine again."))?; | |
| 196 | let fingerprint = hash(token); | |
| 197 | list(db, "machine:")? | |
| 198 | .into_iter() | |
| 199 | .find(|machine| { | |
| 200 | string(&machine["tokenHash"]) | |
| 201 | .as_bytes() | |
| 202 | .ct_eq(fingerprint.as_bytes()) | |
| 203 | .unwrap_u8() | |
| 204 | == 1 | |
| 205 | }) | |
| 206 | .ok_or_else(|| Error::new(401, "Pair this machine again.")) | |
| 207 | } | |
| 208 | fn name(value: &Value) -> Result<&str> { | |
| 209 | value | |
| 210 | .as_str() | |
| 211 | .filter(|s| !s.trim().is_empty() && s.encode_utf16().count() <= 100) | |
| 212 | .ok_or_else(|| Error::new(400, "Enter a name up to 100 characters.")) | |
| 213 | } | |
| 214 | pub(crate) fn manage( | |
| 215 | app: &App, | |
| 216 | db: &rusqlite::Connection, | |
| 217 | parts: &[&str], | |
| 218 | method: &Method, | |
| 219 | owner: &str, | |
| 220 | body: &Value, | |
| 221 | ) -> Result<Value> { | |
| 222 | match parts { | |
| 223 | ["pair"] if method == Method::POST => { | |
| 224 | let code = body["code"] | |
| 225 | .as_str() | |
| 226 | .filter(|s| !s.is_empty() && s.len() <= 40) | |
| 227 | .ok_or_else(|| Error::new(400, "Enter the code from your local agent."))?; | |
| 228 | let code: String = code | |
| 229 | .chars() | |
| 230 | .filter(|c| *c != '-' && !c.is_whitespace()) | |
| 231 | .flat_map(char::to_uppercase) | |
| 232 | .collect(); | |
| 233 | let key = format!("pair:{}", hash(&code)); | |
| 234 | let pairing = get(db, &key)?; | |
| 235 | if pairing.is_null() { | |
| 236 | return Err(Error::new( | |
| 237 | 410, | |
| 238 | "This code expired or was used. Start pairing again.", | |
| 239 | )); | |
| 240 | } | |
| 241 | if machines(db, owner)?.len() >= 128 { | |
| 242 | return Err(Error::new( | |
| 243 | 409, | |
| 244 | "Unlink an unused machine before adding another.", | |
| 245 | )); | |
| 246 | } | |
| 247 | let id = uuid::Uuid::new_v4().to_string(); | |
| 248 | let machine = json!({"id":id,"user":owner,"name":pairing["name"],"platform":pairing["platform"],"tokenHash":pairing["tokenHash"]}); | |
| 249 | put(db, &format!("machine:{id}"), &machine, 0)?; | |
| 250 | delete(db, &key)?; | |
| 251 | Ok(json!(app.relay.view(vec![machine], None).remove(0))) | |
| 252 | } | |
| 253 | ["machines", id] if method == Method::DELETE || method == Method::PATCH => { | |
| 254 | let mut machine = get(db, &format!("machine:{id}"))?; | |
| 255 | if machine["user"] != owner { | |
| 256 | return Err(Error::new(404, "No linked machine with that ID.")); | |
| 257 | } | |
| 258 | if method == Method::DELETE { | |
| 259 | delete(db, &format!("machine:{id}"))?; | |
| 260 | app.relay.disconnect(id); | |
| 261 | Ok(Value::Null) | |
| 262 | } else { | |
| 263 | machine["name"] = json!(name(&body["name"])?); | |
| 264 | put(db, &format!("machine:{id}"), &machine, 0)?; | |
| 265 | Ok(json!(app.relay.view(vec![machine], None).remove(0))) | |
| 266 | } | |
| 267 | } | |
| 268 | ["keys"] if method == Method::POST => { | |
| 269 | let available = machines(db, owner)?; | |
| 270 | let resources = selection( | |
| 271 | &body["resources"], | |
| 272 | &available | |
| 273 | .iter() | |
| 274 | .map(|m| m["id"].clone()) | |
| 275 | .collect::<Vec<_>>(), | |
| 276 | )?; | |
| 277 | let name = name(&body["name"])?; | |
| 278 | let write = body | |
| 279 | .get("write") | |
| 280 | .map(|v| { | |
| 281 | v.as_bool() | |
| 282 | .ok_or_else(|| Error::new(400, "Choose read access or control.")) | |
| 283 | }) | |
| 284 | .transpose()? | |
| 285 | .unwrap_or(false); | |
| 286 | if list(db, "grant:")? | |
| 287 | .iter() | |
| 288 | .filter(|g| g["user"] == owner) | |
| 289 | .count() | |
| 290 | >= 256 | |
| 291 | { | |
| 292 | return Err(Error::new( | |
| 293 | 409, | |
| 294 | "Revoke an unused connection before adding another.", | |
| 295 | )); | |
| 296 | } | |
| 297 | let id = uuid::Uuid::new_v4().to_string(); | |
| 298 | let grant = json!({"id":id,"user":owner,"name":name,"client":null,"resource":app.mcp.resource("agents"),"scopes":if write {json!(["sessions:read","sessions:write"])} else {json!(["sessions:read"])},"resources":resources,"targets":resources,"createdAt":now()}); | |
| 299 | let key = format!("ar_{}", secret()); | |
| 300 | put(db, &format!("grant:{id}"), &grant, 0)?; | |
| 301 | put( | |
| 302 | db, | |
| 303 | &format!("access:{}", hash(&key)), | |
| 304 | &json!({"grant":id,"resource":grant["resource"]}), | |
| 305 | 0, | |
| 306 | )?; | |
| 307 | Ok(json!({"key":key,"id":id})) | |
| 308 | } | |
| 309 | _ => Err(Error::new(404, "No endpoint here.")), | |
| 310 | } | |
| 311 | } | |
| 312 | fn selection(value: &Value, allowed: &[Value]) -> Result<Vec<Value>> { | |
| 313 | let ids = value | |
| 314 | .as_array() | |
| 315 | .filter(|ids| !ids.is_empty() && ids.len() <= 128) | |
| 316 | .ok_or_else(|| Error::new(400, "Choose at least one linked machine."))?; | |
| 317 | if ids | |
| 318 | .iter() | |
| 319 | .enumerate() | |
| 320 | .any(|(i, id)| !allowed.contains(id) || ids[..i].contains(id)) | |
| 321 | { | |
| 322 | return Err(Error::new( | |
| 323 | 403, | |
| 324 | "Choose machines granted to this connection once each.", | |
| 325 | )); | |
| 326 | } | |
| 327 | Ok(ids.clone()) | |
| 328 | } | |
| 329 | fn view(app: &App, grant_id: &str, targets: Option<&Value>) -> Result<Vec<Value>> { | |
| 330 | let mut db = app.mcp.db.lock().unwrap(); | |
| 331 | let tx = db.transaction()?; | |
| 332 | let mut grant = get(&tx, &format!("grant:{grant_id}"))?; | |
| 333 | if grant.is_null() || grant["resource"] != app.mcp.resource("agents") { | |
| 334 | return Err(Error::new( | |
| 335 | 401, | |
| 336 | "This connection was revoked. Connect again.", | |
| 337 | )); | |
| 338 | } | |
| 339 | let machines = machines(&tx, string(&grant["user"]))?; | |
| 340 | if let Some(targets) = targets { | |
| 341 | let allowed: Vec<_> = machines | |
| 342 | .iter() | |
| 343 | .filter(|m| array(&grant["resources"]).contains(&m["id"])) | |
| 344 | .map(|m| m["id"].clone()) | |
| 345 | .collect(); | |
| 346 | grant["targets"] = json!(selection(targets, &allowed)?); | |
| 347 | put(&tx, &format!("grant:{grant_id}"), &grant, 0)?; | |
| 348 | } | |
| 349 | let result = app.relay.view(machines, Some(&grant)); | |
| 350 | tx.commit()?; | |
| 351 | Ok(result) | |
| 352 | } | |
| 353 | fn schema(method: &str) -> Option<Value> { | |
| 354 | let provider = json!({"type":"string","enum":["codex","claude"]}); | |
| 355 | let id = json!({"type":"string","format":"uuid"}); | |
| 356 | let message = json!({"type":"string","minLength":1,"maxLength":100000}); | |
| 357 | let (properties, required) = match method { | |
| 358 | "list_threads" => ( | |
| 359 | json!({"provider":provider,"limit":{"type":"integer","minimum":1,"maximum":100,"default":30}}), | |
| 360 | json!([]), | |
| 361 | ), | |
| 362 | "read_thread" => ( | |
| 363 | json!({"provider":provider,"thread_id":id,"cursor":{"type":"string","minLength":1,"maxLength":512},"limit":{"type":"integer","minimum":1,"maximum":100,"default":20}}), | |
| 364 | json!(["provider", "thread_id"]), | |
| 365 | ), | |
| 366 | "send_message" => ( | |
| 367 | json!({"provider":provider,"thread_id":id,"message":message,"expected_turn_id":id}), | |
| 368 | json!(["provider", "thread_id", "message"]), | |
| 369 | ), | |
| 370 | "interrupt_thread" => ( | |
| 371 | json!({"provider":provider,"thread_id":id,"expected_turn_id":id}), | |
| 372 | json!(["provider", "thread_id"]), | |
| 373 | ), | |
| 374 | "start_thread" => ( | |
| 375 | json!({"provider":provider,"cwd":{"type":"string","minLength":1,"maxLength":4096},"message":message}), | |
| 376 | json!(["provider", "cwd", "message"]), | |
| 377 | ), | |
| 378 | _ => return None, | |
| 379 | }; | |
| 380 | Some( | |
| 381 | json!({"type":"object","properties":properties,"required":required,"additionalProperties":false}), | |
| 382 | ) | |
| 383 | } | |
| 384 | fn command(method: &str, value: Value) -> Result<Value> { | |
| 385 | let schema = schema(method) | |
| 386 | .ok_or_else(|| Error::new(404, "Choose a session tool listed by this connector."))?; | |
| 387 | let mut params = value | |
| 388 | .as_object() | |
| 389 | .cloned() | |
| 390 | .ok_or_else(|| Error::new(400, "Use the fields listed for this tool."))?; | |
| 391 | let properties = schema["properties"].as_object().unwrap(); | |
| 392 | if params.keys().any(|key| !properties.contains_key(key)) | |
| 393 | || array(&schema["required"]) | |
| 394 | .iter() | |
| 395 | .any(|key| !params.contains_key(string(key))) | |
| 396 | { | |
| 397 | return Err(Error::new(400, "Use the fields listed for this tool.")); | |
| 398 | } | |
| 399 | for (key, rule) in properties { | |
| 400 | if !params.contains_key(key) && rule.get("default").is_some() { | |
| 401 | params.insert(key.clone(), rule["default"].clone()); | |
| 402 | } | |
| 403 | let Some(value) = params.get(key) else { | |
| 404 | continue; | |
| 405 | }; | |
| 406 | let valid = match string(&rule["type"]) { | |
| 407 | "integer" => value.as_i64().is_some_and(|n| { | |
| 408 | n >= rule["minimum"].as_i64().unwrap() && n <= rule["maximum"].as_i64().unwrap() | |
| 409 | }), | |
| 410 | "string" => value.as_str().is_some_and(|s| { | |
| 411 | let length = s.encode_utf16().count() as u64; | |
| 412 | rule["minLength"].as_u64().is_none_or(|n| length >= n) | |
| 413 | && rule["maxLength"].as_u64().is_none_or(|n| length <= n) | |
| 414 | && rule | |
| 415 | .get("enum") | |
| 416 | .is_none_or(|values| array(values).contains(value)) | |
| 417 | && (rule["format"] != "uuid" | |
| 418 | || uuid::Uuid::parse_str(s) | |
| 419 | .is_ok_and(|id| id.to_string().eq_ignore_ascii_case(s))) | |
| 420 | }), | |
| 421 | _ => false, | |
| 422 | }; | |
| 423 | if !valid { | |
| 424 | return Err(Error::new( | |
| 425 | 400, | |
| 426 | format!("Check {key} against the tool's fields."), | |
| 427 | )); | |
| 428 | } | |
| 429 | } | |
| 430 | Ok(json!(params)) | |
| 431 | } | |
| 432 | async fn pairing(State(app): State<Arc<App>>, request: Request) -> Result<Response> { | |
| 433 | let method = request.method().clone(); | |
| 434 | let headers = request.headers().clone(); | |
| 435 | let bytes = axum::body::to_bytes(request.into_body(), 4096) | |
| 436 | .await | |
| 437 | .map_err(|_| Error::new(400, "Enter a shorter machine name."))?; | |
| 438 | let mut db = app.mcp.db.lock().unwrap(); | |
| 439 | let tx = db.transaction()?; | |
| 440 | let response = if method == Method::POST { | |
| 441 | if list(&tx, "pair:")?.len() >= 256 { | |
| 442 | return Err(Error::new( | |
| 443 | 429, | |
| 444 | "Too many pairing requests. Try again in ten minutes.", | |
| 445 | )); | |
| 446 | } | |
| 447 | let body: Value = serde_json::from_slice(&bytes) | |
| 448 | .map_err(|_| Error::new(400, "Enter a machine name and platform."))?; | |
| 449 | let name = name(&body["name"])?; | |
| 450 | let platform = body["platform"] | |
| 451 | .as_str() | |
| 452 | .filter(|s| s.encode_utf16().count() <= 100) | |
| 453 | .ok_or_else(|| Error::new(400, "Enter a platform up to 100 characters."))?; | |
| 454 | let token = secret(); | |
| 455 | let code: String = rand::random::<[u8; 5]>() | |
| 456 | .iter() | |
| 457 | .map(|b| format!("{b:02X}")) | |
| 458 | .collect(); | |
| 459 | put( | |
| 460 | &tx, | |
| 461 | &format!("pair:{}", hash(&code)), | |
| 462 | &json!({"name":name,"platform":platform,"tokenHash":hash(&token)}), | |
| 463 | 600, | |
| 464 | )?; | |
| 465 | (StatusCode::CREATED, axum::Json(json!({"code":format!("{}-{}", &code[..5], &code[5..]),"token":token,"expires_in":600}))).into_response() | |
| 466 | } else if method == Method::GET { | |
| 467 | match device(&tx, &headers) { | |
| 468 | Ok(machine) => axum::Json(json!({"machine_id":machine["id"]})).into_response(), | |
| 469 | Err(_) => { | |
| 470 | let token = headers | |
| 471 | .get("authorization") | |
| 472 | .and_then(|v| v.to_str().ok()) | |
| 473 | .and_then(|s| s.strip_prefix("Bearer ")) | |
| 474 | .filter(|s| !s.is_empty() && s.len() <= 256) | |
| 475 | .ok_or_else(|| Error::new(401, "Start pairing from your local agent."))?; | |
| 476 | if !list(&tx, "pair:")? | |
| 477 | .iter() | |
| 478 | .any(|p| p["tokenHash"] == hash(token)) | |
| 479 | { | |
| 480 | return Err(Error::new( | |
| 481 | 410, | |
| 482 | "This pairing expired. Start pairing again.", | |
| 483 | )); | |
| 484 | } | |
| 485 | (StatusCode::ACCEPTED, axum::Json(json!({"pending":true}))).into_response() | |
| 486 | } | |
| 487 | } | |
| 488 | } else { | |
| 489 | return Err(Error::new(405, "Use GET or POST for pairing.")); | |
| 490 | }; | |
| 491 | tx.commit()?; | |
| 492 | Ok(response) | |
| 493 | } | |
| 494 | async fn connect( | |
| 495 | State(app): State<Arc<App>>, | |
| 496 | headers: HeaderMap, | |
| 497 | ws: WebSocketUpgrade, | |
| 498 | ) -> Result<Response> { | |
| 499 | if headers.contains_key("origin") { | |
| 500 | return Err(Error::new(401, "Connect from your local agent.")); | |
| 501 | } | |
| 502 | let machine = device(&app.mcp.db.lock().unwrap(), &headers)?; | |
| 503 | let id = string(&machine["id"]).to_owned(); | |
| 504 | let (send, receive) = mpsc::channel(16); | |
| 505 | let (closed, _) = watch::channel(false); | |
| 506 | let connection = Arc::new(Connection { | |
| 507 | messages: send, | |
| 508 | pending: Mutex::new(HashMap::new()), | |
| 509 | closed, | |
| 510 | }); | |
| 511 | { | |
| 512 | let mut connections = app.relay.connections.lock().unwrap(); | |
| 513 | if connections.contains_key(&id) { | |
| 514 | return Err(Error::new( | |
| 515 | 409, | |
| 516 | "Another agent is connected. Stop it before starting a second copy.", | |
| 517 | )); | |
| 518 | } | |
| 519 | if connections.len() >= 256 { | |
| 520 | return Err(Error::new( | |
| 521 | 503, | |
| 522 | "Too many agents are connected. Try again later.", | |
| 523 | )); | |
| 524 | } | |
| 525 | connections.insert(id.clone(), connection.clone()); | |
| 526 | app.relay.changes.send_replace(()); | |
| 527 | } | |
| 528 | let (failure_app, failure_id, failure_connection) = | |
| 529 | (app.clone(), id.clone(), connection.clone()); | |
| 530 | Ok(ws | |
| 531 | .max_frame_size(4 * 1024 * 1024) | |
| 532 | .max_message_size(4 * 1024 * 1024) | |
| 533 | .read_buffer_size(16 * 1024) | |
| 534 | .write_buffer_size(0) | |
| 535 | .max_write_buffer_size(256 * 1024) | |
| 536 | .on_failed_upgrade(move |_| failure_app.relay.remove(&failure_id, &failure_connection)) | |
| 537 | .on_upgrade(move |socket| session(app, id, connection, receive, socket))) | |
| 538 | } | |
| 539 | async fn session( | |
| 540 | app: Arc<App>, | |
| 541 | id: String, | |
| 542 | connection: Arc<Connection>, | |
| 543 | mut messages: mpsc::Receiver<Message>, | |
| 544 | mut socket: WebSocket, | |
| 545 | ) { | |
| 546 | let mut closed = connection.closed.subscribe(); | |
| 547 | let connected = Message::Text( | |
| 548 | json!({"type":"connected","machine_id":id}) | |
| 549 | .to_string() | |
| 550 | .into(), | |
| 551 | ); | |
| 552 | if tokio::time::timeout(Duration::from_secs(5), socket.send(connected)) | |
| 553 | .await | |
| 554 | .is_ok_and(|r| r.is_ok()) | |
| 555 | { | |
| 556 | let mut heartbeat = tokio::time::interval_at( | |
| 557 | tokio::time::Instant::now() + Duration::from_secs(20), | |
| 558 | Duration::from_secs(20), | |
| 559 | ); | |
| 560 | heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); | |
| 561 | let mut alive = true; | |
| 562 | loop { | |
| 563 | if *closed.borrow() | |
| 564 | || !get(&app.mcp.db.lock().unwrap(), &format!("machine:{id}")) | |
| 565 | .is_ok_and(|m| !m.is_null()) | |
| 566 | { | |
| 567 | break; | |
| 568 | } | |
| 569 | let outgoing = tokio::select! { | |
| 570 | _ = closed.changed() => break, | |
| 571 | outgoing = messages.recv() => match outgoing {Some(frame) => frame, None => break}, | |
| 572 | _ = heartbeat.tick() => { | |
| 573 | if !alive {break;} | |
| 574 | alive = false; | |
| 575 | Message::Ping(Bytes::new()) | |
| 576 | }, | |
| 577 | incoming = socket.recv() => { | |
| 578 | match incoming { | |
| 579 | Some(Ok(Message::Pong(_))) => alive = true, | |
| 580 | Some(Ok(Message::Ping(bytes))) => { | |
| 581 | if !tokio::time::timeout(Duration::from_secs(5), socket.send(Message::Pong(bytes))).await.is_ok_and(|r| r.is_ok()) {break;} | |
| 582 | }, | |
| 583 | Some(Ok(Message::Text(text))) => { | |
| 584 | let reply = serde_json::from_str::<Value>(&text); | |
| 585 | let Ok(reply) = reply else {break}; | |
| 586 | let valid = reply.as_object().is_some_and(|fields| fields.keys().all(|k| ["id","result","error"].contains(&k.as_str()))) | |
| 587 | && reply["id"].as_str().is_some_and(|s| uuid::Uuid::parse_str(s).is_ok()) | |
| 588 | && (reply.get("result").is_some() != reply.get("error").is_some()) | |
| 589 | && reply.get("error").is_none_or(|error| error.as_str().is_some_and(|s| s.encode_utf16().count() <= 2000)); | |
| 590 | if !valid {break;} | |
| 591 | if let Some(send) = connection.pending.lock().unwrap().remove(string(&reply["id"])) { | |
| 592 | let result = if let Some(error) = reply["error"].as_str() {Err(Error::new(400, error))} else {Ok(reply["result"].clone())}; | |
| 593 | let _ = send.send(result); | |
| 594 | } | |
| 595 | }, | |
| 596 | _ => break, | |
| 597 | } | |
| 598 | continue; | |
| 599 | } | |
| 600 | }; | |
| 601 | if !tokio::time::timeout(Duration::from_secs(5), socket.send(outgoing)) | |
| 602 | .await | |
| 603 | .is_ok_and(|r| r.is_ok()) | |
| 604 | { | |
| 605 | break; | |
| 606 | } | |
| 607 | } | |
| 608 | } | |
| 609 | app.relay.remove(&id, &connection); | |
| 610 | let _ = tokio::time::timeout(Duration::from_secs(1), socket.close()).await; | |
| 611 | } | |
| 612 | async fn rest(State(app): State<Arc<App>>, request: Request) -> Response { | |
| 613 | let result: Result<Response> = async { | |
| 614 | if request.headers().get("origin").is_some_and(|v| { | |
| 615 | v.to_str().ok() != Some(app.mcp.origin.origin().ascii_serialization().as_str()) | |
| 616 | }) { | |
| 617 | return Err(Error::new(403, "Use the relay from its own origin.")); | |
| 618 | } | |
| 619 | let grant = app | |
| 620 | .mcp | |
| 621 | .authenticate(request.headers(), &app.mcp.resource("agents"))?; | |
| 622 | if !mcp::active_owner(&app, &grant)? { | |
| 623 | return Err(Error::new(401, "This connection's account is no longer authorized.")); | |
| 624 | } | |
| 625 | let id = string(&grant["id"]); | |
| 626 | let method = request.method().clone(); | |
| 627 | let path = request | |
| 628 | .uri() | |
| 629 | .path() | |
| 630 | .trim_start_matches("/api/v1/") | |
| 631 | .to_owned(); | |
| 632 | let bytes = axum::body::to_bytes(request.into_body(), 256 * 1024) | |
| 633 | .await | |
| 634 | .map_err(|_| Error::new(400, "Send a shorter command."))?; | |
| 635 | let body: Value = if bytes.is_empty() { | |
| 636 | Value::Null | |
| 637 | } else { | |
| 638 | serde_json::from_slice(&bytes).map_err(|_| Error::new(400, "Use JSON command fields."))? | |
| 639 | }; | |
| 640 | let value = match path.split('/').collect::<Vec<_>>().as_slice() { | |
| 641 | ["machines"] if method == Method::GET => json!(view(&app, id, None)?), | |
| 642 | ["targets"] if method == Method::PUT => json!(view(&app, id, Some(&body["machine_ids"]))?), | |
| 643 | ["machines", machine, "commands"] if method == Method::POST => { | |
| 644 | let method = body["method"] | |
| 645 | .as_str() | |
| 646 | .ok_or_else(|| Error::new(400, "Choose a session command."))?; | |
| 647 | json!({"result":app.relay.dispatch(&app.mcp, id, machine, method, body["params"].clone(), Duration::from_secs(30)).await?}) | |
| 648 | } | |
| 649 | _ => return Err(Error::new(404, "No relay endpoint here.")), | |
| 650 | }; | |
| 651 | Ok(axum::Json(value).into_response()) | |
| 652 | }.await; | |
| 653 | match result { | |
| 654 | Ok(response) => response, | |
| 655 | Err(error) => (StatusCode::from_u16(error.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), axum::Json(json!({"error":if error.status >= 500 {"The relay couldn't answer. Check its dashboard and retry."} else {&error.message}}))).into_response(), | |
| 656 | } | |
| 657 | } | |
| 658 | #[derive(Clone)] | |
| 659 | struct Agents(Arc<App>); | |
| 660 | impl ServerHandler for Agents { | |
| 661 | fn get_info(&self) -> ServerConfig { | |
| 662 | ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) | |
| 663 | } | |
| 664 | async fn list_tools( | |
| 665 | &self, | |
| 666 | _: Option<PaginatedRequestParams>, | |
| 667 | _: RequestContext<RoleServer>, | |
| 668 | ) -> std::result::Result<ListToolsResult, ErrorData> { | |
| 669 | let tools = [ | |
| 670 | ("list_machines", "List granted machines and their connection state."), | |
| 671 | ("set_target_machines", "Select default machines for this connection."), | |
| 672 | ("list_threads", "List recent Codex and Claude Code threads on selected machines."), | |
| 673 | ("read_thread", "Read a thread and its current status."), | |
| 674 | ("send_message", "Submit a message. Desktop control requires local opt-in and reopens unloaded chats, switching the selected desktop chat. Submission acknowledges delivery, not task completion."), | |
| 675 | ("interrupt_thread", "Interrupt an agent-owned session or an opted-in Codex desktop turn."), | |
| 676 | ("start_thread", "Start an agent-owned session under a locally allowed directory."), | |
| 677 | ].into_iter().map(|(name, description)| { | |
| 678 | let mut schema = schema(name).unwrap_or_else(|| if name == "set_target_machines" {json!({"type":"object","properties":{"machine_ids":{"type":"array","items":{"type":"string","format":"uuid"},"minItems":1,"maxItems":128,"uniqueItems":true}},"required":["machine_ids"],"additionalProperties":false})} else {json!({"type":"object","properties":{},"additionalProperties":false})}); | |
| 679 | if !["list_machines","set_target_machines"].contains(&name) {schema["properties"]["machine_id"] = json!({"type":"string","format":"uuid"});} | |
| 680 | let read = ["list_machines","list_threads","read_thread"].contains(&name); | |
| 681 | Tool::new(name, description, schema.as_object().unwrap().clone()).with_annotations(ToolAnnotations::new().read_only(read).destructive(name == "interrupt_thread").idempotent(read)) | |
| 682 | }).collect(); | |
| 683 | Ok(ListToolsResult { | |
| 684 | tools, | |
| 685 | ttl_ms: Some(0), | |
| 686 | cache_scope: Some(CacheScope::Private), | |
| 687 | ..Default::default() | |
| 688 | }) | |
| 689 | } | |
| 690 | async fn call_tool( | |
| 691 | &self, | |
| 692 | request: CallToolRequestParams, | |
| 693 | context: RequestContext<RoleServer>, | |
| 694 | ) -> std::result::Result<CallToolResponse, ErrorData> { | |
| 695 | let result: Result<CallToolResult> = async { | |
| 696 | let grant = &context | |
| 697 | .extensions | |
| 698 | .get::<axum::http::request::Parts>() | |
| 699 | .and_then(|parts| parts.extensions.get::<mcp::Grant>()) | |
| 700 | .ok_or_else(|| Error::new(401, "This connection expired. Connect again."))? | |
| 701 | .0; | |
| 702 | let mut arguments = request.arguments.unwrap_or_default(); | |
| 703 | let id = string(&grant["id"]); | |
| 704 | match request.name.as_ref() { | |
| 705 | "list_machines" if arguments.is_empty() => Ok(CallToolResult::structured( | |
| 706 | json!({"machines":view(&self.0, id, None)?}), | |
| 707 | )), | |
| 708 | "set_target_machines" | |
| 709 | if arguments.len() == 1 && arguments.contains_key("machine_ids") => | |
| 710 | { | |
| 711 | Ok(CallToolResult::structured( | |
| 712 | json!({"machines":view(&self.0, id, arguments.get("machine_ids"))?}), | |
| 713 | )) | |
| 714 | } | |
| 715 | method => { | |
| 716 | let explicit = arguments.remove("machine_id"); | |
| 717 | let machines = view(&self.0, id, None)?; | |
| 718 | let targets: Vec<_> = if let Some(explicit) = explicit { | |
| 719 | let explicit = explicit | |
| 720 | .as_str() | |
| 721 | .ok_or_else(|| Error::new(400, "Choose a machine ID."))?; | |
| 722 | if !machines.iter().any(|m| m["id"] == explicit) { | |
| 723 | return Err(Error::new(403, "Choose a granted machine.")); | |
| 724 | } | |
| 725 | vec![explicit.to_owned()] | |
| 726 | } else { | |
| 727 | machines | |
| 728 | .iter() | |
| 729 | .filter(|m| m["selected"] == true) | |
| 730 | .map(|m| string(&m["id"]).to_owned()) | |
| 731 | .collect() | |
| 732 | }; | |
| 733 | if targets.is_empty() || method != "list_threads" && targets.len() != 1 { | |
| 734 | return Err(Error::new( | |
| 735 | 400, | |
| 736 | "Select one machine or supply machine_id for this command.", | |
| 737 | )); | |
| 738 | } | |
| 739 | let params = command(method, json!(arguments))?; | |
| 740 | let mut replies: futures::stream::FuturesUnordered<_> = targets.into_iter().map(|machine| { | |
| 741 | let params = params.clone(); | |
| 742 | async move { | |
| 743 | match self | |
| 744 | .0 | |
| 745 | .relay | |
| 746 | .dispatch( | |
| 747 | &self.0.mcp, | |
| 748 | id, | |
| 749 | &machine, | |
| 750 | method, | |
| 751 | params, | |
| 752 | Duration::from_secs(30), | |
| 753 | ) | |
| 754 | .await | |
| 755 | { | |
| 756 | Ok(result) => json!({"machine_id":machine,"result":result}), | |
| 757 | Err(error) => json!({"machine_id":machine,"error":error.message}), | |
| 758 | } | |
| 759 | } | |
| 760 | }).collect(); | |
| 761 | let mut results = Vec::new(); | |
| 762 | let mut bytes = 0; | |
| 763 | while let Some(reply) = futures::StreamExt::next(&mut replies).await { | |
| 764 | bytes += reply.to_string().len(); | |
| 765 | if bytes > 16*1024*1024 {return Err(Error::new(413, "Machine replies exceed 16 MB. Select fewer machines or request fewer messages."));} | |
| 766 | results.push(reply); | |
| 767 | } | |
| 768 | let errors = results.iter().any(|r| r.get("error").is_some()); | |
| 769 | let mut result = CallToolResult::structured(json!({"results":results})); | |
| 770 | result.is_error = Some(errors); | |
| 771 | Ok(result) | |
| 772 | } | |
| 773 | } | |
| 774 | } | |
| 775 | .await; | |
| 776 | Ok(match result { | |
| 777 | Ok(result) => result, | |
| 778 | Err(error) => CallToolResult::error(vec![ContentBlock::text(if error.status >= 500 { | |
| 779 | "The relay couldn't answer. Check its dashboard and retry.".to_owned() | |
| 780 | } else { | |
| 781 | error.message | |
| 782 | })]), | |
| 783 | } | |
| 784 | .into()) | |
| 785 | } | |
| 786 | } | |
| 787 | async fn installer(State(app): State<Arc<App>>, request: Request) -> Response { | |
| 788 | let origin = app.mcp.origin.origin().ascii_serialization(); | |
| 789 | let source = if request.uri().path().ends_with(".ps1") { | |
| 790 | include_str!("../agent/install.ps1") | |
| 791 | .replace("__SERVER__", &format!("'{}'", origin.replace('\'', "''"))) | |
| 792 | } else { | |
| 793 | include_str!("../agent/install.sh").replace( | |
| 794 | "__SERVER__", | |
| 795 | &format!("'{}'", origin.replace('\'', "'\\''")), | |
| 796 | ) | |
| 797 | }; | |
| 798 | ([("content-type", "text/plain; charset=utf-8")], source).into_response() | |
| 799 | } | |
| 800 | pub fn router(app: Arc<App>) -> Router { | |
| 801 | let state = app.clone(); | |
| 802 | let expected_host = | |
| 803 | app.mcp.origin[url::Position::BeforeHost..url::Position::AfterPort].to_owned(); | |
| 804 | let agent = env("SNOWGLOBE_AGENT_DIR", "agent"); | |
| 805 | Router::new() | |
| 806 | .route("/pairing", any(pairing)) | |
| 807 | .route("/agent/connect", any(connect)) | |
| 808 | .route("/agent/install.sh", axum::routing::get(installer)) | |
| 809 | .route("/agent/install.ps1", axum::routing::get(installer)) | |
| 810 | .route_service( | |
| 811 | "/agent/setup.mjs", | |
| 812 | ServeFile::new(format!("{agent}/setup.mjs")), | |
| 813 | ) | |
| 814 | .route_service( | |
| 815 | "/agent/relay.mjs", | |
| 816 | ServeFile::new(format!("{agent}/relay.mjs")), | |
| 817 | ) | |
| 818 | .route("/api/v1/{*path}", any(rest)) | |
| 819 | .with_state(app.clone()) | |
| 820 | .merge(mcp::router(app, "agents", move || { | |
| 821 | Ok(Agents(state.clone())) | |
| 822 | })) | |
| 823 | .layer(axum::middleware::from_fn( | |
| 824 | move |request: Request, next: axum::middleware::Next| { | |
| 825 | let host = expected_host.clone(); | |
| 826 | async move { | |
| 827 | if request.headers().get("host").and_then(|v| v.to_str().ok()) != Some(&host) { | |
| 828 | return StatusCode::MISDIRECTED_REQUEST.into_response(); | |
| 829 | } | |
| 830 | next.run(request).await | |
| 831 | } | |
| 832 | }, | |
| 833 | )) | |
| 834 | } | |
| 835 | ||
| 836 | #[cfg(test)] | |
| 837 | mod tests { | |
| 838 | use super::*; | |
| 839 | struct Fixture { | |
| 840 | store: Arc<mcp::Store>, | |
| 841 | broker: Arc<Broker>, | |
| 842 | path: PathBuf, | |
| 843 | machine: String, | |
| 844 | grant: String, | |
| 845 | } | |
| 846 | impl Fixture { | |
| 847 | fn new(write: bool) -> Self { | |
| 848 | let path = std::env::temp_dir() | |
| 849 | .canonicalize() | |
| 850 | .unwrap() | |
| 851 | .join(format!("snowglobe-relay-test-{}", uuid::Uuid::new_v4())); | |
| 852 | let store = Arc::new(mcp::Store::new(&path, "https://globe.snowglobe.test").unwrap()); | |
| 853 | let machine = uuid::Uuid::new_v4().to_string(); | |
| 854 | let grant = uuid::Uuid::new_v4().to_string(); | |
| 855 | { | |
| 856 | let db = store.db.lock().unwrap(); | |
| 857 | put(&db, &format!("machine:{machine}"), &json!({"id":machine,"user":"owner","name":"Fixture","tokenHash":hash("device-secret")}), 0).unwrap(); | |
| 858 | put(&db, &format!("grant:{grant}"), &json!({"id":grant,"user":"owner","resource":store.resource("agents"),"resources":[machine],"scopes":if write {json!(["sessions:read","sessions:write"])} else {json!(["sessions:read"])}}), 0).unwrap(); | |
| 859 | } | |
| 860 | Self { | |
| 861 | store, | |
| 862 | broker: Arc::new(Broker::default()), | |
| 863 | path, | |
| 864 | machine, | |
| 865 | grant, | |
| 866 | } | |
| 867 | } | |
| 868 | fn connect(&self) -> (Arc<Connection>, mpsc::Receiver<Message>) { | |
| 869 | let (messages, receive) = mpsc::channel(16); | |
| 870 | let (closed, _) = watch::channel(false); | |
| 871 | let connection = Arc::new(Connection { | |
| 872 | messages, | |
| 873 | closed, | |
| 874 | pending: Mutex::new(HashMap::new()), | |
| 875 | }); | |
| 876 | self.broker | |
| 877 | .connections | |
| 878 | .lock() | |
| 879 | .unwrap() | |
| 880 | .insert(self.machine.clone(), connection.clone()); | |
| 881 | (connection, receive) | |
| 882 | } | |
| 883 | fn dispatch(&self, duration: Duration) -> tokio::task::JoinHandle<Result<Value>> { | |
| 884 | let (store, broker, machine, grant) = ( | |
| 885 | self.store.clone(), | |
| 886 | self.broker.clone(), | |
| 887 | self.machine.clone(), | |
| 888 | self.grant.clone(), | |
| 889 | ); | |
| 890 | tokio::spawn(async move { | |
| 891 | broker | |
| 892 | .dispatch( | |
| 893 | &store, | |
| 894 | &grant, | |
| 895 | &machine, | |
| 896 | "list_threads", | |
| 897 | json!({}), | |
| 898 | duration, | |
| 899 | ) | |
| 900 | .await | |
| 901 | }) | |
| 902 | } | |
| 903 | } | |
| 904 | impl Drop for Fixture { | |
| 905 | fn drop(&mut self) { | |
| 906 | std::fs::remove_dir_all(&self.path).unwrap(); | |
| 907 | } | |
| 908 | } | |
| 909 | #[test] | |
| 910 | fn command_fields_defaults_and_provider_boundaries() { | |
| 911 | assert_eq!( | |
| 912 | command("list_threads", json!({})).unwrap(), | |
| 913 | json!({"limit":30}) | |
| 914 | ); | |
| 915 | let id = uuid::Uuid::new_v4().to_string(); | |
| 916 | assert_eq!( | |
| 917 | command("read_thread", json!({"provider":"claude","thread_id":id})).unwrap()["limit"], | |
| 918 | 20 | |
| 919 | ); | |
| 920 | assert_eq!( | |
| 921 | command( | |
| 922 | "read_thread", | |
| 923 | json!({"provider":"codex","thread_id":id,"cursor":"page"}) | |
| 924 | ) | |
| 925 | .unwrap()["cursor"], | |
| 926 | "page" | |
| 927 | ); | |
| 928 | for (method, params) in [ | |
| 929 | ( | |
| 930 | "read_thread", | |
| 931 | json!({"provider":"codex","thread_id":id,"cursor":""}), | |
| 932 | ), | |
| 933 | ( | |
| 934 | "read_thread", | |
| 935 | json!({"provider":"codex","thread_id":id,"cursor":"x".repeat(513)}), | |
| 936 | ), | |
| 937 | ( | |
| 938 | "read_thread", | |
| 939 | json!({"provider":"codex","thread_id":"not-a-uuid"}), | |
| 940 | ), | |
| 941 | ( | |
| 942 | "read_thread", | |
| 943 | json!({"provider":"native-chat","thread_id":id}), | |
| 944 | ), | |
| 945 | ("list_threads", json!({"limit":101})), | |
| 946 | ("list_threads", json!({"limit":1.5})), | |
| 947 | ("list_threads", json!({"approval_response":true})), | |
| 948 | ( | |
| 949 | "send_message", | |
| 950 | json!({"provider":"codex","thread_id":id,"message":""}), | |
| 951 | ), | |
| 952 | ("start_thread", json!({"provider":"claude","cwd":"/tmp"})), | |
| 953 | ( | |
| 954 | "interrupt_thread", | |
| 955 | json!({"provider":"codex","thread_id":id,"expected_turn_id":1}), | |
| 956 | ), | |
| 957 | ("approve_tool", json!({})), | |
| 958 | ] { | |
| 959 | assert!(command(method, params).is_err(), "{method}"); | |
| 960 | } | |
| 961 | } | |
| 962 | #[tokio::test] | |
| 963 | async fn dispatch_uses_current_owner_grant_and_control_scope() { | |
| 964 | let fixture = Fixture::new(false); | |
| 965 | let (connection, mut receive) = fixture.connect(); | |
| 966 | let task = fixture.dispatch(Duration::from_secs(2)); | |
| 967 | let Message::Text(frame) = receive.recv().await.unwrap() else { | |
| 968 | panic!() | |
| 969 | }; | |
| 970 | let frame: Value = serde_json::from_str(&frame).unwrap(); | |
| 971 | assert_eq!(frame["params"], json!({"limit":30})); | |
| 972 | connection | |
| 973 | .pending | |
| 974 | .lock() | |
| 975 | .unwrap() | |
| 976 | .remove(string(&frame["id"])) | |
| 977 | .unwrap() | |
| 978 | .send(Ok(json!({"threads":[]}))) | |
| 979 | .unwrap(); | |
| 980 | assert_eq!(task.await.unwrap().unwrap(), json!({"threads":[]})); | |
| 981 | let refused = fixture | |
| 982 | .broker | |
| 983 | .dispatch( | |
| 984 | &fixture.store, | |
| 985 | &fixture.grant, | |
| 986 | &fixture.machine, | |
| 987 | "start_thread", | |
| 988 | json!({"provider":"codex","cwd":"/tmp","message":"owned fixture"}), | |
| 989 | Duration::from_secs(2), | |
| 990 | ) | |
| 991 | .await | |
| 992 | .unwrap_err(); | |
| 993 | assert_eq!(refused.status, 403); | |
| 994 | assert!(receive.try_recv().is_err()); | |
| 995 | let foreign = uuid::Uuid::new_v4().to_string(); | |
| 996 | { | |
| 997 | let db = fixture.store.db.lock().unwrap(); | |
| 998 | let mut grant = get(&db, &format!("grant:{}", fixture.grant)).unwrap(); | |
| 999 | grant["resources"] = json!([foreign]); | |
| 1000 | put(&db, &format!("grant:{}", fixture.grant), &grant, 0).unwrap(); | |
| 1001 | put( | |
| 1002 | &db, | |
| 1003 | &format!("machine:{foreign}"), | |
| 1004 | &json!({"id":foreign,"user":"someone-else"}), | |
| 1005 | 0, | |
| 1006 | ) | |
| 1007 | .unwrap(); | |
| 1008 | } | |
| 1009 | assert_eq!( | |
| 1010 | fixture | |
| 1011 | .broker | |
| 1012 | .dispatch( | |
| 1013 | &fixture.store, | |
| 1014 | &fixture.grant, | |
| 1015 | &foreign, | |
| 1016 | "list_threads", | |
| 1017 | json!({}), | |
| 1018 | Duration::from_secs(2) | |
| 1019 | ) | |
| 1020 | .await | |
| 1021 | .unwrap_err() | |
| 1022 | .status, | |
| 1023 | 403 | |
| 1024 | ); | |
| 1025 | delete( | |
| 1026 | &fixture.store.db.lock().unwrap(), | |
| 1027 | &format!("grant:{}", fixture.grant), | |
| 1028 | ) | |
| 1029 | .unwrap(); | |
| 1030 | assert_eq!( | |
| 1031 | fixture | |
| 1032 | .dispatch(Duration::from_secs(2)) | |
| 1033 | .await | |
| 1034 | .unwrap() | |
| 1035 | .unwrap_err() | |
| 1036 | .status, | |
| 1037 | 403 | |
| 1038 | ); | |
| 1039 | } | |
| 1040 | #[tokio::test] | |
| 1041 | async fn unicode_message_cannot_exceed_local_agent_frame_budget() { | |
| 1042 | let fixture = Fixture::new(true); | |
| 1043 | let (connection, mut receive) = fixture.connect(); | |
| 1044 | let error = fixture.broker.dispatch(&fixture.store, &fixture.grant, &fixture.machine, "send_message", json!({"provider":"codex","thread_id":uuid::Uuid::new_v4().to_string(),"message":"雪".repeat(100000)}), Duration::from_secs(2)).await.unwrap_err(); | |
| 1045 | assert_eq!(error.status, 413); | |
| 1046 | assert!(receive.try_recv().is_err()); | |
| 1047 | assert!(connection.pending.lock().unwrap().is_empty()); | |
| 1048 | assert_eq!(fixture.broker.pending_slots.available_permits(), 128); | |
| 1049 | } | |
| 1050 | #[tokio::test] | |
| 1051 | async fn eight_pending_limit_and_cancellation_release_capacity() { | |
| 1052 | let fixture = Fixture::new(true); | |
| 1053 | let (connection, mut receive) = fixture.connect(); | |
| 1054 | let mut tasks = Vec::new(); | |
| 1055 | for _ in 0..8 { | |
| 1056 | tasks.push(fixture.dispatch(Duration::from_secs(2))); | |
| 1057 | receive.recv().await.unwrap(); | |
| 1058 | } | |
| 1059 | assert_eq!( | |
| 1060 | fixture | |
| 1061 | .dispatch(Duration::from_secs(2)) | |
| 1062 | .await | |
| 1063 | .unwrap() | |
| 1064 | .unwrap_err() | |
| 1065 | .status, | |
| 1066 | 429 | |
| 1067 | ); | |
| 1068 | tasks.remove(0).abort(); | |
| 1069 | tokio::task::yield_now().await; | |
| 1070 | assert_eq!(connection.pending.lock().unwrap().len(), 7); | |
| 1071 | tasks.push(fixture.dispatch(Duration::from_secs(2))); | |
| 1072 | receive.recv().await.unwrap(); | |
| 1073 | assert_eq!(connection.pending.lock().unwrap().len(), 8); | |
| 1074 | fixture.broker.disconnect(&fixture.machine); | |
| 1075 | for task in tasks { | |
| 1076 | assert!(task.await.unwrap().unwrap_err().message.contains("unknown")); | |
| 1077 | } | |
| 1078 | assert!(connection.pending.lock().unwrap().is_empty()); | |
| 1079 | } | |
| 1080 | #[tokio::test] | |
| 1081 | async fn timeout_disconnect_and_reconnect_do_not_replay() { | |
| 1082 | let fixture = Fixture::new(true); | |
| 1083 | let (old, mut receive) = fixture.connect(); | |
| 1084 | let task = fixture.dispatch(Duration::from_millis(5)); | |
| 1085 | receive.recv().await.unwrap(); | |
| 1086 | assert!(task.await.unwrap().unwrap_err().message.contains("unknown")); | |
| 1087 | assert!(old.pending.lock().unwrap().is_empty()); | |
| 1088 | assert!(receive.try_recv().is_err()); | |
| 1089 | let task = fixture.dispatch(Duration::from_secs(2)); | |
| 1090 | receive.recv().await.unwrap(); | |
| 1091 | fixture.broker.disconnect(&fixture.machine); | |
| 1092 | assert!(task.await.unwrap().unwrap_err().message.contains("unknown")); | |
| 1093 | let (new, mut receive) = fixture.connect(); | |
| 1094 | fixture.broker.remove(&fixture.machine, &old); | |
| 1095 | assert!(Arc::ptr_eq( | |
| 1096 | fixture | |
| 1097 | .broker | |
| 1098 | .connections | |
| 1099 | .lock() | |
| 1100 | .unwrap() | |
| 1101 | .get(&fixture.machine) | |
| 1102 | .unwrap(), | |
| 1103 | &new | |
| 1104 | )); | |
| 1105 | assert!(receive.try_recv().is_err()); | |
| 1106 | let task = fixture.dispatch(Duration::from_secs(2)); | |
| 1107 | receive.recv().await.unwrap(); | |
| 1108 | fixture.broker.disconnect(&fixture.machine); | |
| 1109 | assert!(task.await.unwrap().unwrap_err().message.contains("unknown")); | |
| 1110 | } | |
| 1111 | } |
dashboard/web/api.contract.ts-6| ... | ... | @@ -81,12 +81,6 @@ export type Api = Hono<{}, { |
| 81 | 81 | $get: Endpoint<Consent, { param: { id: string } }>; |
| 82 | 82 | $post: Endpoint<{ redirect: string }, { param: { id: string }; json: { resources: Access } | { deny: true } }>; |
| 83 | 83 | }; |
| 84 | "/mcp/relay/pair": { $post: Endpoint<Connections["machines"][number], { json: { code: string } }>; }; | |
| 85 | "/mcp/relay/machines/:id": { | |
| 86 | $patch: Endpoint<Connections["machines"][number], { param: { id: string }; json: { name: string } }>; | |
| 87 | $delete: Endpoint<null, { param: { id: string } }, 204>; | |
| 88 | }; | |
| 89 | "/mcp/relay/keys": { $post: Endpoint<{ key: string; id: string }, { json: { name: string; resources: string[]; write: boolean } }>; }; | |
| 90 | 84 | "/mcp/connections/:id": { |
| 91 | 85 | $get: Endpoint<{ resources: Resources; selected: Access; linked: boolean; resourceError: string | null }, { param: { id: string } }>; |
| 92 | 86 | $post: Endpoint<null, { param: { id: string }; json: { resources: Access } }, 204>; |
dashboard/web/pages/MCP.css-11| ... | ... | @@ -12,7 +12,6 @@ |
| 12 | 12 | .mcp-endpoint .muted { font-size: 12px; } |
| 13 | 13 | .mcp-repositories, .mcp-install { margin: 12px 0; } |
| 14 | 14 | .mcp-repositories summary, .mcp-install summary { cursor: pointer; color: var(--text-2); } |
| 15 | .mcp-install h3 { margin: 12px 0 6px; } | |
| 16 | 15 | .mcp-page .mcp-access-modes > label { padding: 6px 0; border: 0; background: none; } |
| 17 | 16 | .mcp-actions { display: flex; flex-wrap: wrap; gap: 8px; } |
| 18 | 17 | .mcp-access { padding: 0; margin: 20px 0; border: 0; min-width: 0; } |
| ... | ... | @@ -30,15 +29,7 @@ |
| 30 | 29 | .mcp-client > .mcp-actions { align-self: start; } |
| 31 | 30 | .mcp-client p { margin: 6px 0 0; overflow-wrap: anywhere; } |
| 32 | 31 | .mcp-edit-access { grid-column: 1 / -1; } |
| 33 | .mcp-page table { margin: 16px 0; } | |
| 34 | .mcp-page form { margin: 16px 0; } | |
| 35 | .mcp-page form > label { display: flex; align-items: center; gap: 12px; } | |
| 36 | 32 | |
| 37 | .mcp-page form:not(.mcp-actions) > button { margin-top: 12px; } | |
| 38 | .mcp-help { margin: 24px 0; } | |
| 39 | .mcp-help summary { cursor: pointer; } | |
| 40 | .mcp-help li { margin: 12px 0; } | |
| 41 | .mcp-connector { padding: 16px 0; margin: 16px 0; border-top: 1px solid var(--line); } | |
| 42 | 33 | .mcp-authorization { min-height: 100%; display: grid; place-items: center; padding: 40px 24px; box-sizing: border-box; } |
| 43 | 34 | .mcp-approval { width: min(100%, 600px); padding: 32px; box-sizing: border-box; background: var(--surface); border: 1px solid var(--line); border-radius: 16px; } |
| 44 | 35 | .mcp-approval-brand { color: var(--accent); font-size: 13px; font-weight: 600; margin-bottom: 28px; } |
| ... | ... | @@ -58,8 +49,6 @@ |
| 58 | 49 | .mcp-section-heading { flex-wrap: wrap; } |
| 59 | 50 | .mcp-endpoint .copy { width: 100%; } |
| 60 | 51 | .mcp-repository-list > div { grid-template-columns: 1fr; gap: 4px; } |
| 61 | .mcp-page form > label { flex-wrap: wrap; } | |
| 62 | .mcp-page input { max-width: 100%; min-width: 0; } | |
| 63 | 52 | .mcp-authorization { padding: 20px 12px; align-items: start; } |
| 64 | 53 | .mcp-approval { padding: 24px 20px; } |
| 65 | 54 | } |
dashboard/web/pages/MCP.tsx+4-73| ... | ... | @@ -1,9 +1,8 @@ |
| 1 | 1 | import { A, useNavigate, useParams } from "@solidjs/router"; |
| 2 | 2 | import { parseResponse } from "hono/client"; |
| 3 | import { createEffect, createResource, createSignal, For, onCleanup, Show } from "solid-js"; | |
| 3 | import { createEffect, createResource, createSignal, For, Show } from "solid-js"; | |
| 4 | 4 | import { api, reason } from "../api.ts"; |
| 5 | 5 | import { Ago } from "../components/Ago.tsx"; |
| 6 | import { Checkbox } from "../components/Checkbox.tsx"; | |
| 7 | 6 | import { Copy } from "../components/Copy.tsx"; |
| 8 | 7 | import { showConfirmDialog } from "../components/Dialog.tsx"; |
| 9 | 8 | import { Loaded } from "../components/Loaded.tsx"; |
| ... | ... | @@ -18,7 +17,6 @@ import "./MCP.css"; |
| 18 | 17 | const descriptions: Record<Catalog, string> = { |
| 19 | 18 | computer: "Inspect and control selected virtual machines, run commands, and install guest software.", |
| 20 | 19 | shale: "Read and edit issues across your Shale repositories.", |
| 21 | agents: "Connect to Codex and Claude Code on your machines.", | |
| 22 | 20 | observability: "Read logs and traces from your services.", |
| 23 | 21 | }; |
| 24 | 22 | |
| ... | ... | @@ -27,7 +25,7 @@ export function MCP(props: { me: Me }) { |
| 27 | 25 | const navigate = useNavigate(); |
| 28 | 26 | const ai = () => props.me.sections.includes("ai"); |
| 29 | 27 | createEffect(() => { if (!params.catalog || params.catalog === "ai" && !ai()) navigate(`/mcp/settings/${ai() ? "ai" : "observability"}`, { replace: true }); }); |
| 30 | const [overview, { refetch, mutate }] = createResource(() => parseResponse(api.mcp.$get())); | |
| 28 | const [overview, { refetch }] = createResource(() => parseResponse(api.mcp.$get())); | |
| 31 | 29 | const [shale, { refetch: retryShale }] = createResource(() => params.catalog === "shale", |
| 32 | 30 | () => parseResponse(api.mcp.shale.$get())); |
| 33 | 31 | const [editing, setEditing] = createSignal(""); |
| ... | ... | @@ -39,21 +37,7 @@ export function MCP(props: { me: Me }) { |
| 39 | 37 | return result; |
| 40 | 38 | }); |
| 41 | 39 | const [busy, setBusy] = createSignal(false); |
| 42 | const [code, setCode] = createSignal(""); | |
| 43 | const [keyName, setKeyName] = createSignal(""); | |
| 44 | const [keyMachines, setKeyMachines] = createSignal<string[]>([]); | |
| 45 | const [control, setControl] = createSignal(false); | |
| 46 | const [key, setKey] = createSignal(""); | |
| 47 | createEffect(() => { params.catalog; setEditing(""); setKey(""); }); | |
| 48 | createEffect(() => { | |
| 49 | if (params.catalog !== "agents") return; | |
| 50 | const events = new EventSource("/api/mcp/relay/live"); | |
| 51 | events.onmessage = (event) => { | |
| 52 | const machines: NonNullable<ReturnType<typeof overview>>["machines"] = JSON.parse(event.data); | |
| 53 | mutate((previous) => previous && { ...previous, machines }); | |
| 54 | }; | |
| 55 | onCleanup(() => events.close()); | |
| 56 | }); | |
| 40 | createEffect(() => { params.catalog; setEditing(""); }); | |
| 57 | 41 | const linkShale = async () => { |
| 58 | 42 | setBusy(true); |
| 59 | 43 | try { const result = await parseResponse(api.mcp.shale.$post({ json: {} })); window.location.assign(result.redirect); } |
| ... | ... | @@ -94,59 +78,6 @@ export function MCP(props: { me: Me }) { |
| 94 | 78 | </Loaded> |
| 95 | 79 | </section> |
| 96 | 80 | </Show> |
| 97 | <Show when={current().id === "agents"}> | |
| 98 | <section class="mcp-panel"> | |
| 99 | <h2>Local machines</h2> | |
| 100 | <details class="mcp-install"><summary>Install an agent</summary> | |
| 101 | <p>Install on each machine, then enter the pairing code below. The agent starts at login.</p> | |
| 102 | <h3>macOS or Linux</h3> | |
| 103 | <Copy value={`curl -fsSL ${window.location.origin}/agent/install.sh | sh`} label="macOS or Linux install command" /> | |
| 104 | <h3>Windows PowerShell</h3> | |
| 105 | <Copy value={`irm ${window.location.origin}/agent/install.ps1 | iex`} label="Windows install command" /> | |
| 106 | <p class="muted">Use your usual terminal, without administrator privileges. Codex or Claude Code must already be installed and signed in.</p></details> | |
| 107 | <form class="mcp-actions" onSubmit={async (event) => { | |
| 108 | event.preventDefault(); setBusy(true); | |
| 109 | try { await parseResponse(api.mcp.relay.pair.$post({ json: { code: code() } })); setCode(""); await refetch(); } | |
| 110 | catch (error) { toast(reason(error)); } | |
| 111 | finally { setBusy(false); } | |
| 112 | }}><label>Pairing code <input class="search" value={code()} onInput={(event) => setCode(event.currentTarget.value)} maxLength={40} /></label> | |
| 113 | <button class="button" disabled={!code().trim() || busy()}>Link machine</button></form> | |
| 114 | <Show when={data().machines.length} fallback={<p class="muted">No machines linked yet. Run the installer on a machine to link it.</p>}> | |
| 115 | <table class="data"><thead><tr><th>Machine</th><th>Platform</th><th>Connection</th><th /></tr></thead><tbody> | |
| 116 | <For each={data().machines}>{(machine) => <tr><td>{machine.name}</td><td>{machine.platform}</td><td>{machine.online ? "Online" : "Offline"}</td><td> | |
| 117 | <button class="button small" onClick={async () => { | |
| 118 | try { await parseResponse(api.mcp.relay.machines[":id"].$delete({ param: { id: machine.id } })); await refetch(); } | |
| 119 | catch (error) { toast(reason(error)); } | |
| 120 | }}>Unlink</button> | |
| 121 | </td></tr>}</For> | |
| 122 | </tbody></table> | |
| 123 | <h3>API key</h3> | |
| 124 | <form onSubmit={async (event) => { | |
| 125 | event.preventDefault(); setBusy(true); | |
| 126 | try { const result = await parseResponse(api.mcp.relay.keys.$post({ json: { name: keyName(), resources: keyMachines(), write: control() } })); setKey(result.key); setKeyName(""); setKeyMachines([]); setControl(false); await refetch(); } | |
| 127 | catch (error) { toast(reason(error)); } | |
| 128 | finally { setBusy(false); } | |
| 129 | }}> | |
| 130 | <label>Key name <input class="search" value={keyName()} onInput={(event) => setKeyName(event.currentTarget.value)} maxLength={100} /></label> | |
| 131 | <div class="mcp-resources"><For each={data().machines}>{(machine) => <Checkbox checked={keyMachines().includes(machine.id)} onChange={(checked) => setKeyMachines(checked ? [...keyMachines(), machine.id] : keyMachines().filter((id) => id !== machine.id))}>{machine.name}</Checkbox>}</For></div> | |
| 132 | <Checkbox checked={control()} onChange={setControl}>Allow session control</Checkbox> | |
| 133 | <button class="button" disabled={!keyName().trim() || !keyMachines().length || busy()}>Create key</button> | |
| 134 | </form> | |
| 135 | </Show> | |
| 136 | <details class="mcp-help"><summary>How to use linked machines</summary> | |
| 137 | <ol> | |
| 138 | <li>Add the Local agents endpoint above to your AI client's MCP connectors. Sign in and choose the machines it can access.</li> | |
| 139 | <li>Ask the client to list machines, choose a target, and list or read its Codex and Claude Code chats.</li> | |
| 140 | <li>To start a chat, name the machine, provider, and an existing project folder allowed during installation.</li> | |
| 141 | </ol> | |
| 142 | <p>Session control lets a client send messages, start chats, and interrupt turns. Desktop Codex control needs the installer's experimental option.</p> | |
| 143 | <p>Linked clients can read saved chats on granted machines. Allowed project folders limit where new chats start; existing chats keep their own permissions.</p> | |
| 144 | <p>For a script or another local tool, create an API key for selected machines. Enable session control only when it needs to write.</p> | |
| 145 | <p>Rerun the installer to update the agent or change allowed folders. Unlink removes the machine's access immediately.</p> | |
| 146 | </details> | |
| 147 | <Show when={key()}><section class="mcp-connector"><h3>New API key</h3><p>Copy this key now. It won't be shown again.</p><Copy value={key()} label="API key" /><button class="button secondary" onClick={() => setKey("")}>Dismiss</button></section></Show> | |
| 148 | </section> | |
| 149 | </Show> | |
| 150 | 81 | <section class="mcp-panel"><h2>Connected clients</h2> |
| 151 | 82 | <Show when={connections().length} fallback={<p class="muted">No clients connected. Add the connector URL to your AI client to get started.</p>}> |
| 152 | 83 | <div class="mcp-client-list"><For each={connections()}>{(client) => { |
| ... | ... | @@ -157,7 +88,7 @@ export function MCP(props: { me: Me }) { |
| 157 | 88 | event.preventDefault(); event.stopPropagation(); cancel(); |
| 158 | 89 | } |
| 159 | 90 | }}> |
| 160 | <div><h3>{client.name}</h3><p>{client.resources === "all" ? "All Repositories" : client.resources.join(", ")}</p><p class="muted">{client.scopes.includes("computer:control") ? "VM control and commands" : client.scopes.includes("sessions:write") ? "Session control" : client.scopes.includes("shale:write") ? "Issue editing" : "Read only"} · Connected <Ago t={client.createdAt} /></p></div> | |
| 91 | <div><h3>{client.name}</h3><p>{client.resources === "all" ? "All Repositories" : client.resources.join(", ")}</p><p class="muted">{client.scopes.includes("computer:control") ? "VM control and commands" : client.scopes.includes("shale:write") ? "Issue editing" : "Read only"} · Connected <Ago t={client.createdAt} /></p></div> | |
| 161 | 92 | <div class="mcp-actions"><button ref={editButton} class="button small" aria-expanded={editing() === client.id} disabled={busy()} onClick={() => setEditing(editing() === client.id ? "" : client.id)}>Edit access</button> |
| 162 | 93 | <button class="button small" disabled={busy()} onClick={() => showConfirmDialog({ title: "Revoke this connection?", description: `${client.name} will lose access immediately.`, confirmLabel: "Revoke", destructive: true, onConfirm: async () => { |
| 163 | 94 | await parseResponse(api.mcp.connections[":id"].$delete({ param: { id: client.id } })); if (editing() === client.id) setEditing(""); await refetch(); toast("Connection revoked"); |
dashboard/web/pages/MCPAccess.tsx+2-2| ... | ... | @@ -10,7 +10,7 @@ export function MCPAccess(props: { |
| 10 | 10 | disabled: boolean; |
| 11 | 11 | }) { |
| 12 | 12 | return <fieldset class="mcp-access" disabled={props.disabled}> |
| 13 | <legend>{props.catalog === "computer" ? "Virtual machines" : props.catalog === "shale" ? "Repositories" : props.catalog === "agents" ? "Machines" : "Services"}</legend> | |
| 13 | <legend>{props.catalog === "computer" ? "Virtual machines" : props.catalog === "shale" ? "Repositories" : "Services"}</legend> | |
| 14 | 14 | <Show when={props.catalog === "shale"}> |
| 15 | 15 | <div class="mcp-access-modes"> |
| 16 | 16 | <label><input type="radio" name="repository-access" checked={props.value === "all"} onChange={() => props.onChange("all")} /> |
| ... | ... | @@ -28,7 +28,7 @@ export function MCPAccess(props: { |
| 28 | 28 | props.onChange(checked ? [...selected, resource.id] : selected.filter((id) => id !== resource.id)); |
| 29 | 29 | }}><span>{resource.name}<Show when={resource.description}><small class="muted">{resource.description}</small></Show></span></Checkbox> |
| 30 | 30 | }</For></div> |
| 31 | <Show when={!props.resources.length}><p class="muted">{props.catalog === "computer" ? "No supported VMs belong to your account." : props.catalog === "agents" ? "No machines linked. Link a machine in MCP settings before connecting a client." : props.catalog === "shale" ? "No repositories available to select." : "No services available to your account."}</p></Show> | |
| 31 | <Show when={!props.resources.length}><p class="muted">{props.catalog === "computer" ? "No supported VMs belong to your account." : props.catalog === "shale" ? "No repositories available to select." : "No services available to your account."}</p></Show> | |
| 32 | 32 | </Show> |
| 33 | 33 | </fieldset>; |
| 34 | 34 | } |
dashboard/web/pages/MCPConsent.tsx+2-3| ... | ... | @@ -58,13 +58,12 @@ export function MCPConsent() { |
| 58 | 58 | </>}> |
| 59 | 59 | {(data) => <> |
| 60 | 60 | <h1 id="connection-title">Connect {data().client}</h1> |
| 61 | <p class="mcp-approval-intro">{data().catalog === "computer" ? "Grant access to selected virtual machines." : data().catalog === "shale" ? "Grant access to Shale issues." : data().catalog === "agents" ? "Grant access to your local agents." : "Grant access to logs and traces."}</p> | |
| 61 | <p class="mcp-approval-intro">{data().catalog === "computer" ? "Grant access to selected virtual machines." : data().catalog === "shale" ? "Grant access to Shale issues." : "Grant access to logs and traces."}</p> | |
| 62 | 62 | <dl class="mcp-request-identity"><div><dt>Signed in as</dt><dd>{data().account}</dd></div><div><dt>Return to</dt><dd>{data().redirectHost}</dd></div></dl> |
| 63 | 63 | <div class="mcp-permissions"><h2>Requested access</h2> |
| 64 | <p>{data().catalog === "computer" ? "Read VM status, screenshots, and application controls" : data().catalog === "shale" ? "Read issues and comments" : data().catalog === "agents" ? "Read saved chats" : "Read logs and traces"}</p> | |
| 64 | <p>{data().catalog === "computer" ? "Read VM status, screenshots, and application controls" : data().catalog === "shale" ? "Read issues and comments" : "Read logs and traces"}</p> | |
| 65 | 65 | <Show when={data().scopes.includes("computer:control")}><p>Control the desktop, run commands, and install software inside the selected VMs</p></Show> |
| 66 | 66 | <Show when={data().scopes.includes("shale:write")}><p>Create issues, comment, and edit issue titles and status</p></Show> |
| 67 | <Show when={data().scopes.includes("sessions:write")}><p>Send messages, start chats, and interrupt turns</p></Show> | |
| 68 | 67 | <Show when={data().scopes.includes("offline_access")}><p>Stay connected without signing in again</p></Show> |
| 69 | 68 | </div> |
| 70 | 69 | <Show when={data().linked} fallback={<div class="mcp-link-step"><h2>Link your Shale account</h2><p>Sign in to Shale, then return here to approve access.</p><button class="button primary" disabled={busy()} onClick={linkShale}>Link account</button></div>}> |
dashboard/web/types/mcp.ts+1-2| ... | ... | @@ -1,11 +1,10 @@ |
| 1 | export type Catalog = "shale" | "agents" | "observability" | "computer"; | |
| 1 | export type Catalog = "shale" | "observability" | "computer"; | |
| 2 | 2 | export type Access = "all" | string[]; |
| 3 | 3 | export type Resources = { id: string; name: string; description?: string }[]; |
| 4 | 4 | |
| 5 | 5 | export interface Connections { |
| 6 | 6 | catalogs: { id: Catalog; name: string; endpoint: string }[]; |
| 7 | 7 | connections: { id: string; name: string; catalog: Catalog; resources: Access; scopes: string[]; createdAt: number }[]; |
| 8 | machines: { id: string; name: string; platform: string; online: boolean }[]; | |
| 9 | 8 | shale: { linkedAt: number } | null; |
| 10 | 9 | } |
| 11 | 10 | export interface Consent { |
nixos/dashboard.nix-2| ... | ... | @@ -37,7 +37,6 @@ let |
| 37 | 37 | root = ../dashboard; |
| 38 | 38 | fileset = lib.fileset.unions [ |
| 39 | 39 | ../dashboard/src ../dashboard/web/sso ../dashboard/ai ../dashboard/tests ../dashboard/Cargo.toml ../dashboard/Cargo.lock |
| 40 | ../dashboard/agent/install.sh ../dashboard/agent/install.ps1 | |
| 41 | 40 | ]; |
| 42 | 41 | }; |
| 43 | 42 | cargoLock.lockFile = ../dashboard/Cargo.lock; |
| ... | ... | @@ -68,6 +67,5 @@ let |
| 68 | 67 | ln -s ${server}/bin/home-dashboard $out/bin/home-dashboard |
| 69 | 68 | ln -s ${web} $out/lib/home-dashboard/dist |
| 70 | 69 | ln -s ${../dashboard/server} $out/lib/home-dashboard/server |
| 71 | ln -s ${../dashboard/agent} $out/lib/home-dashboard/agent | |
| 72 | 70 | ''; |
| 73 | 71 | in dashboard |
tools/build-agent.py deleted-29| ... | ... | @@ -1,29 +0,0 @@ |
| 1 | #!/usr/bin/env python3 | |
| 2 | import argparse | |
| 3 | import json | |
| 4 | from pathlib import Path | |
| 5 | import subprocess | |
| 6 | ||
| 7 | ||
| 8 | def build(repo, destination, manifest): | |
| 9 | spec = json.loads(manifest.read_text()) | |
| 10 | source = (repo / "dashboard/agent" / spec["source"]).resolve(strict=True) | |
| 11 | entry = (source / spec["entry"]).resolve(strict=True) | |
| 12 | if not source.is_relative_to(repo.parent) or not entry.is_relative_to(source): | |
| 13 | raise ValueError("agent source must stay inside the workspace") | |
| 14 | destination.parent.mkdir(parents=True, exist_ok=True) | |
| 15 | subprocess.run([ | |
| 16 | str(repo / "dashboard/node_modules/.bin/esbuild"), str(entry), | |
| 17 | "--bundle", "--platform=node", "--format=esm", "--target=node24", | |
| 18 | "--external:bufferutil", "--external:utf-8-validate", | |
| 19 | "--banner:js=import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);", | |
| 20 | "--outfile=" + str(destination), | |
| 21 | ], check=True) | |
| 22 | ||
| 23 | ||
| 24 | if __name__ == "__main__": | |
| 25 | parser = argparse.ArgumentParser() | |
| 26 | parser.add_argument("--output", type=Path) | |
| 27 | args = parser.parse_args() | |
| 28 | repo = Path(__file__).resolve().parent.parent | |
| 29 | build(repo, args.output or repo / "dashboard/agent/relay.mjs", repo / "dashboard/agent/source.json") |
tools/dashboard-agent-test.py deleted-175| ... | ... | @@ -1,175 +0,0 @@ |
| 1 | #!/usr/bin/env python3 | |
| 2 | import argparse | |
| 3 | import fcntl | |
| 4 | import json | |
| 5 | import os | |
| 6 | from pathlib import Path | |
| 7 | import pty | |
| 8 | import re | |
| 9 | import select | |
| 10 | import shlex | |
| 11 | import sqlite3 | |
| 12 | import subprocess | |
| 13 | import tempfile | |
| 14 | import termios | |
| 15 | import time | |
| 16 | import urllib.error | |
| 17 | import urllib.request | |
| 18 | import uuid | |
| 19 | ||
| 20 | ||
| 21 | def main(): | |
| 22 | parser = argparse.ArgumentParser() | |
| 23 | parser.add_argument("--url", required=True) | |
| 24 | parser.add_argument("--output", type=Path) | |
| 25 | parser.add_argument("--home", type=Path) | |
| 26 | args = parser.parse_args() | |
| 27 | origin = args.url.rstrip("/") | |
| 28 | if os.uname().sysname == "Darwin": | |
| 29 | existing = subprocess.run(["launchctl", "print", f"gui/{os.getuid()}/net.paperclover.agent-relay"], capture_output=True) | |
| 30 | assert existing.returncode != 0, "stop the installed agent before running this disposable fixture" | |
| 31 | ||
| 32 | def http(path, body=None, token=None, status=200): | |
| 33 | request = urllib.request.Request(origin + path, data=json.dumps(body).encode() if body is not None else None, | |
| 34 | headers={"Content-Type": "application/json", "Origin": origin, **({"Authorization": "Bearer " + token} if token else {})}) | |
| 35 | try: | |
| 36 | response = urllib.request.urlopen(request, timeout=15) | |
| 37 | except urllib.error.HTTPError as error: | |
| 38 | response = error | |
| 39 | with response: | |
| 40 | raw = response.read().decode() | |
| 41 | assert response.status == status, (path, response.status, raw[:200]) | |
| 42 | try: | |
| 43 | return json.loads(raw) if raw else None | |
| 44 | except ValueError: | |
| 45 | return raw | |
| 46 | ||
| 47 | with tempfile.TemporaryDirectory(prefix="agent-relay-native-") as temporary: | |
| 48 | root = args.home.resolve() if args.home else Path(temporary).resolve() / "home with spaces $dollar %percent" | |
| 49 | root.mkdir(exist_ok=True) | |
| 50 | assert not (root / ".config/agent-relay/agent.json").exists(), "use a disposable home without an agent pairing" | |
| 51 | projects = root / "projects" | |
| 52 | projects.mkdir() | |
| 53 | codex = root / "codex" | |
| 54 | codex.mkdir() | |
| 55 | thread = str(uuid.uuid4()) | |
| 56 | db = sqlite3.connect(codex / "state_5.sqlite") | |
| 57 | db.execute("CREATE TABLE threads (id TEXT,title TEXT,cwd TEXT,updated_at INTEGER,rollout_path TEXT,archived INTEGER)") | |
| 58 | db.execute("INSERT INTO threads VALUES (?,?,?,?,?,0)", (thread, "Installer fixture", str(projects), int(time.time()), str(root / "fixture.jsonl"))) | |
| 59 | db.commit() | |
| 60 | db.close() | |
| 61 | env = {**os.environ, "HOME": str(root), "XDG_CONFIG_HOME": str(root / ".config"), "XDG_DATA_HOME": str(root / ".local/share"), "CODEX_HOME": str(codex), "CLAUDE_CONFIG_DIR": str(root / "claude")} | |
| 62 | base = root / "Library/Application Support/AgentRelay" if os.uname().sysname == "Darwin" else root / ".local/share/agent-relay" | |
| 63 | data = root / ".config/agent-relay" | |
| 64 | machine = None | |
| 65 | child = None | |
| 66 | master = None | |
| 67 | transcript = "" | |
| 68 | ||
| 69 | def install(fresh): | |
| 70 | nonlocal child, master, transcript, machine | |
| 71 | master, slave = pty.openpty() | |
| 72 | ||
| 73 | def terminal(): | |
| 74 | os.setsid() | |
| 75 | fcntl.ioctl(0, termios.TIOCSCTTY, 0) | |
| 76 | ||
| 77 | child = subprocess.Popen(["sh", "-c", f"curl -fsSL {shlex.quote(origin + '/agent/install.sh')} | sh"], stdin=slave, stdout=slave, stderr=slave, env=env, preexec_fn=terminal) | |
| 78 | os.close(slave) | |
| 79 | transcript = "" | |
| 80 | cursor = 0 | |
| 81 | ||
| 82 | def expect(pattern, timeout=120): | |
| 83 | nonlocal transcript, cursor | |
| 84 | deadline = time.monotonic() + timeout | |
| 85 | while True: | |
| 86 | match = re.search(pattern, transcript[cursor:]) | |
| 87 | if match: | |
| 88 | cursor += match.end() | |
| 89 | return match | |
| 90 | assert time.monotonic() < deadline, transcript[-1800:] | |
| 91 | if select.select([master], [], [], .2)[0]: | |
| 92 | try: | |
| 93 | chunk = os.read(master, 65536) | |
| 94 | except OSError: | |
| 95 | chunk = b"" | |
| 96 | assert chunk, transcript[-1800:] | |
| 97 | transcript += chunk.decode(errors="replace") | |
| 98 | ||
| 99 | if fresh: | |
| 100 | expect(r"Machine name \[.*?\]: ") | |
| 101 | os.write(master, b"Installer fixture\n") | |
| 102 | expect(r"Project folder: ") | |
| 103 | os.write(master, (str(projects) + "\n" if fresh else "\n").encode()) | |
| 104 | if fresh: | |
| 105 | expect(r"Project folder: ") | |
| 106 | os.write(master, b"\n") | |
| 107 | expect(r"Enable desktop control\?.*?: ") | |
| 108 | os.write(master, b"n\n") | |
| 109 | if fresh: | |
| 110 | code = expect(r"link this machine with code ([A-Z0-9]+-[A-Z0-9]+)").group(1) | |
| 111 | machine = http("/api/mcp/relay/pair", {"code": code}) | |
| 112 | expect(r"Installed\. Agent Relay starts at login\.") | |
| 113 | deadline = time.monotonic() + 20 | |
| 114 | while child.poll() is None and time.monotonic() < deadline: | |
| 115 | if select.select([master], [], [], .2)[0]: | |
| 116 | try: | |
| 117 | transcript += os.read(master, 65536).decode(errors="replace") | |
| 118 | except OSError: | |
| 119 | break | |
| 120 | assert child.poll() is not None, transcript[-1800:] | |
| 121 | assert child.returncode == 0, transcript[-1800:] | |
| 122 | os.close(master) | |
| 123 | master = None | |
| 124 | ||
| 125 | def online(expected): | |
| 126 | deadline = time.monotonic() + 20 | |
| 127 | while time.monotonic() < deadline: | |
| 128 | machines = http("/api/mcp")["machines"] | |
| 129 | found = next((item for item in machines if item["id"] == machine["id"]), None) | |
| 130 | if found and found["online"] == expected: | |
| 131 | return | |
| 132 | time.sleep(.2) | |
| 133 | raise AssertionError("agent connection did not change") | |
| 134 | ||
| 135 | try: | |
| 136 | install(True) | |
| 137 | online(True) | |
| 138 | config = json.loads((data / "agent.json").read_text()) | |
| 139 | assert config["roots"] == [str(projects)] and not config["desktopWrite"] | |
| 140 | assert (data / "agent.json").stat().st_mode & 0o777 == 0o600 | |
| 141 | key = http("/api/mcp/relay/keys", {"name": "Installer fixture", "resources": [machine["id"]], "write": True})["key"] | |
| 142 | result = http(f"/api/v1/machines/{machine['id']}/commands", {"method": "list_threads", "params": {"provider": "codex"}}, key) | |
| 143 | assert any(item["id"] == thread for item in result["result"]["threads"]), result | |
| 144 | result = http(f"/api/v1/machines/{machine['id']}/commands", {"method": "start_thread", "params": {"provider": "codex", "cwd": str(root), "message": "fixture"}}, key, status=400) | |
| 145 | assert "outside the roots" in str(result) | |
| 146 | install(False) | |
| 147 | online(True) | |
| 148 | assert json.loads((data / "agent.json").read_text()) == config | |
| 149 | manage = [str(base / "node"), str(base / "setup.mjs")] | |
| 150 | subprocess.run([*manage, "stop"], env=env, check=True, capture_output=True) | |
| 151 | online(False) | |
| 152 | subprocess.run([*manage, "start"], env=env, check=True, capture_output=True) | |
| 153 | online(True) | |
| 154 | subprocess.run([*manage, "uninstall"], env=env, check=True, capture_output=True) | |
| 155 | online(False) | |
| 156 | assert (data / "agent.json").exists() | |
| 157 | report = {"platform": os.uname().sysname, "curl_pipe_prompts": "passed", "pairing": "passed", "native_login_startup": "passed", "private_credentials": "passed", "captured_cli_environment": "passed", "allowed_folders": "passed", "reinstall_keeps_identity": "passed", "stop_start_uninstall": "passed", "spaces_dollars_percent_in_paths": "passed"} | |
| 158 | if args.output: | |
| 159 | args.output.write_text(json.dumps(report, indent=2) + "\n") | |
| 160 | print(json.dumps(report)) | |
| 161 | finally: | |
| 162 | if (base / "setup.mjs").exists(): | |
| 163 | subprocess.run([str(base / "node"), str(base / "setup.mjs"), "uninstall"], env=env, capture_output=True) | |
| 164 | if child and child.poll() is None: | |
| 165 | os.killpg(child.pid, 9) | |
| 166 | child.wait(timeout=10) | |
| 167 | if master is not None: | |
| 168 | os.close(master) | |
| 169 | if machine: | |
| 170 | request = urllib.request.Request(origin + "/api/mcp/relay/machines/" + machine["id"], method="DELETE", headers={"Origin": origin}) | |
| 171 | urllib.request.urlopen(request, timeout=10).close() | |
| 172 | ||
| 173 | ||
| 174 | if __name__ == "__main__": | |
| 175 | main() |
tools/deploy.py-3| ... | ... | @@ -2,7 +2,6 @@ |
| 2 | 2 | import argparse |
| 3 | 3 | import json |
| 4 | 4 | import os |
| 5 | from importlib import import_module | |
| 6 | 5 | from pathlib import Path |
| 7 | 6 | import re |
| 8 | 7 | import shlex |
| ... | ... | @@ -131,8 +130,6 @@ def upload(main=False): |
| 131 | 130 | shutil.copytree(origin, destination, symlinks=True) |
| 132 | 131 | else: |
| 133 | 132 | shutil.copy2(origin, destination) |
| 134 | if (snapshot / "dashboard/agent/source.json").exists(): | |
| 135 | import_module("build-agent").build(REPO, snapshot / "dashboard/agent/relay.mjs", snapshot / "dashboard/agent/source.json") | |
| 136 | 133 | digest = tree_digest(snapshot) |
| 137 | 134 | release = digest[:16] |
| 138 | 135 | remote_release = REMOTE / "releases" / release |