Skip to content

Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.

Run Tucano on a server, used from a browser (#27)

Eduardo Machado817a206be84c
diff --git a/README.md b/README.md
index 272f404..61fe0ef 100644
--- a/README.md
+++ b/README.md
@@ -125,6 +125,8 @@ curl -fsSL https://github.com/eduwxyz/tucano/releases/latest/download/install.sh
It downloads the latest release and opens it. On a Mac it puts Tucano in **Applications**; on Linux it installs the .deb with apt (it asks for your password) or, without apt, the AppImage in `~/.local/bin` with an entry in the applications menu. Run on Windows (in Git Bash, say), it points you to the PowerShell command above.
+**On a server** (a VPS, to keep routines running while your computer sleeps): Tucano can also run without a window and be used from a browser. See [docs/server.md](docs/server.md). This is experimental.
+
From 0.1.2 on, Tucano updates itself: it downloads a new version in the background and shows **Restart** in the sidebar when it's ready (or it goes in the next time you quit). Earlier versions update with the same download or command. On Linux the AppImage and the .deb update themselves too; the .deb asks for your password to put the update in. So does Windows, with no warning.
**3. The first run is the setup.** Tucano speaks English and Portuguese; pick one on the first screen, or later in **Settings**. Then, in a few steps: your name; which harnesses agents may use (each with a **Test now** button that sends a real question); the models that route channels and keep memory; what every agent should know about you; your tools (optional); your skills (optional); and your first agent, from a template or from scratch. It ends in a `#general` channel with your agent already working.
diff --git a/README.pt-BR.md b/README.pt-BR.md
index 8f31743..4116f37 100644
--- a/README.pt-BR.md
+++ b/README.pt-BR.md
@@ -125,6 +125,8 @@ curl -fsSL https://github.com/eduwxyz/tucano/releases/latest/download/install.sh
Ele baixa a última versão e abre. No Mac, coloca o Tucano em **Aplicativos**; no Linux, instala o .deb pelo apt (pede a sua senha) ou, sem apt, o AppImage em `~/.local/bin`, com um atalho no menu de aplicativos. Rodado no Windows (no Git Bash, por exemplo), ele indica o comando do PowerShell acima.
+**Num servidor** (uma VPS, pras rotinas continuarem rodando com o seu computador dormindo): o Tucano também roda sem janela, e você usa pelo navegador. Veja [docs/server.md](docs/server.md) (em inglês). É experimental.
+
A partir da 0.1.2, o Tucano se atualiza sozinho: baixa a versão nova em segundo plano e mostra **Reiniciar** na barra lateral quando ela está pronta (ou ela entra na próxima vez que você fechar o app). As versões anteriores se atualizam pelo mesmo download ou comando. No Linux, o AppImage e o .deb também se atualizam sozinhos; o .deb pede a sua senha pra instalar a atualização. No Windows também, sem aviso nenhum.
**3. A primeira abertura é a configuração.** O Tucano fala português e inglês; escolha na primeira tela, ou depois em **Configurações**. Em seguida, em poucos passos: seu nome; quais harnesses os agentes podem usar (cada um com um **Testar agora** que manda uma pergunta de verdade); os modelos que roteiam os canais e cuidam da memória; o que todo agente deve saber sobre você; suas ferramentas (opcional); suas skills (opcional); e o primeiro agente, de um modelo pronto ou do zero. No fim, um canal `#geral` com o seu agente já trabalhando.
diff --git a/docs/server.md b/docs/server.md
new file mode 100644
index 0000000..dde0c92
--- /dev/null
+++ b/docs/server.md
@@ -0,0 +1,108 @@
+# Tucano on a server
+
+Tucano can run on a server you own, such as a VPS or a machine at home. On a server, routines keep running when your computer sleeps, and you use Tucano from a browser, on any computer or phone. The server runs Tucano's core on plain Node and serves the app's own screens to the browser. Nothing goes through a Tucano service: the server is yours, and so are the data and the logins on it.
+
+Status: **new and experimental.** The core, the screens and the agents work in a browser, tested on Linux (Debian 12, Node 24) and macOS. A real agent turn on a server has only been tested with the test engine so far.
+
+## What you need
+
+| | |
+|---|---|
+| Linux, x64 or ARM64 | Any VPS with 2 GB of RAM or more |
+| [Node.js](https://nodejs.org) 24+ | Tucano's database is Node's built-in SQLite |
+| At least one harness, installed and signed in | Signed in **on the server**, as the user that runs Tucano (see below) |
+| Optional: Docker Engine | For agents' isolated Linux computers |
+| Optional: Chromium or Google Chrome | For agents' browsers (`apt install chromium`) |
+
+## Install
+
+As the user that will run Tucano (not root):
+
+```bash
+git clone https://github.com/eduwxyz/tucano.git
+cd tucano
+ELECTRON_SKIP_BINARY_DOWNLOAD=1 npm ci # the server doesn't need Electron itself
+npm run build
+npm run server
+```
+
+It prints the address to open:
+
+```
+Tucano server: http://127.0.0.1:7337/?token=…
+```
+
+Open that link once. The token signs the browser in, and a cookie keeps it signed in. The token lives in `~/.tucano-server/server-token`. To sign every browser out, delete that file and restart Tucano.
+
+### Signing the harnesses in
+
+Sign each harness in on the server, in a terminal over SSH:
+
+```bash
+curl -fsSL https://claude.ai/install.sh | bash && claude auth login # prints a link and asks for the code
+npm install -g @openai/codex
+```
+
+Codex is signed in from Tucano's **Settings › Models**, like on a desktop. On a server, the **Sign in** button can't open a terminal, so it shows the command to run in your SSH session.
+
+## Reaching it
+
+By default the server only listens on the server itself (`127.0.0.1`), because anyone who has the token controls your agents. Pick one of these ways to reach it:
+
+- **SSH tunnel**, the simplest: run `ssh -L 7337:127.0.0.1:7337 you@your-server`, then open the printed link on your computer.
+- **Tailscale** (or another private network): set `TUCANO_HOST` to the server's Tailscale address, then open `http://<that address>:7337/?token=…` from any of your devices, including your phone.
+- **A reverse proxy with HTTPS** (Caddy, nginx) on a domain of yours: keep Tucano on `127.0.0.1` and point the proxy at it. Turn off response buffering for `/events`, which is a live event stream. For example, with Caddy:
+
+ ```
+ tucano.example.com {
+ reverse_proxy 127.0.0.1:7337 {
+ flush_interval -1
+ }
+ }
+ ```
+
+Never expose port 7337 on a public address without HTTPS.
+
+## Keeping it running
+
+Run Tucano as a systemd service, under your own user. Save this as `/etc/systemd/system/tucano.service` and change the user and the path:
+
+```ini
+[Unit]
+Description=Tucano
+After=network-online.target
+
+[Service]
+User=you
+WorkingDirectory=/home/you/tucano
+ExecStart=/usr/bin/npm run server
+Restart=on-failure
+Environment=TUCANO_PORT=7337
+
+[Install]
+WantedBy=multi-user.target
+```
+
+Then run `sudo systemctl enable --now tucano`. The logs, including the address with the token, are in `journalctl -u tucano`.
+
+To update Tucano, run `git pull && npm ci && npm run build && sudo systemctl restart tucano`.
+
+## Settings
+
+| Variable | Default | |
+|---|---|---|
+| `TUCANO_DATA` | `~/.tucano-server` | Where everything is kept: database, memory, agents' files, the key and the token |
+| `TUCANO_HOST` | `127.0.0.1` | The address to listen on |
+| `TUCANO_PORT` | `7337` | |
+| `TUCANO_TOKEN` | a random token, kept in `server-token` | Set it to use a token of your own |
+
+## How it differs from the desktop app
+
+- **Connectors that sign in with OAuth** (an **Authorize in the browser** button): Tucano opens the authorization page in your browser. When you allow access, the page ends on an address starting with `http://127.0.0.1` that doesn't load, because that address is the server's own. Copy the whole address from the address bar and paste it into Tucano.
+- **Secrets** (connector keys, Telegram, GitHub) are encrypted with AES-256-GCM. The key is in `server.key` in the data folder, and only your user can read that file. A desktop app keeps that key in the system's keychain instead. Back the key up together with the data folder: the secrets can't be read without it.
+- **Notifications:** connect Telegram (**Settings › Phone and GitHub**) to get approvals, questions and results on your phone. The browser doesn't pop up notifications.
+- **Agents' browsers** need Chromium or Chrome on the server, and run without a window. **Take over** doesn't open a window there: the live picture of the browser in the panel becomes the browser. Click on it, type, paste and scroll, then click **Hand back**. This is how you sign in to a site for an agent.
+- **Pages agents serve** (a dashboard, an API) listen on the server's own `127.0.0.1`. Agents take their screenshots with the server's Chrome. When Tucano listens on a private address (Tailscale or a home network), it also passes each running page through on the same port at that address, so the preview panel and **Open** work from your computer. That doesn't happen on a public address, because those pages have no token. Over an SSH tunnel, forward the page's port too (`-L 5173:127.0.0.1:5173`).
+- **Choosing a folder** asks for its path on the server, since the browser can't browse the server's disk.
+- **No self-update.** Update with `git pull` (see above).
+- **One Tucano per data folder.** Don't run the desktop app and the server on the same data folder at the same time.
diff --git a/electron.vite.config.ts b/electron.vite.config.ts
index c82968f..574debf 100644
--- a/electron.vite.config.ts
+++ b/electron.vite.config.ts
@@ -5,7 +5,7 @@ export default defineConfig({
main: {
build: {
rolldownOptions: {
- input: { index: 'src/main/index.ts', core: 'src/core/index.ts' }
+ input: { index: 'src/main/index.ts', core: 'src/core/index.ts', server: 'src/server/index.ts' }
}
}
},
diff --git a/package.json b/package.json
index 04cedc4..28acb00 100644
--- a/package.json
+++ b/package.json
@@ -11,6 +11,7 @@
"dev": "electron-vite dev",
"build": "electron-vite build",
"start": "electron-vite preview",
+ "server": "node out/main/server.js",
"typecheck": "tsc --noEmit -p tsconfig.json",
"test": "vitest run",
"dist": "sh scripts/dist.sh",
diff --git a/src/core/chrome.ts b/src/core/chrome.ts
index d8e4ebb..2a70f0a 100644
--- a/src/core/chrome.ts
+++ b/src/core/chrome.ts
@@ -11,7 +11,7 @@ import { join } from 'node:path'
import { L } from '../shared/lang'
import { findChrome, userAgentPlatform } from './platform'
import { POINT, PICK, SNAPSHOT, TEXT } from '../shared/page'
-import type { BrowserOp, BrowserReply } from '../shared/types'
+import type { BrowserInput, BrowserOp, BrowserReply } from '../shared/types'
// Google Chrome on this computer, where it usually is on each system (see platform.ts).
export const CHROME = findChrome()
@@ -48,7 +48,10 @@ const KEYS: Record<string, { key: string; code: string; vk: number; text?: strin
arrowleft: { key: 'ArrowLeft', code: 'ArrowLeft', vk: 37 },
arrowright: { key: 'ArrowRight', code: 'ArrowRight', vk: 39 },
pagedown: { key: 'PageDown', code: 'PageDown', vk: 34 },
- pageup: { key: 'PageUp', code: 'PageUp', vk: 33 }
+ pageup: { key: 'PageUp', code: 'PageUp', vk: 33 },
+ delete: { key: 'Delete', code: 'Delete', vk: 46 },
+ home: { key: 'Home', code: 'Home', vk: 36 },
+ end: { key: 'End', code: 'End', vk: 35 }
}
type Pending = { resolve: (v: Record<string, unknown>) => void; reject: (e: Error) => void }
@@ -65,6 +68,7 @@ class Tab {
url = ''
private world: number | undefined // our isolated world in the tab's main frame
closedAll?: () => void // every tab is gone (I closed the window)
+ remote = false // I'm driving it from the panel (no window: Tucano as a server)
constructor(
readonly proc: ChildProcess,
@@ -199,7 +203,10 @@ export class ChromeBrowsers {
private dir: string, // profiles live in <dir>/<agentId>
private onShown: (agentId: string, shown: boolean) => void,
private bin: string = CHROME ?? '',
- private onFrame?: OnFrame
+ private onFrame?: OnFrame,
+ // No screen to open a window on (Tucano as a server): taking over keeps it
+ // headless and I drive it from the panel, through 'input'.
+ private windowless = false
) {
process.on('exit', () => this.quit())
}
@@ -310,6 +317,26 @@ export class ChromeBrowsers {
}
return { url: '', title: '' }
}
+ if (op === 'show' && this.windowless) {
+ const tab = await this.tab(agentId)
+ tab.remote = true
+ this.onShown(agentId, true)
+ return { url: tab.url, title: '', shown: true }
+ }
+ if (op === 'hide' && this.windowless) {
+ const t = this.tabs.get(agentId)
+ if (t?.remote) {
+ t.remote = false
+ this.onShown(agentId, false)
+ }
+ return { url: t?.url ?? '', title: '', shown: false }
+ }
+ if (op === 'input') {
+ const t = this.tabs.get(agentId)
+ if (!t?.remote) throw new Error(L('Assuma o navegador antes de usar.', 'Take the browser over before using it.'))
+ await this.input(t, args as BrowserInput)
+ return { url: t.url, title: '', shown: true }
+ }
if (op === 'show') {
const current = this.tabs.get(agentId) ?? (await this.starting.get(agentId))
if (current?.headed) return { url: current.url, title: '', shown: true }
@@ -335,7 +362,7 @@ export class ChromeBrowsers {
.run<{ url: string; title: string; w: number; h: number }>('({ url: location.href, title: document.title, w: innerWidth, h: innerHeight })')
.catch(() => ({ url: tab.url, title: '', w: 0, h: 0 }))
const point = at && w && h ? { x: at.x / w, y: at.y / h } : undefined
- return { ...info, shown: tab.headed, ...(point ? { point } : {}), ...(frame ? { frame: await this.frame(tab) } : {}) }
+ return { ...info, shown: tab.headed || tab.remote, ...(point ? { point } : {}), ...(frame ? { frame: await this.frame(tab) } : {}) }
}
switch (op) {
@@ -348,7 +375,7 @@ export class ChromeBrowsers {
return here(true)
}
case 'snapshot':
- return { ...(await tab.run<BrowserReply>(SNAPSHOT)), shown: tab.headed }
+ return { ...(await tab.run<BrowserReply>(SNAPSHOT)), shown: tab.headed || tab.remote }
case 'click': {
const at = typeof args['ref'] === 'number' ? await tab.run<{ x: number; y: number } | null>(POINT(args['ref'], false)) : { x: Number(args['x']), y: Number(args['y']) }
if (!at || !Number.isFinite(at.x) || !Number.isFinite(at.y)) throw new Error(L('Esse elemento não está mais na página. Leia a página de novo.', 'That element is no longer on the page. Read the page again.'))
@@ -410,6 +437,63 @@ export class ChromeBrowsers {
await tab.cmd('Input.dispatchMouseEvent', { type: 'mouseReleased', ...p, button: 'left', clickCount: 1 })
}
+ // A picture of a page (a service an agent started), where there's no Electron
+ // to take it (Tucano as a server): a throwaway headless Chrome of its own, no
+ // cookies from anything else, sized as asked, the whole page when asked.
+ async shot(o: { url: string; width: number; height: number; fullPage: boolean }): Promise<Buffer> {
+ if (!/^https?:\/\//.test(o.url)) throw new Error(L('só http e https', 'only http and https'))
+ const id = `.shot-${process.pid}-${Date.now()}`
+ const tab = await this.launch(id, false)
+ try {
+ const size = (height: number): Promise<unknown> => tab.cmd('Emulation.setDeviceMetricsOverride', { width: o.width, height, deviceScaleFactor: 1, mobile: false })
+ await size(o.height)
+ await Promise.race([tab.cmd('Page.navigate', { url: o.url }), wait(30_000).then(() => Promise.reject(new Error(L('a página não carregou em 30 s', "the page didn't load in 30 s"))))])
+ await this.settle(tab)
+ await wait(800) // fonts, charts and client-side rendering
+ if (o.fullPage) {
+ const h = await tab.run<number>('Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)').catch(() => 0)
+ if (h > o.height) {
+ await size(Math.min(h, 6000))
+ await wait(600)
+ }
+ }
+ const r = (await tab.cmd('Page.captureScreenshot', { format: 'png' })) as { data?: string }
+ if (!r.data) throw new Error(L('o Chrome não devolveu a imagem', "Chrome returned no image"))
+ return Buffer.from(r.data, 'base64')
+ } finally {
+ tab.close()
+ await gone(tab.proc)
+ // Windows lets go of a closed Chrome's files a moment late; a leftover is only a temp folder.
+ try {
+ rmSync(this.profile(id), { recursive: true, force: true, maxRetries: 10, retryDelay: 200 })
+ } catch {}
+ }
+ }
+
+ // What I do from the panel: a click where I clicked on the picture, what I
+ // typed, a key, the wheel.
+ private async input(tab: Tab, i: BrowserInput): Promise<void> {
+ if (i.kind === 'click') {
+ const { w, h } = await tab.run<{ w: number; h: number }>('({ w: innerWidth, h: innerHeight })')
+ const x = Math.min(Math.max(Number(i.x), 0), 1)
+ const y = Math.min(Math.max(Number(i.y), 0), 1)
+ return this.click(tab, x * w, y * h)
+ }
+ if (i.kind === 'text') {
+ if (i.text) await tab.cmd('Input.insertText', { text: String(i.text).slice(0, 10_000) })
+ return
+ }
+ if (i.kind === 'key') {
+ const name = String(i.key).toLowerCase()
+ if (KEYS[name]) await this.key(tab, name)
+ return
+ }
+ if (i.kind === 'scroll') {
+ const { w, h } = await tab.run<{ w: number; h: number }>('({ w: innerWidth, h: innerHeight })').catch(() => ({ w: W, h: H }))
+ await tab.cmd('Input.dispatchMouseEvent', { type: 'mouseWheel', x: w / 2, y: h / 2, deltaX: 0, deltaY: Math.max(-3000, Math.min(3000, Number(i.dy) || 0)) })
+ }
+ }
+
private async key(tab: Tab, name: string): Promise<void> {
const k = KEYS[name]!
const base = { key: k.key, code: k.code, windowsVirtualKeyCode: k.vk }
diff --git a/src/core/connectors.ts b/src/core/connectors.ts
index dd2fb10..c0c1543 100644
--- a/src/core/connectors.ts
+++ b/src/core/connectors.ts
@@ -43,6 +43,8 @@ const key = (id: string, what: string): string => `connector:${id}:${what}`
export class ConnectorManager {
private live = new Map<string, Live>()
private oauthStates = new Map<string, { connectorId: string; transport: StreamableHTTPClientTransport }>()
+ private authUrls = new Map<string, string>() // a connector's last authorization page
+ private doneStates = new Set<string>() // finished already (the callback got there first): not an expired one
constructor(private deps: ConnectorDeps) {}
@@ -245,15 +247,35 @@ export class ConnectorManager {
// ---------- OAuth ----------
- authorize(id: string): Promise<void> {
- return this.connect(id, true)
+ // The authorization page's address comes back too: on a server there's no
+ // browser to open it in, so the page the person is using opens it.
+ async authorize(id: string): Promise<string | undefined> {
+ this.authUrls.delete(id)
+ await this.connect(id, true).catch(() => {})
+ return this.authUrls.get(id)
+ }
+
+ // On a server the authorization page sends the person's browser to the
+ // callback on the server's own loopback, which it can't reach; the address
+ // it was sent to carries the code, and the person pastes it here.
+ async finishOAuthFromUrl(pasted: string): Promise<boolean> {
+ let url: URL
+ try {
+ url = new URL(pasted.trim())
+ } catch {
+ throw new Error(L('Isso não parece um endereço. Copie o endereço inteiro da barra do navegador.', "That doesn't look like an address. Copy the whole address from the browser's bar."))
+ }
+ const code = url.searchParams.get('code')
+ if (!code) throw new Error(L(`Autorização não concluída: ${url.searchParams.get('error_description') ?? url.searchParams.get('error') ?? 'o endereço não tem o código'}.`, `Authorization not completed: ${url.searchParams.get('error_description') ?? url.searchParams.get('error') ?? 'the address has no code'}.`))
+ return this.finishOAuth(url.searchParams.get('state') ?? '', code)
}
// Called by the local HTTP server when the browser comes back from the authorization page.
async finishOAuth(state: string, code: string): Promise<boolean> {
const pending = this.oauthStates.get(state)
- if (!pending) return false
+ if (!pending) return this.doneStates.has(state)
this.oauthStates.delete(state)
+ this.doneStates.add(state)
await pending.transport.finishAuth(code)
await this.connect(pending.connectorId)
return true
@@ -294,6 +316,7 @@ export class ConnectorManager {
redirectToAuthorization: (url) => {
if (!interactive) return // never pop a browser on a background reconnect
this.oauthStates.set(state || url.searchParams.get('state') || '', { connectorId: id, transport: transport() })
+ this.authUrls.set(id, url.toString())
this.deps.openUrl(url.toString())
},
invalidateCredentials: async (scope) => {
diff --git a/src/core/index.ts b/src/core/index.ts
index bb2f476..64469a7 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -46,6 +46,8 @@ import { seed } from './seed'
const dataDir = process.env['TUCANO_DATA'] ?? join(process.cwd(), '.tucano')
const fake = process.env['TUCANO_FAKE_ENGINES'] === '1'
+// Run by the server (src/server): no window, and the screens are in a browser elsewhere.
+const serverMode = process.env['TUCANO_SERVER'] === '1'
mkdirSync(dataDir, { recursive: true })
const db = new Db(join(dataDir, 'tucano.db'))
@@ -206,7 +208,9 @@ process.parentPort.on('message', (e) => {
if (r.error !== undefined) p?.reject(new Error(r.error))
else p?.resolve(Buffer.from(String(r.data ?? ''), 'base64'))
})
-const shoot: Shooter = (opts) =>
+// On a server there's no Electron: the agents' Chrome takes the picture instead.
+const shoot: Shooter = (opts) => (serverMode && chrome ? chrome.shot(opts) : electronShoot(opts))
+const electronShoot: Shooter = (opts) =>
new Promise((resolve, reject) => {
const id = randomUUID()
shots.set(id, { resolve, reject })
@@ -227,7 +231,8 @@ const chrome =
join(dataDir, 'navegador'),
(agentId, shown) => browser.setShown(agentId, shown),
undefined,
- (agentId, jpeg) => browser.frame(agentId, jpeg)
+ (agentId, jpeg) => browser.frame(agentId, jpeg),
+ serverMode
)
: undefined
const host: BrowserHost = chrome ? (agentId, op, args) => chrome.run(agentId, op, args) : electronHost
@@ -246,7 +251,8 @@ const connectors = new ConnectorManager({
db,
secrets,
emit,
- openUrl: (url) => toMain({ type: 'open', url }),
+ // On a server there's nothing to open it in: authorizeConnector hands it to the page.
+ openUrl: (url) => serverMode || toMain({ type: 'open', url }),
oauthCallbackUrl: () => gateway.url('/oauth/callback')
})
gateway.route('/oauth/callback', async (url) => {
@@ -690,7 +696,11 @@ const api: Api = {
removeConnector: ({ id }) => void connectors.remove(id),
reconnectConnector: ({ id }) => void connectors.connect(id),
- authorizeConnector: ({ id }) => void connectors.authorize(id),
+ authorizeConnector: async ({ id }) => {
+ const url = await connectors.authorize(id)
+ return serverMode && url ? { url } : {}
+ },
+ finishConnectorAuth: ({ url }) => connectors.finishOAuthFromUrl(url),
harnessMcps: async () => (await foundMcps()).map(publicMcp),
importHarnessMcp: async ({ key }) => {
const m = (await foundMcps()).find((x) => x.key === key)
@@ -721,6 +731,12 @@ const api: Api = {
void run().catch((e: unknown) => console.error('[computer]', e))
},
stopService: ({ agentId, name }) => void computers.stopService(agentId, name),
+ // Driving a taken-over browser from the panel (Tucano as a server: no window to open).
+ browserInput: async ({ agentId, input }) => {
+ if (!serverMode || !chrome) throw new Error(L('Só no Tucano em servidor.', 'Only on Tucano as a server.'))
+ await chrome.run(agentId, 'input', input)
+ },
+
browserAction: ({ agentId, action }) => {
const agent = db.agent(agentId)
if (agent) void browser.action(agent, action).catch((e: unknown) => console.error('[navegador]', e))
diff --git a/src/main/browser.ts b/src/main/browser.ts
index cacf25d..4fd2155 100644
--- a/src/main/browser.ts
+++ b/src/main/browser.ts
@@ -186,6 +186,8 @@ export class Browsers {
return { ...here(), text: wc.getURL() === '' ? '' : await iso<string>(TEXT) }
case 'frame':
return { ...here(), frame: await this.frame(win) }
+ case 'input': // only Chrome on a server takes input from the panel; a window here is used directly
+ throw new Error('input is for a windowless browser')
}
}
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index 4268b87..5230706 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -50,8 +50,21 @@ export function App(): ReactNode {
}, [intro, mac])
if (!view) return <div className="boot" />
- if (intro) return <Onboarding />
- if (view.kind === 'tuca') return <Onboarding build from={view.from} />
+ // Dialogs too: connecting a tool from the introduction may open one (on a server).
+ if (intro)
+ return (
+ <>
+ <Onboarding />
+ <Dialogs />
+ </>
+ )
+ if (view.kind === 'tuca')
+ return (
+ <>
+ <Onboarding build from={view.from} />
+ <Dialogs />
+ </>
+ )
return (
<div className="app">
diff --git a/src/renderer/src/components/Dialogs.tsx b/src/renderer/src/components/Dialogs.tsx
index 8ee6c6f..60cee68 100644
--- a/src/renderer/src/components/Dialogs.tsx
+++ b/src/renderer/src/components/Dialogs.tsx
@@ -3,7 +3,7 @@
// menu and the channel's header open the same ones.
import { L } from '../../../shared/lang'
import { useEffect, useRef, useState, type ReactNode } from 'react'
-import { agentById, archiveAgent, isTeam, openTuca, createChannel, getState, navigate, openDialog, openDm, renameChannel, setChannelMembers, setTopic, shortcut, useStore, type State, type View } from '../store'
+import { agentById, archiveAgent, isTeam, openTuca, createChannel, finishConnectorAuth, getState, navigate, openDialog, openDm, renameChannel, setChannelMembers, setTopic, shortcut, useStore, type State, type View } from '../store'
import { AgentAvatar, Icon, type IconName } from './ui'
const message = (e: unknown): string => (e instanceof Error ? e.message.replace(/^Error invoking.*?: /, '') : String(e))
@@ -14,6 +14,7 @@ export function Dialogs(): ReactNode {
const close = (): void => openDialog(null)
if (dialog?.kind === 'search') return <Search onClose={close} />
if (dialog?.kind === 'archived') return <Archived onClose={close} />
+ if (dialog?.kind === 'oauth') return <OAuthDialog id={dialog.id} url={dialog.url} onClose={close} />
if (dialog?.kind === 'new-channel')
return <TextDialog title={L('Novo canal', 'New channel')} label={L('Nome', 'Name')} value="" hint={L('Minúsculas e hífens: “Squad Pagamentos” vira squad-pagamentos. Depois você escolhe os agentes.', 'Lowercase and hyphens: “Payments Squad” becomes payments-squad. You pick the agents next.')} prefix="#" onSave={(v) => createChannel(v)} onClose={() => getState().dialog?.kind === 'new-channel' && close()} />
if (!dialog || !conv) return null
@@ -123,6 +124,63 @@ function TextDialog(p: { title: string; label: string; value: string; hint: stri
)
}
+// Signing a connector in on a server: the authorization page opens here, and its
+// last stop (the server's loopback, which this browser can't reach) is pasted back.
+function OAuthDialog({ id, url, onClose }: { id: string; url: string; onClose: () => void }): ReactNode {
+ const name = useStore((s) => s.connectors.find((c) => c.id === id)?.name ?? L('o conector', 'the connector'))
+ // Connected some other way (the callback reached the server after all): nothing left to paste.
+ const connected = useStore((s) => s.connectors.find((c) => c.id === id)?.status === 'connected')
+ useEffect(() => {
+ if (connected) onClose()
+ }, [connected, onClose])
+ const [pasted, setPasted] = useState('')
+ const [error, setError] = useState<string | null>(null)
+ const [busy, setBusy] = useState(false)
+ const finish = (): void => {
+ if (!pasted.trim() || busy) return
+ setBusy(true)
+ setError(null)
+ finishConnectorAuth(pasted).then(
+ (ok) => (ok ? onClose() : (setError(L('Esse pedido de autorização expirou. Feche e clique em Conectar de novo.', 'This authorization request expired. Close this and click Connect again.')), setBusy(false))),
+ (e: unknown) => (setError(message(e)), setBusy(false))
+ )
+ }
+ return (
+ <Modal title={L(`Conectar ${name}`, `Connect ${name}`)} onClose={onClose}>
+ <p className="small modal__lead">
+ {L('1. Abra a página de autorização e permita o acesso.', '1. Open the authorization page and allow access.')}
+ </p>
+ <p>
+ <a className="btn btn--primary btn--sm" href={url} target="_blank" rel="noopener noreferrer">
+ {L('Abrir a página de autorização', 'Open the authorization page')}
+ </a>
+ </p>
+ <label className="field">
+ <span className="field__label">{L('2. Cole aqui o endereço em que ela terminou', '2. Paste the address it ended on')}</span>
+ <span className="row row--center modal__input">
+ <input autoFocus className="grow" placeholder="http://127.0.0.1:…/oauth/callback?code=…" value={pasted} onChange={(e) => setPasted(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && finish()} />
+ </span>
+ <span className="hint">
+ {L(
+ 'Depois de permitir, o navegador vai pra um endereço que começa com http://127.0.0.1 e mostra que a página não abre. É normal: o Tucano está no servidor. Copie o endereço inteiro da barra e cole aqui.',
+ 'After you allow it, the browser goes to an address starting with http://127.0.0.1 and says the page can’t be reached. That’s expected: Tucano is on the server. Copy the whole address from the bar and paste it here.'
+ )}
+ </span>
+ </label>
+ {error && <p className="field__error">{error}</p>}
+ <footer className="modal__foot">
+ <span className="grow" />
+ <button className="btn btn--ghost btn--sm" onClick={onClose}>
+ {L('Cancelar', 'Cancel')}
+ </button>
+ <button className="btn btn--primary btn--sm" disabled={!pasted.trim() || busy} onClick={finish}>
+ {L('Concluir', 'Finish')}
+ </button>
+ </footer>
+ </Modal>
+ )
+}
+
// The agents taken out of the sidebar, to see or bring back.
function Archived({ onClose }: { onClose: () => void }): ReactNode {
const agents = useStore((s) => s.agents.filter((a) => a.archived))
diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsx
index e19a9bf..b5b3177 100644
--- a/src/renderer/src/components/Pages.tsx
+++ b/src/renderer/src/components/Pages.tsx
@@ -52,7 +52,8 @@ import {
type MemoryMode,
type Skill,
type ToolClass,
- isTeam
+ isTeam,
+ reachable
} from '../store'
import { HarnessList, HarnessMcps, ModelPicker, onGateway, OutsideGateway } from './Harness'
import { ApprovalCard } from './Conversation'
@@ -742,7 +743,7 @@ function Services({ agentId }: { agentId: string }): ReactNode {
</span>
{svc.running && svc.url && (
<>
- <button className="btn btn--sm btn--ghost" onClick={() => openExternal(svc.url!)}>
+ <button className="btn btn--sm btn--ghost" onClick={() => openExternal(reachable(svc.url!))}>
{L('Abrir', 'Open')}
</button>
<button className="btn btn--sm btn--ghost" onClick={() => stopService(agentId, svc.name)}>
diff --git a/src/renderer/src/components/Panel.tsx b/src/renderer/src/components/Panel.tsx
index da986cd..f07a926 100644
--- a/src/renderer/src/components/Panel.tsx
+++ b/src/renderer/src/components/Panel.tsx
@@ -4,7 +4,7 @@ import { L, locale } from '../../../shared/lang'
import { useEffect, useState, type ReactNode } from 'react'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
-import { agentById, artifactUrl, browserAction, browserOf, computerOf, openExternal, openPanel, stopService, useStore, type Artifact } from '../store'
+import { agentById, artifactUrl, browserAction, browserInput, browserOf, reachable, windowless, computerOf, openExternal, openPanel, stopService, useStore, type Artifact } from '../store'
import { call } from '../rpc'
import { Icon, type IconName } from './ui'
@@ -156,6 +156,9 @@ function BrowserScreen({ agentId, onOpen }: { agentId: string; onOpen?: () => vo
</div>
)
const c = view.cursor
+ // Taken over on a server: the picture is the browser. Clicks land where I click,
+ // keys and pastes go to the page, the wheel scrolls it.
+ if (view.shown && windowless() && !onOpen) return <DrivenScreen agentId={agentId} frame={view.frame} title={view.title} />
return (
<div className={`screen ${onOpen ? 'screen--button' : ''}`} onClick={onOpen} role={onOpen ? 'button' : undefined}>
<img className="screen__frame" src={view.frame} alt={view.title} draggable={false} />
@@ -186,6 +189,41 @@ function BrowserScreen({ agentId, onOpen }: { agentId: string; onOpen?: () => vo
)
}
+const PAGE_KEYS = new Set(['Enter', 'Escape', 'Tab', 'Backspace', 'Delete', 'ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'PageDown', 'PageUp', 'Home', 'End'])
+
+function DrivenScreen({ agentId, frame, title }: { agentId: string; frame: string; title: string }): ReactNode {
+ return (
+ <div
+ className="screen screen--driven"
+ tabIndex={0}
+ onClick={(e) => {
+ const r = (e.currentTarget.querySelector('img') ?? e.currentTarget).getBoundingClientRect()
+ e.currentTarget.focus()
+ browserInput(agentId, { kind: 'click', x: (e.clientX - r.left) / r.width, y: (e.clientY - r.top) / r.height })
+ }}
+ onKeyDown={(e) => {
+ if (e.metaKey || e.ctrlKey) return // paste and the app's own shortcuts
+ if (e.key.length === 1) browserInput(agentId, { kind: 'text', text: e.key })
+ else if (PAGE_KEYS.has(e.key)) browserInput(agentId, { kind: 'key', key: e.key === ' ' ? 'space' : e.key })
+ else return
+ e.preventDefault()
+ }}
+ onPaste={(e) => {
+ const text = e.clipboardData.getData('text')
+ if (text) browserInput(agentId, { kind: 'text', text })
+ e.preventDefault()
+ }}
+ onWheel={(e) => browserInput(agentId, { kind: 'scroll', dy: e.deltaY })}
+ >
+ <img className="screen__frame" src={frame} alt={title} draggable={false} />
+ <span className="screen__status screen__status--you">
+ <Icon name="hand" size={13} />
+ {L('Você está no controle: clique e digite na tela. Clique em Devolver ao terminar.', 'You’re in control: click and type on the screen. Click Hand back when you’re done.')}
+ </span>
+ </div>
+ )
+}
+
function BrowserLog({ agentId, max }: { agentId: string; max?: number }): ReactNode {
const view = useStore((s) => browserOf(s, agentId))
if (!view) return null
@@ -227,7 +265,7 @@ function TakeOver({ agentId }: { agentId: string }): ReactNode {
return (
<button
className={`btn btn--sm ${view.shown ? 'btn--primary' : 'btn--ghost'}`}
- title={view.shown ? L('Fecha a janela e devolve o navegador', 'Closes the window and hands the browser back') : L('Abre o navegador numa janela pra você usar (login, código, captcha)', 'Opens the browser in a window for you to use (login, code, captcha)')}
+ title={view.shown ? L('Devolve o navegador ao agente', 'Hands the browser back to the agent') : windowless() ? L('Você usa o navegador aqui mesmo, na tela (login, código, captcha)', 'You use the browser right here, on the screen (login, code, captcha)') : L('Abre o navegador numa janela pra você usar (login, código, captcha)', 'Opens the browser in a window for you to use (login, code, captcha)')}
onClick={(e) => {
e.stopPropagation()
browserAction(agentId, view.shown ? 'hide' : 'show')
@@ -332,7 +370,7 @@ export function SidePanel(): ReactNode {
<header className="side-panel__head">
<Icon name={panel.kind === 'service' || panel.kind === 'browser' ? 'globe' : 'edit'} size={14} />
<strong className="side-panel__title">{title}</strong>
- {service?.url && <code className="side-panel__url">{service.url}</code>}
+ {service?.url && <code className="side-panel__url">{reachable(service.url)}</code>}
{panel.kind === 'browser' && <LiveBadge agentId={panel.agentId} />}
<span className="grow" />
{panel.kind === 'browser' && <TakeOver agentId={panel.agentId} />}
@@ -341,7 +379,7 @@ export function SidePanel(): ReactNode {
<button className="icon-btn" title={L('Recarregar', 'Reload')} onClick={() => setReload((n) => n + 1)}>
<Icon name="clock" size={14} />
</button>
- <button className="btn btn--sm btn--ghost" onClick={() => openExternal(service.url!)}>
+ <button className="btn btn--sm btn--ghost" onClick={() => openExternal(reachable(service.url!))}>
{L('Abrir no navegador', 'Open in the browser')}
</button>
</>
@@ -355,7 +393,7 @@ export function SidePanel(): ReactNode {
{panel.kind === 'service' &&
(service?.running && service.url ? (
// Same origin is the service's own (127.0.0.1:port), not the app's.
- <iframe key={reload} src={service.url} sandbox="allow-scripts allow-forms allow-same-origin allow-popups allow-modals" title={service.name} />
+ <iframe key={reload} src={reachable(service.url)} sandbox="allow-scripts allow-forms allow-same-origin allow-popups allow-modals" title={service.name} />
) : (
<p className="empty">{L('Esse serviço não está rodando.', 'This service isn’t running.')}</p>
))}
diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.ts
index 11bbc9a..aedc16e 100644
--- a/src/renderer/src/store.ts
+++ b/src/renderer/src/store.ts
@@ -7,6 +7,7 @@ import {
MODELS,
modelInfo,
type EngineId,
+ type BrowserInput,
type Agent,
type Approval,
type Artifact,
@@ -78,7 +79,7 @@ export interface State {
demoServer?: { command: string; args: string[] }
}
-export type Dialog = { kind: 'members' | 'rename' | 'topic'; id: string } | { kind: 'archived' | 'new-channel' | 'search' }
+export type Dialog = { kind: 'members' | 'rename' | 'topic'; id: string } | { kind: 'archived' | 'new-channel' | 'search' } | { kind: 'oauth'; id: string; url: string }
export type Panel = { kind: 'artifact'; id: string } | { kind: 'service'; agentId: string; name: string } | { kind: 'browser'; agentId: string }
@@ -369,7 +370,10 @@ export const updateTool = (connectorId: string, name: string, patch: Partial<Pic
export const addConnector = (input: ConnectorInput): Promise<string> => call('addConnector', { input })
export const removeConnector = (id: string): void => void call('removeConnector', { id })
export const reconnectConnector = (id: string): void => void call('reconnectConnector', { id })
-export const authorizeConnector = (id: string): void => void call('authorizeConnector', { id })
+// On a server the authorization page comes back to be opened here, then pasted back.
+export const authorizeConnector = (id: string): void =>
+ void call('authorizeConnector', { id }).then((r) => r.url && openDialog({ kind: 'oauth', id, url: r.url }))
+export const finishConnectorAuth = (url: string): Promise<boolean> => call('finishConnectorAuth', { url })
export const harnessMcps = (): Promise<HarnessMcp[]> => call('harnessMcps')
export const importHarnessMcp = (key: string): Promise<string> => call('importHarnessMcp', { key })
@@ -415,7 +419,16 @@ export const computerAction = (agentId: string, action: 'start' | 'restart' | 'e
void call('computerAction', { agentId, action })
export const stopService = (agentId: string, name: string): void => void call('stopService', { agentId, name })
export const browserAction = (agentId: string, action: 'show' | 'hide' | 'clear'): void => void call('browserAction', { agentId, action })
-export const openExternal = (url: string): void => void call('openExternal', { url })
+// Tucano as a server: the page is in a browser and the agent's has no window, so I
+// drive it from its picture in the panel.
+export const windowless = (): boolean => !!(window as { __TUCANO_WEB__?: boolean }).__TUCANO_WEB__
+// A page an agent serves, as this browser reaches it: on a server, at the server's
+// address (it passes running services through on a private network).
+export const reachable = (url: string): string => (windowless() ? url.replace(/^http:\/\/127\.0\.0\.1:/, `http://${location.hostname}:`) : url)
+export const browserInput = (agentId: string, input: BrowserInput): void => void call('browserInput', { agentId, input }).catch(() => {})
+// In a browser (Tucano as a server) the page opens it itself: the server has no screen.
+export const openExternal = (url: string): void =>
+ (window as { __TUCANO_WEB__?: boolean }).__TUCANO_WEB__ ? void window.open(url, '_blank', 'noopener') : void call('openExternal', { url })
export const saveRoutine = (routine: RoutineInput): Promise<Routine> => call('saveRoutine', { routine })
export const setJevKey = (key: string | null): Promise<void> => call('setJevKey', { key })
diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.css
index 7710de3..298cb1f 100644
--- a/src/renderer/src/styles.css
+++ b/src/renderer/src/styles.css
@@ -2061,6 +2061,14 @@ h3 {
.screen--button {
cursor: zoom-in;
}
+.screen--driven {
+ cursor: pointer;
+ outline: 2px solid var(--accent);
+ outline-offset: -2px;
+}
+.screen--driven:focus-visible {
+ outline-width: 3px;
+}
.screen__frame {
display: block;
width: 100%;
diff --git a/src/server/forward.ts b/src/server/forward.ts
new file mode 100644
index 0000000..578e117
--- /dev/null
+++ b/src/server/forward.ts
@@ -0,0 +1,43 @@
+import { connect, createServer, type Server, type Socket } from 'node:net'
+
+// A private address: a home or office network, or Tailscale's 100.64.0.0/10.
+export const isPrivate = (host: string): boolean => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/.test(host)
+
+// Passes ports of the server's own loopback through at another of its addresses,
+// as plain TCP (pages, their scripts, websockets alike), and stops when told.
+export class Forwarder {
+ private servers = new Map<number, { server: Server; open: Set<Socket> }>()
+
+ constructor(private host: string) {}
+
+ set(ports: Set<number>): void {
+ // A service that stopped: no new connections, and the open ones end too.
+ for (const [p, f] of this.servers)
+ if (!ports.has(p)) {
+ f.server.close()
+ for (const c of f.open) c.destroy()
+ this.servers.delete(p)
+ }
+ for (const p of ports) {
+ if (this.servers.has(p)) continue
+ const open = new Set<Socket>()
+ const server = createServer((client) => {
+ const to = connect(p, '127.0.0.1')
+ open.add(client)
+ client.pipe(to).pipe(client)
+ const end = (): void => (open.delete(client), client.destroy(), void to.destroy())
+ client.on('close', end)
+ client.on('error', end)
+ to.on('close', end)
+ to.on('error', end)
+ })
+ server.on('error', () => this.servers.get(p)?.server === server && this.servers.delete(p)) // taken: nothing to pass through
+ server.listen(p, this.host)
+ this.servers.set(p, { server, open })
+ }
+ }
+
+ get ports(): number[] {
+ return [...this.servers.keys()]
+ }
+}
diff --git a/src/server/index.ts b/src/server/index.ts
new file mode 100644
index 0000000..44c7aa7
--- /dev/null
+++ b/src/server/index.ts
@@ -0,0 +1,259 @@
+// Tucano as a server: the core on plain Node (a VPS, a home server), and the
+// app's own screens in a browser. Where the desktop app's main process hosts the
+// core and the window, this does: it stands in for Electron's parentPort, keeps
+// the secrets with a key of its own, and serves the page plus a bridge to the
+// core (events down an event stream, requests up by POST). Every request needs
+// the server's token.
+//
+// node out/main/server.js (TUCANO_DATA, TUCANO_HOST, TUCANO_PORT, TUCANO_TOKEN)
+import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'
+import { EventEmitter } from 'node:events'
+import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
+import { homedir } from 'node:os'
+import { extname, join, normalize, sep } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { Forwarder, isPrivate } from './forward'
+import { vault } from './vault'
+
+const dataDir = process.env['TUCANO_DATA'] || join(homedir(), '.tucano-server')
+const host = process.env['TUCANO_HOST'] || '127.0.0.1'
+const port = Number(process.env['TUCANO_PORT'] || 7337)
+const page = join(import.meta.dirname, '..', 'renderer')
+mkdirSync(dataDir, { recursive: true, mode: 0o700 })
+
+// A file only this user reads, made once: the server's key or token.
+function kept(name: string, make: () => string): string {
+ const file = join(dataDir, name)
+ if (!existsSync(file)) writeFileSync(file, make(), { mode: 0o600 })
+ chmodSync(file, 0o600)
+ return readFileSync(file, 'utf8').trim()
+}
+const token = process.env['TUCANO_TOKEN'] || kept('server-token', () => randomBytes(24).toString('base64url'))
+// The secrets (Telegram, GitHub, connector keys) are sealed with this key; on a
+// desktop it's the system's keychain, which a server doesn't have.
+const key = Buffer.from(kept('server.key', () => randomBytes(32).toString('base64')), 'base64')
+
+const { seal, open } = vault(key)
+
+// Electron's MessagePortMain and parentPort, as far as the core uses them.
+class Port extends EventEmitter {
+ constructor(readonly postMessage: (msg: unknown) => void) {
+ super()
+ }
+ start(): void {}
+ close(): void {
+ this.emit('close')
+ }
+}
+
+type CoreRequest = { type: string; id?: string; op?: string; data?: string }
+const parent = new Port((msg) => fromCore(msg as CoreRequest))
+const toCore = (data: unknown, ports: Port[] = []): boolean => parent.emit('message', { data, ports })
+
+// What the main process does for the core on a desktop. A server has no screen:
+// no notifications (Telegram carries them), nothing to open, no login item.
+function fromCore(msg: CoreRequest): void {
+ const id = msg.id
+ if (msg.type === 'secret') {
+ try {
+ toCore({ type: 'secret-result', id, data: msg.op === 'encrypt' ? seal(msg.data ?? '') : open(msg.data ?? '') })
+ } catch (e) {
+ toCore({ type: 'secret-result', id, error: e instanceof Error ? e.message : String(e) })
+ }
+ } else if (msg.type === 'screenshot') {
+ toCore({ type: 'screenshot-result', id, error: 'screenshots need the desktop app' })
+ } else if (msg.type === 'browser') {
+ // Only when there's no Chrome: the core drives Chrome or Chromium itself when one is installed.
+ toCore({ type: 'browser-result', id, error: 'install Google Chrome or Chromium on the server for the agents’ browser' })
+ }
+}
+
+// The page's connections: each one a port of the core, events down its stream.
+const clients = new Map<string, Port>()
+
+const TYPES: Record<string, string> = {
+ '.html': 'text/html; charset=utf-8',
+ '.js': 'text/javascript; charset=utf-8',
+ '.css': 'text/css; charset=utf-8',
+ '.json': 'application/json',
+ '.svg': 'image/svg+xml',
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.woff2': 'font/woff2',
+ '.mp3': 'audio/mpeg',
+ '.wav': 'audio/wav',
+ '.pdf': 'application/pdf',
+ '.txt': 'text/plain; charset=utf-8',
+ '.md': 'text/plain; charset=utf-8',
+ '.csv': 'text/csv; charset=utf-8'
+}
+
+function file(res: ServerResponse, path: string, headers: Record<string, string> = {}): void {
+ if (!existsSync(path)) return void res.writeHead(404).end('not found')
+ res.writeHead(200, { 'content-type': TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream', ...headers }).end(readFileSync(path))
+}
+
+const sameToken = (t: string | undefined): boolean => !!t && t.length === token.length && timingSafeEqual(Buffer.from(t), Buffer.from(token))
+const cookieToken = (req: IncomingMessage): string | undefined => /(?:^|;\s*)tucano=([^;]+)/.exec(req.headers.cookie ?? '')?.[1]
+
+// The pages agents serve (a dashboard, an API) listen on the server's own
+// loopback. On a private address (Tailscale, a home network) each running one
+// is passed through on the same port at the server's address, so the preview
+// panel can show it. Never on a public address: those pages have no token.
+const privateHost = isPrivate(host)
+const forwarder = new Forwarder(host)
+const forwardServices = (ports: Set<number>): void => {
+ if (privateHost) forwarder.set(new Set([...ports].filter((p) => p !== port)))
+}
+const servicePorts = new Map<string, number[]>() // by agent
+const loopbackPort = (url?: string): number | undefined => (url ? Number(/^http:\/\/127\.0\.0\.1:(\d+)/.exec(url)?.[1]) || undefined : undefined)
+type Computer = { agentId: string; services: { url?: string; running: boolean }[] }
+function sawComputers(list: Computer[]): void {
+ for (const c of list) servicePorts.set(c.agentId, c.services.filter((s) => s.running).flatMap((s) => loopbackPort(s.url) ?? []))
+ forwardServices(new Set([...servicePorts.values()].flat()))
+}
+// The server's own connection to the core, to follow the services.
+const watcher = new Port((msg) => {
+ const m = msg as { id?: number; result?: { computers?: Computer[] }; event?: { type: string; computer?: Computer } }
+ if (m.id === 1 && m.result?.computers) sawComputers(m.result.computers)
+ else if (m.event?.type === 'computer' && m.event.computer) sawComputers([m.event.computer])
+})
+
+// The desktop page, told it's in a browser: the bridge script first, and its
+// policy letting it frame the agents' pages from this server.
+function index(): string {
+ return readFileSync(join(page, 'index.html'), 'utf8')
+ .replace('frame-src tucano:', `frame-src 'self' tucano:${privateHost ? ` http://${host}:*` : ''}`)
+ .replace('<title>', '<meta name="viewport" content="width=device-width, initial-scale=1" />\n <script src="./tucano-web.js"></script>\n <title>')
+}
+
+function body(req: IncomingMessage): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const chunks: Buffer[] = []
+ let size = 0
+ req.on('data', (c: Buffer) => {
+ size += c.length
+ if (size > 64 * 1024 * 1024) return reject(new Error('too large'))
+ chunks.push(c)
+ })
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
+ req.on('error', reject)
+ })
+}
+
+const server = createServer((req, res) => {
+ const url = new URL(req.url ?? '/', 'http://x')
+ // The link with ?token= signs this browser in, then drops it from the address bar. Lax, not
+ // Strict: the link is often clicked from elsewhere (a chat), and a Strict cookie wouldn't ride
+ // the redirect that follows. Lax still keeps it off other sites' POSTs to /rpc.
+ if (sameToken(url.searchParams.get('token') ?? undefined)) {
+ const secure = req.headers['x-forwarded-proto'] === 'https' ? '; Secure' : ''
+ return void res.writeHead(302, { 'set-cookie': `tucano=${token}; HttpOnly; SameSite=Lax; Path=/; Max-Age=31536000${secure}`, location: '/' }).end()
+ }
+ if (!sameToken(cookieToken(req))) {
+ return void res
+ .writeHead(401, { 'content-type': 'text/plain; charset=utf-8' })
+ .end('Tucano: open the link with the token the server printed (…/?token=…).\nTucano: abra o link com o token que o servidor mostrou (…/?token=…).')
+ }
+
+ if (url.pathname === '/events') {
+ const c = new Port((msg) => res.write(`data: ${JSON.stringify(msg)}\n\n`))
+ const id = randomUUID()
+ clients.set(id, c)
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', 'x-accel-buffering': 'no' })
+ res.write(`event: hello\ndata: ${id}\n\n`)
+ const beat = setInterval(() => res.write(': \n\n'), 25_000)
+ toCore(null, [c])
+ req.on('close', () => {
+ clearInterval(beat)
+ clients.delete(id)
+ c.close()
+ })
+ return
+ }
+
+ if (url.pathname === '/rpc' && req.method === 'POST') {
+ const c = clients.get(url.searchParams.get('c') ?? '')
+ if (!c) return void res.writeHead(410).end()
+ body(req).then(
+ (text) => {
+ c.emit('message', { data: JSON.parse(text) })
+ res.writeHead(204).end()
+ },
+ () => res.writeHead(413).end()
+ )
+ return
+ }
+
+ // What the agents showed in the chat, sandboxed as on the desktop.
+ const art = /^\/artifact\/([0-9a-f-]{36})\/([^/]+)$/.exec(url.pathname)
+ if (art) {
+ const dir = join(dataDir, 'artifacts', art[1]!)
+ const path = normalize(join(dir, decodeURIComponent(art[2]!)))
+ if (!path.startsWith(dir + sep)) return void res.writeHead(404).end()
+ return file(res, path, { 'content-security-policy': 'sandbox allow-scripts allow-popups' })
+ }
+
+ if (url.pathname === '/tucano-web.js') return void res.writeHead(200, { 'content-type': TYPES['.js']! }).end(WEB)
+ if (url.pathname === '/' || url.pathname === '/index.html') return void res.writeHead(200, { 'content-type': TYPES['.html']!, 'cache-control': 'no-cache' }).end(index())
+ const path = normalize(join(page, decodeURIComponent(url.pathname)))
+ if (!path.startsWith(page + sep)) return void res.writeHead(404).end()
+ file(res, path)
+})
+
+// window.tucano for a browser: the core's port comes from the event stream and
+// the requests go up by POST; what only the desktop does is left out quietly.
+const WEB = `(() => {
+ window.__TUCANO_WEB__ = true
+ let client = null
+ const connect = () => {
+ const ch = new MessageChannel()
+ const es = new EventSource('./events')
+ let opened = false
+ es.addEventListener('hello', (e) => {
+ if (opened) return location.reload() // a new connection after a drop: start fresh
+ opened = true
+ client = e.data
+ window.postMessage('core:port', '*', [ch.port1])
+ })
+ es.onmessage = (e) => ch.port2.postMessage(JSON.parse(e.data))
+ ch.port2.onmessage = (m) => {
+ fetch('./rpc?c=' + encodeURIComponent(client), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(m.data) }).then((r) => {
+ if (r.status === 410) location.reload()
+ })
+ }
+ }
+ window.tucano = {
+ connect,
+ pickFolder: async () => {
+ const p = prompt('Pasta no servidor (caminho completo) / Folder on the server (full path):')
+ return p && p.trim() ? p.trim() : null
+ },
+ onNavigate: () => {},
+ viewing: () => {},
+ updateState: async () => ({ version: '', status: 'off' }),
+ onUpdate: () => {},
+ checkUpdates: () => {},
+ installUpdate: () => {}
+ }
+})()
+`
+
+process.env['TUCANO_DATA'] = dataDir
+process.env['TUCANO_PACKAGED'] = '1'
+process.env['TUCANO_SERVER'] = '1'
+;(process as unknown as { parentPort: Port }).parentPort = parent
+await import(pathToFileURL(join(import.meta.dirname, 'core.js')).href)
+toCore(null, [watcher])
+watcher.emit('message', { data: { id: 1, method: 'snapshot' } })
+
+server.listen(port, host, () => {
+ const shown = host === '0.0.0.0' || host === '::' ? 'localhost' : host
+ console.log(`Tucano server: http://${shown}:${port}/?token=${token}`)
+ console.log(`Data: ${dataDir}`)
+ if (host === '127.0.0.1') console.log('Listening on this machine only: reach it through an SSH tunnel, Tailscale or a reverse proxy with HTTPS (docs/server.md).')
+})
diff --git a/src/server/vault.ts b/src/server/vault.ts
new file mode 100644
index 0000000..234caa4
--- /dev/null
+++ b/src/server/vault.ts
@@ -0,0 +1,21 @@
+import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'
+
+// The server's stand-in for the system keychain: AES-256-GCM with a key kept in
+// a file only its user reads. Sealed text is iv | tag | ciphertext, in base64.
+export function vault(key: Buffer): { seal: (text: string) => string; open: (sealed: string) => string } {
+ if (key.length !== 32) throw new Error('the server key must be 32 bytes')
+ return {
+ seal(text) {
+ const iv = randomBytes(12)
+ const c = createCipheriv('aes-256-gcm', key, iv)
+ const body = Buffer.concat([c.update(text, 'utf8'), c.final()])
+ return Buffer.concat([iv, c.getAuthTag(), body]).toString('base64')
+ },
+ open(sealed) {
+ const b = Buffer.from(sealed, 'base64')
+ const d = createDecipheriv('aes-256-gcm', key, b.subarray(0, 12))
+ d.setAuthTag(b.subarray(12, 28))
+ return Buffer.concat([d.update(b.subarray(28)), d.final()]).toString('utf8')
+ }
+ }
+}
diff --git a/src/shared/rpc.ts b/src/shared/rpc.ts
index bc78fee..786e5cd 100644
--- a/src/shared/rpc.ts
+++ b/src/shared/rpc.ts
@@ -1,5 +1,5 @@
// The contract between the renderer and the core, carried over a MessagePort.
-import type { Os, Agent, Approval, Artifact, ImageUpload, BrowserView, ComputerInfo, Connector, ConnectorInput, ConnectorTool, HarnessMcp, Conversation, EngineId, Memory, MemoryScope, Message, Routine, RoutineInput, Report, Settings, LocalSkill, Skill, SkillInput, SkillVersion, Trigger, UsageReport } from './types'
+import type { Os, Agent, BrowserInput, Approval, Artifact, ImageUpload, BrowserView, ComputerInfo, Connector, ConnectorInput, ConnectorTool, HarnessMcp, Conversation, EngineId, Memory, MemoryScope, Message, Routine, RoutineInput, Report, Settings, LocalSkill, Skill, SkillInput, SkillVersion, Trigger, UsageReport } from './types'
export interface Snapshot {
settings: Settings
@@ -44,7 +44,8 @@ export interface Api {
addConnector(p: { input: ConnectorInput }): Promise<string>
removeConnector(p: { id: string }): void
reconnectConnector(p: { id: string }): void
- authorizeConnector(p: { id: string }): void
+ authorizeConnector(p: { id: string }): Promise<{ url?: string }> // url: on a server, the page to open in the person's browser
+ finishConnectorAuth(p: { url: string }): Promise<boolean> // on a server: the address the authorization page ended on
harnessMcps(): Promise<HarnessMcp[]> // the MCP servers set up in Claude Code, Codex and OpenCode
importHarnessMcp(p: { key: string }): Promise<string> // adds one as a connector; its secrets never pass through the screen
updateTool(p: { connectorId: string; name: string; patch: Partial<Pick<ConnectorTool, 'cls' | 'enabled' | 'highRisk'>> }): void
@@ -59,7 +60,8 @@ export interface Api {
summarizeNow(p: { conversationId: string }): void
computerAction(p: { agentId: string; action: 'start' | 'restart' | 'erase' | 'open_folder' | 'refresh' }): void
stopService(p: { agentId: string; name: string }): void
- browserAction(p: { agentId: string; action: 'show' | 'hide' | 'clear' }): void // show: I take over the agent's browser; clear: logins and history go
+ browserAction(p: { agentId: string; action: 'show' | 'hide' | 'clear' }): void
+ browserInput(p: { agentId: string; input: BrowserInput }): Promise<void> // a server's taken-over browser, driven from the panel // show: I take over the agent's browser; clear: logins and history go
lendFolder(p: { agentId: string; path: string }): void // throws why it can't, for the page
folderAction(p: { agentId: string; name: string; action: 'read_only' | 'read_write' | 'return' }): void
openExternal(p: { url: string }): void
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 7ef6ab8..256c140 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -203,7 +203,11 @@ export interface Settings {
}
// What the main process does in an agent's browser for the core, and what it answers (spec §24).
-export type BrowserOp = 'open' | 'snapshot' | 'click' | 'type' | 'key' | 'scroll' | 'back' | 'text' | 'frame' | 'show' | 'hide' | 'close' | 'clear'
+export type BrowserOp = 'open' | 'snapshot' | 'click' | 'type' | 'key' | 'scroll' | 'back' | 'text' | 'frame' | 'show' | 'hide' | 'close' | 'clear' | 'input'
+
+// What I do on the agent's browser from the panel, when it has no window of its own
+// (Tucano as a server): x and y are fractions of the screen.
+export type BrowserInput = { kind: 'click'; x: number; y: number } | { kind: 'text'; text: string } | { kind: 'key'; key: string } | { kind: 'scroll'; dy: number }
export interface BrowserElement {
ref: number // its number in the last snapshot of the page
@@ -496,7 +500,9 @@ export const IMAGE_MIMES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'
export const MAX_IMAGE_BYTES = 5 * 1024 * 1024 // what the models take per image
export const MAX_IMAGES_PER_MESSAGE = 10
-export const artifactUrl = (a: Pick<Artifact, 'id' | 'name'>): string => `tucano://artifact/${a.id}/${encodeURIComponent(a.name)}`
+// In a browser (Tucano as a server) the server itself serves them, under /artifact.
+export const artifactUrl = (a: Pick<Artifact, 'id' | 'name'>): string =>
+ `${(globalThis as { __TUCANO_WEB__?: boolean }).__TUCANO_WEB__ ? './artifact/' : 'tucano://artifact/'}${a.id}/${encodeURIComponent(a.name)}`
// ---------- routines (spec §14) ----------
diff --git a/test/chrome-windowless.test.ts b/test/chrome-windowless.test.ts
new file mode 100644
index 0000000..f08f1f4
--- /dev/null
+++ b/test/chrome-windowless.test.ts
@@ -0,0 +1,62 @@
+import { createServer, type Server } from 'node:http'
+import { mkdtempSync } from 'node:fs'
+import type { AddressInfo } from 'node:net'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { ChromeBrowsers, hasChrome } from '../src/core/chrome'
+
+// Tucano as a server: taking the agent's browser over keeps it headless, and
+// what I do on its picture in the panel reaches the page.
+const PAGE = `<!doctype html><title>start</title>
+<input id="q" style="position:fixed;top:0;left:0;width:100vw;height:100px;font-size:40px">
+<div style="height:4000px"></div>
+<script>q.addEventListener('keydown', (e) => { if (e.key === 'Enter') document.title = 'sent:' + q.value })
+addEventListener('scroll', () => { document.title = document.title.startsWith('sent:') ? document.title : 'scrolled' })</script>`
+
+describe.skipIf(!hasChrome())('a windowless browser driven from the panel', () => {
+ let server: Server
+ let url = ''
+ const shown: boolean[] = []
+ let chrome: ChromeBrowsers
+
+ beforeAll(async () => {
+ server = createServer((_req, res) => void res.writeHead(200, { 'content-type': 'text/html' }).end(PAGE))
+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
+ url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`
+ chrome = new ChromeBrowsers(mkdtempSync(join(tmpdir(), 'tucano-chrome-')), (_id, s) => shown.push(s), undefined, undefined, true)
+ })
+
+ afterAll(async () => {
+ await chrome.run('a', 'close').catch(() => {})
+ await new Promise((r) => server.close(r))
+ })
+
+ it('takes clicks, typing and keys while taken over, and refuses them after', async () => {
+ await chrome.run('a', 'open', { url })
+ await expect(chrome.run('a', 'input', { kind: 'text', text: 'x' })).rejects.toThrow()
+
+ expect((await chrome.run('a', 'show')).shown).toBe(true)
+ expect(shown).toEqual([true])
+
+ await chrome.run('a', 'input', { kind: 'click', x: 0.5, y: 0.03 })
+ await chrome.run('a', 'input', { kind: 'text', text: 'olá mundo' })
+ await chrome.run('a', 'input', { kind: 'key', key: 'Enter' })
+ expect((await chrome.run('a', 'frame')).title).toBe('sent:olá mundo')
+
+ expect((await chrome.run('a', 'hide')).shown).toBe(false)
+ expect(shown).toEqual([true, false])
+ await expect(chrome.run('a', 'input', { kind: 'key', key: 'Enter' })).rejects.toThrow()
+ }, 60_000)
+
+ it('takes a picture of a page, sized as asked and whole when asked', async () => {
+ const size = (png: Buffer): { w: number; h: number } => ({ w: png.readUInt32BE(16), h: png.readUInt32BE(20) })
+ const shot = await chrome.shot({ url, width: 800, height: 600, fullPage: false })
+ expect(shot.subarray(1, 4).toString()).toBe('PNG')
+ expect(size(shot)).toEqual({ w: 800, h: 600 })
+ const whole = size(await chrome.shot({ url, width: 800, height: 600, fullPage: true }))
+ expect(whole.w).toBe(800)
+ expect(whole.h).toBeGreaterThan(4000)
+ await expect(chrome.shot({ url: 'file:///etc/hosts', width: 800, height: 600, fullPage: false })).rejects.toThrow()
+ }, 60_000)
+})
diff --git a/test/connectors.test.ts b/test/connectors.test.ts
index 1e37591..f305204 100644
--- a/test/connectors.test.ts
+++ b/test/connectors.test.ts
@@ -46,3 +46,62 @@ describe('OAuth on a server that takes no new apps', () => {
expect(c.error).not.toMatch(/Incompatible/)
})
})
+
+// The same, with dynamic registration and a token endpoint: an app may sign in.
+describe('OAuth signed in from a page on another machine (Tucano as a server)', () => {
+ let auth: Server
+ let authBase: string
+ const tokenCalls: string[] = []
+
+ beforeEach(async () => {
+ tokenCalls.length = 0
+ auth = createServer((req, res) => {
+ const json = (body: unknown, status = 200): void => void res.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(body))
+ if (req.url?.startsWith('/.well-known/oauth-protected-resource')) return json({ resource: `${authBase}/mcp`, authorization_servers: [authBase] })
+ if (req.url?.startsWith('/.well-known/oauth-authorization-server'))
+ return json({ issuer: authBase, authorization_endpoint: `${authBase}/authorize`, token_endpoint: `${authBase}/token`, registration_endpoint: `${authBase}/register`, response_types_supported: ['code'], code_challenge_methods_supported: ['S256'] })
+ if (req.url === '/register') return json({ client_id: 'tucano-test', redirect_uris: ['http://127.0.0.1:1/oauth/callback'] }, 201)
+ if (req.url === '/token') {
+ let body = ''
+ req.on('data', (c: Buffer) => (body += c))
+ req.on('end', () => {
+ tokenCalls.push(body)
+ json({ access_token: 'at-1', token_type: 'Bearer', expires_in: 3600 })
+ })
+ return
+ }
+ res.writeHead(401, { 'www-authenticate': `Bearer resource_metadata="${authBase}/.well-known/oauth-protected-resource"` }).end()
+ })
+ await new Promise<void>((resolve) => auth.listen(0, '127.0.0.1', resolve))
+ authBase = `http://127.0.0.1:${(auth.address() as AddressInfo).port}`
+ })
+
+ afterEach(async () => {
+ await new Promise((resolve) => auth.close(resolve))
+ })
+
+ it('hands back the authorization page, and finishes from the pasted address', async () => {
+ const id = await connectors.add({ name: 'Linear', kind: 'remote', url: `${authBase}/mcp`, auth: 'oauth' })
+ await connectors.connect(id) // adding tries once on its own; the click comes after
+ const page = await connectors.authorize(id)
+ expect(page).toBeDefined()
+ const state = new URL(page!).searchParams.get('state')
+ expect(state).toBeTruthy()
+
+ // What the person's browser ended on: the server's loopback, with the code.
+ await connectors.finishOAuthFromUrl(`http://127.0.0.1:1/oauth/callback?code=abc&state=${state}`).catch(() => {})
+ expect(tokenCalls).toHaveLength(1)
+ expect(tokenCalls[0]).toContain('code=abc')
+
+ // Pasted after it finished (the callback got there first): done, not expired, and not exchanged twice.
+ expect(await connectors.finishOAuthFromUrl(`http://127.0.0.1:1/oauth/callback?code=abc&state=${state}`)).toBe(true)
+ expect(tokenCalls).toHaveLength(1)
+ // One it never asked for is no answer.
+ expect(await connectors.finishOAuthFromUrl('http://127.0.0.1:1/oauth/callback?code=abc&state=nope')).toBe(false)
+ })
+
+ it('says what went wrong with an address that is no answer', async () => {
+ await expect(connectors.finishOAuthFromUrl('não é um endereço')).rejects.toThrow()
+ await expect(connectors.finishOAuthFromUrl('http://127.0.0.1:1/oauth/callback?error=access_denied')).rejects.toThrow(/access_denied/)
+ })
+})
diff --git a/test/server.test.ts b/test/server.test.ts
new file mode 100644
index 0000000..a96712e
--- /dev/null
+++ b/test/server.test.ts
@@ -0,0 +1,50 @@
+import { randomBytes } from 'node:crypto'
+import { createServer } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { networkInterfaces } from 'node:os'
+import { describe, expect, it } from 'vitest'
+import { Forwarder, isPrivate } from '../src/server/forward'
+import { vault } from '../src/server/vault'
+
+describe('the server vault', () => {
+ it('opens what it sealed, and nothing sealed with another key', () => {
+ const v = vault(randomBytes(32))
+ const sealed = v.seal('bot-token:123 ção')
+ expect(sealed).not.toContain('bot-token')
+ expect(v.open(sealed)).toBe('bot-token:123 ção')
+ expect(() => vault(randomBytes(32)).open(sealed)).toThrow()
+ })
+
+ it('refuses a tampered secret and a key of the wrong size', () => {
+ const v = vault(randomBytes(32))
+ const b = Buffer.from(v.seal('x'), 'base64')
+ b[b.length - 1]! ^= 1
+ expect(() => v.open(b.toString('base64'))).toThrow()
+ expect(() => vault(randomBytes(16))).toThrow()
+ })
+})
+
+describe('passing services through on a private address', () => {
+ it('knows a private address from a public one', () => {
+ for (const h of ['100.86.178.43', '100.64.0.1', '192.168.3.1', '10.0.0.2', '172.20.1.1']) expect(isPrivate(h)).toBe(true)
+ for (const h of ['0.0.0.0', '116.203.200.219', '100.63.0.1', '100.128.0.1', '172.32.0.1', '127.0.0.1']) expect(isPrivate(h)).toBe(false)
+ })
+
+ // Needs an address of this machine on a private network to listen on.
+ const lan = Object.values(networkInterfaces())
+ .flat()
+ .find((i) => i && i.family === 'IPv4' && !i.internal && isPrivate(i.address))?.address
+ it.skipIf(!lan)('serves a loopback page at the private address, then stops', async () => {
+ const page = createServer((_q, r) => void r.end('do serviço'))
+ await new Promise<void>((r) => page.listen(0, '127.0.0.1', r))
+ const p = (page.address() as AddressInfo).port
+ const f = new Forwarder(lan!)
+ f.set(new Set([p]))
+ await new Promise((r) => setTimeout(r, 100))
+ expect(await (await fetch(`http://${lan}:${p}/`)).text()).toBe('do serviço')
+ f.set(new Set())
+ await new Promise((r) => setTimeout(r, 100))
+ await expect(fetch(`http://${lan}:${p}/`)).rejects.toThrow()
+ await new Promise((r) => page.close(r))
+ })
+})