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.

Remove push and PR from the agent's computer; GitHub goes through its connector (#167)

Eduardo Machadoc321b30789bf
diff --git a/README.md b/README.md
index c11c2c4..15df18a 100644
--- a/README.md
+++ b/README.md
@@ -153,7 +153,7 @@ On Linux and Windows, use **Ctrl** instead of **⌘**. Closing the window keeps
- **Connect a tool:** **Connectors → Add**, paste the MCP server's address. OAuth servers open the browser; the others ask for a token. Then, on each agent's page, set its access to each connector.
- **Archived agents** leave the sidebar and stop answering, but keep their history and receipts. Find them under **Archived** to bring them back.
-- **Approve from your phone:** connect the Telegram bot in **Settings → Phone and GitHub**; approvals and questions arrive with their buttons.
+- **Approve from your phone:** connect the Telegram bot in **Settings → Phone**; approvals and questions arrive with their buttons.
- **Getting started**, in the sidebar, walks you through the rest: build a team, connect a tool, teach the memory, schedule a routine, lend a project.
## How it works
diff --git a/README.pt-BR.md b/README.pt-BR.md
index dca9175..f299b65 100644
--- a/README.pt-BR.md
+++ b/README.pt-BR.md
@@ -153,7 +153,7 @@ No Linux e no Windows, use **Ctrl** no lugar do **⌘**. Fechar a janela deixa o
- **Conectar uma ferramenta:** **Conectores → Adicionar**, cole o endereço do servidor MCP. Os com OAuth abrem o navegador; os outros pedem um token. Depois, na página de cada agente, escolha o acesso dele a cada conector.
- **Agentes arquivados** saem da barra lateral e param de responder, mas o histórico e os recibos ficam. Eles aparecem em **Arquivados**, pra reativar.
-- **Aprovar pelo celular:** conecte o bot do Telegram em **Configurações → Celular e GitHub**; aprovações e perguntas chegam com os botões.
+- **Aprovar pelo celular:** conecte o bot do Telegram em **Configurações → Celular**; aprovações e perguntas chegam com os botões.
- **Primeiros passos**, na barra lateral, leva você pelo resto: montar um time, conectar uma ferramenta, ensinar a memória, agendar uma rotina, emprestar um projeto.
## Como funciona
diff --git a/docs/server.md b/docs/server.md
index 9bee9bf..3876ebe 100644
--- a/docs/server.md
+++ b/docs/server.md
@@ -104,7 +104,7 @@ Once a browser has the cookie, the server answers only its own page: a page of a
- **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.
+- **Notifications:** connect Telegram (**Settings › Phone**) 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), behind a reverse proxy with HTTPS (`TUCANO_URL`): each opens at `https://<port>-<your address>`, with a sign-in of its own that Tucano hands the panel. The proxy has to send those names to Tucano too (`*.tucano.example.com`, with a certificate for each name: Caddy's on-demand TLS does it). Otherwise, they 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.
diff --git a/scripts/screens-new.mjs b/scripts/screens-new.mjs
index 3ea5cb5..73ff89a 100644
--- a/scripts/screens-new.mjs
+++ b/scripts/screens-new.mjs
@@ -50,7 +50,7 @@ await step('configuracoes', async () => {
await win.locator('.card:has(.card__head:has-text("Router")) select').selectOption('jev')
await win.waitForTimeout(300)
await card('Router', '01-router-jev')
- await win.click('.tabs [role=tab]:has-text("Celular e GitHub")')
+ await win.click('.tabs [role=tab]:has-text("Celular")')
await card('Celular (Telegram)', '02-celular-telegram')
await win.click('.tabs [role=tab]:has-text("Agentes")')
await card('Limites', '03-limites')
@@ -174,8 +174,6 @@ await step('configuracoes-2', async () => {
await win.locator('.key-row:has-text("Horário de silêncio") .toggle').click()
await win.waitForTimeout(300)
await card('Rotinas', '20-silencio')
- await win.click('.tabs [role=tab]:has-text("Celular e GitHub")')
- await card('GitHub (push e PR)', '21-github')
await win.click('.tabs [role=tab]:has-text("Geral")')
await card('Time e backup', '22-time-backup')
})
diff --git a/src/core/computer.ts b/src/core/computer.ts
index b0f3430..00e0ed0 100644
--- a/src/core/computer.ts
+++ b/src/core/computer.ts
@@ -371,12 +371,11 @@ export interface ComputerDeps {
dataDir: string
emit: (e: CoreEvent) => void
shoot?: Shooter // screenshots need the main process (Electron's Chromium)
- gitRemote?: (agentId: string) => string | undefined // the app's GitHub proxy for this agent (spec §22)
}
export class Computers {
private infos = new Map<string, ComputerInfo>()
- private gitSet = new Set<string>() // computers whose git already goes through the proxy, this session
+ private gitSet = new Set<string>() // computers whose git was taken off the old GitHub proxy, this session
private ports = new Map<string, Record<number, number>>()
private starting = new Map<string, Promise<void>>()
private prefix: string
@@ -494,7 +493,7 @@ export class Computers {
}
if (state.code === 0 && running === 'true') {
if (!this.ports.has(agentId)) await this.readPorts(agentId)
- await this.pointGit(agentId)
+ await this.unpointGit(agentId)
if (this.infos.get(agentId)?.state !== 'running') this.set(agentId, { state: 'running', services: await this.serviceStatus(agentId) })
return
}
@@ -550,19 +549,17 @@ export class Computers {
await docker(['exec', name, 'bash', '-c', clean], { timeoutMs: 15_000 })
}
await this.readPorts(agentId)
- await this.pointGit(agentId)
+ await this.unpointGit(agentId)
this.set(agentId, { state: 'running', services: await this.serviceStatus(agentId) })
}
- // GitHub, by any of its URL forms, goes through the app's proxy, which adds the
- // token outside the computer and lets through only what its lent folders allow.
- private async pointGit(agentId: string): Promise<void> {
- const via = this.deps.gitRemote?.(agentId)
- if (!via || this.gitSet.has(agentId)) return
+ // A computer made when GitHub went through the app's proxy (push and PR from the agent's computer,
+ // since removed) still sends git there: those rewrites go, so git reaches GitHub as it would.
+ private async unpointGit(agentId: string): Promise<void> {
+ if (this.gitSet.has(agentId)) return
const name = this.name(agentId)
- for (const [from, match] of [['https://github.com/', '^https://github'], ['[email protected]:', '^git@github'], ['ssh://[email protected]/', '^ssh://']] as const) {
- await docker(['exec', name, 'git', 'config', '--global', '--replace-all', `url.${via}.insteadOf`, from, match], { timeoutMs: 15_000 })
- }
+ const drop = "for k in $(git config --global --name-only --get-regexp '^url\\..*/git/.*\\.insteadof$' 2>/dev/null | sed 's/\\.insteadof$//' | sort -u); do git config --global --remove-section \"$k\" 2>/dev/null; done; true"
+ await docker(['exec', name, 'bash', '-c', drop], { timeoutMs: 15_000 }).catch(() => {})
this.gitSet.add(agentId)
}
diff --git a/src/core/context.ts b/src/core/context.ts
index ba10f20..539f0f6 100644
--- a/src/core/context.ts
+++ b/src/core/context.ts
@@ -26,12 +26,11 @@ export function systemPrompt(opts: {
apps?: AgentApp[] // the person's own apps it may use
routines?: Routine[] // its own, when it can schedule
skills?: Skill[] // the active ones it follows, when it has skill tools
- publish?: string[] // the GitHub repositories it can push agent/* branches to
builder?: string // the Tuca's view of the workspace: models, connectors, the team
wiki?: { pages: number; kinds: string[] } // the wiki it may read
connectors?: boolean // it has connector tools (Slack, Databricks…)
}): string {
- const { agent, settings, conversation, peers, memories, canRemember, hasComputer, computerOff, macFolder, offline, web, browser, apps, routines, skills, publish, builder, wiki, connectors } = opts
+ const { agent, settings, conversation, peers, memories, canRemember, hasComputer, computerOff, macFolder, offline, web, browser, apps, routines, skills, builder, wiki, connectors } = opts
const me = settings.workspaceName || L('o usuário', 'the user')
const where =
conversation.kind === 'dm'
@@ -71,15 +70,10 @@ export function systemPrompt(opts: {
`Nelas, mude só o que ${me} pediu e confira com os testes ou o build do projeto. Antes de mexer, olhe o git status; não apague, não reescreva o que não entendeu e não descarte mudanças de ${me}. node_modules e .venv aqui são do Linux, separados dos do computador de ${me}: instale à vontade.`,
`In them, change only what ${me} asked for and check it with the project's tests or build. Before touching anything, look at git status; don't delete, don't rewrite what you don't understand and don't discard ${me}'s changes. node_modules and .venv here are Linux's, separate from ${me}'s computer's: install freely.`
)} ${
- publish?.length
- ? L(
- `Não há credenciais no seu computador, mas o app publica no GitHub (${publish.join(', ')}) por você: faça commit numa branch agent/<assunto> e \`git push origin agent/<assunto>\` (só branches agent/* passam; main e as outras são recusadas). Depois peça a PR com abrir_pr: ${me} aprova e o app abre. Deploy continua com ${me}.`,
- `There are no credentials on your computer, but the app publishes to GitHub (${publish.join(', ')}) for you: commit on an agent/<topic> branch and \`git push origin agent/<topic>\` (only agent/* branches go through; main and the others are refused). Then ask for the PR with abrir_pr: ${me} approves and the app opens it. Deploying stays with ${me}.`
- )
- : L(
- `Não há credenciais no seu computador, então git push e deploy não funcionam: faça commit só se ${me} pedir e diga o que falta ${me} fazer.`,
- `There are no credentials on your computer, so git push and deploys don't work: commit only if ${me} asks and say what's left for ${me} to do.`
- )
+ L(
+ `Não há credenciais no seu computador, então git push e deploy não funcionam: faça commit só se ${me} pedir e diga o que falta ${me} fazer. Pra publicar no GitHub (uma branch, uma PR), use as ferramentas do conector do GitHub, se você tiver.`,
+ `There are no credentials on your computer, so git push and deploys don't work: commit only if ${me} asks and say what's left for ${me} to do. To publish to GitHub (a branch, a PR), use the GitHub connector's tools, if you have it.`
+ )
}\``
].join('\n')
]
diff --git a/src/core/github.ts b/src/core/github.ts
deleted file mode 100644
index 9a53bf0..0000000
--- a/src/core/github.ts
+++ /dev/null
@@ -1,275 +0,0 @@
-// Issue to PR (spec §22). Agents' computers have no credentials; their git
-// talks to GitHub through this proxy, which adds the token on the way out and
-// lets through only what the agent's lent folders allow: fetching their repositories,
-// and pushing only to branches agent/*, for folders it may change.
-// Opening the PR is a tool that becomes an approval; the app opens it with the API.
-import { createHmac, randomBytes } from 'node:crypto'
-import { existsSync, readFileSync, statSync } from 'node:fs'
-import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
-import { join, resolve } from 'node:path'
-import { gunzipSync } from 'node:zlib'
-import { L } from '../shared/lang'
-import type { Agent } from '../shared/types'
-import type { Db } from './db'
-import type { Secrets } from './secrets'
-import { workspacePorts } from './ports'
-
-export const GIT_PROXY_PORT = 47_718
-export const GITHUB = 'github' // the approvals' connector id for abrir_pr
-export const ABRIR_PR = 'abrir_pr'
-const TOKEN = 'github:token'
-const KEY = 'github:proxy-key'
-const MAX_PUSH = 300 * 1024 * 1024
-const AGENT_BRANCH = /^refs\/heads\/agent\/[A-Za-z0-9._\/-]+$/
-const ZERO = /^0{40}$/
-
-type Fetch = typeof fetch
-
-// "owner/name" of a folder's origin on GitHub, read from its git config as text
-// (git itself is never run on a folder an agent can write to). Worktrees included.
-export function githubRepo(folder: string): string | undefined {
- try {
- let gitDir = join(folder, '.git')
- if (statSync(gitDir).isFile()) {
- gitDir = resolve(folder, /gitdir:\s*(.+)/.exec(readFileSync(gitDir, 'utf8'))![1]!.trim())
- const common = join(gitDir, 'commondir')
- if (existsSync(common)) gitDir = resolve(gitDir, readFileSync(common, 'utf8').trim())
- }
- const config = readFileSync(join(gitDir, 'config'), 'utf8')
- const origin = /\[remote "origin"\]([^[]*)/.exec(config)?.[1] ?? ''
- const url = /^\s*url\s*=\s*(.+)$/m.exec(origin)?.[1]?.trim() ?? ''
- return /github\.com[:/]([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/.exec(url)?.[1]
- } catch {
- return undefined
- }
-}
-
-// The ref updates at the start of a receive-pack request: pkt-lines up to the first flush.
-export function pushedRefs(body: Buffer): { old: string; next: string; ref: string; caps?: string }[] | undefined {
- const refs: { old: string; next: string; ref: string; caps?: string }[] = []
- let i = 0
- while (i + 4 <= body.length) {
- const len = parseInt(body.subarray(i, i + 4).toString('ascii'), 16)
- if (Number.isNaN(len)) return undefined
- if (len === 0) return refs
- if (len < 4 || i + len > body.length) return undefined
- const [line, caps] = body.subarray(i + 4, i + len).toString('utf8').split('\0')
- const [old, next, ref] = line!.trim().split(' ')
- if (!old || !next || !ref) return undefined
- refs.push({ old, next, ref, ...(caps ? { caps: caps.trim() } : {}) })
- i += len
- }
- return undefined
-}
-
-export interface GitHubDeps {
- secrets: Pick<Secrets, 'get' | 'set'>
- db: Db
- post: (conversationId: string, text: string) => void // a line in the agent's conversation when something is published
- changed: () => void
- fetch?: Fetch
- upstream?: string // where git goes; https://github.com except in tests
-}
-
-export class GitHub {
- private user?: string
- private error?: string
- private server?: Server
- private key?: string
-
- constructor(private deps: GitHubDeps) {}
-
- private get f(): Fetch {
- return this.deps.fetch ?? fetch
- }
-
- info(): { user?: string; error?: string } {
- return { user: this.user, error: this.error }
- }
-
- async start(): Promise<void> {
- this.key = (await this.deps.secrets.get(KEY)) ?? undefined
- const token = await this.deps.secrets.get(TOKEN)
- if (token) {
- await this.ensureKey()
- try {
- this.user = await this.whoami(token)
- } catch (e) {
- this.error = e instanceof Error ? e.message : String(e)
- }
- this.deps.changed()
- }
- }
-
- listen(port = workspacePorts().git): Server {
- this.server = createServer((req, res) => void this.proxy(req, res).catch((e: unknown) => send(res, 502, `Tucano: ${e instanceof Error ? e.message : String(e)}\n`)))
- this.server.on('error', (e) => console.error(`[github] porta ${port}:`, e.message))
- this.server.listen(port, '127.0.0.1')
- return this.server
- }
-
- stop(): void {
- this.server?.close()
- }
-
- async setToken(token: string | null): Promise<void> {
- const t = token?.trim()
- if (t) this.user = await this.whoami(t)
- else this.user = undefined
- this.error = undefined
- await this.deps.secrets.set(TOKEN, t || undefined)
- if (t) await this.ensureKey()
- this.deps.changed()
- }
-
- // The proxy's key, made the first time GitHub is connected: until then nothing needs the
- // system's vault, so opening the app never asks for it (on Linux, the keyring's prompt).
- private async ensureKey(): Promise<void> {
- if (this.key) return
- this.key = randomBytes(24).toString('hex')
- await this.deps.secrets.set(KEY, this.key)
- }
-
- private async whoami(token: string): Promise<string> {
- let res: Response
- try {
- res = await this.f('https://api.github.com/user', { headers: headers(token), signal: AbortSignal.timeout(10_000) })
- } catch {
- throw new Error(L('Não consegui falar com o GitHub. Confira a internet.', "I couldn't reach GitHub. Check the internet."))
- }
- if (res.status === 401) throw new Error(L('O GitHub recusou esse token.', 'GitHub refused that token.'))
- if (!res.ok) throw new Error(L(`O GitHub respondeu ${res.status}.`, `GitHub answered ${res.status}.`))
- return ((await res.json()) as { login: string }).login
- }
-
- // ---------- what an agent may do ----------
-
- // The path prefix that identifies an agent to the proxy, from a key only the app knows.
- agentToken(agentId: string): string | undefined {
- return this.key && createHmac('sha256', this.key).update(agentId).digest('hex').slice(0, 32)
- }
-
- // The git config that sends an agent's GitHub traffic through the proxy.
- gitRemote(agentId: string): string | undefined {
- const t = this.agentToken(agentId)
- return t && `http://host.docker.internal:${workspacePorts().git}/git/${t}/`
- }
-
- // The folder lent to this agent whose repository is `repo`, and whether it may change it.
- private access(agent: Agent, repo: string): { write: boolean } | undefined {
- const f = (agent.folders ?? []).find((x) => githubRepo(x.path)?.toLowerCase() === repo.toLowerCase())
- return f && { write: !f.readOnly }
- }
-
- // For the prompt and the tools: the repositories of its lent folders it can push to.
- pushable(agent: Agent): string[] {
- if (!this.user) return []
- const repos = (agent.folders ?? []).filter((f) => !f.readOnly).flatMap((f) => githubRepo(f.path) ?? [])
- return [...new Set(repos)]
- }
-
- // ---------- the proxy ----------
-
- private async proxy(req: IncomingMessage, res: ServerResponse): Promise<void> {
- const m = /^\/git\/([0-9a-f]{32})\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/(info\/refs|git-upload-pack|git-receive-pack)(\?.*)?$/.exec(req.url ?? '')
- if (!m) return send(res, 404, L('Tucano: endereço desconhecido\n', 'Tucano: unknown address\n'))
- const [, token, owner, name, path, query = ''] = m
- const agent = this.deps.db.agents().find((a) => this.agentToken(a.id) === token)
- if (!agent) return send(res, 403, L('Tucano: agente desconhecido\n', 'Tucano: unknown agent\n'))
- const repo = `${owner}/${name}`
- const access = this.access(agent, repo)
- if (!access) return send(res, 403, L(`Tucano: ${repo} não é o repositório de uma pasta sua\n`, `Tucano: ${repo} isn't the repository of one of your folders\n`))
- const pushing = path === 'git-receive-pack' || query.includes('service=git-receive-pack')
- if (pushing && !access.write) return send(res, 403, L('Tucano: você só lê esta pasta\n', 'Tucano: you can only read this folder\n'))
- const gh = await this.deps.secrets.get(TOKEN)
- if (!gh) return send(res, 403, L('Tucano: o GitHub não está conectado no app (Configurações → GitHub)\n', "Tucano: GitHub isn't connected in the app (Settings → GitHub)\n"))
-
- const body = req.method === 'POST' ? await read(req, MAX_PUSH) : undefined
- let refs: { old: string; next: string; ref: string }[] | undefined
- if (path === 'git-receive-pack' && body) {
- const raw = req.headers['content-encoding'] === 'gzip' ? gunzipSync(body) : body
- refs = pushedRefs(raw)
- if (!refs) return send(res, 400, L('Tucano: pedido de push que não entendi\n', "Tucano: a push request I didn't understand\n"))
- const bad = refs.find((r) => !AGENT_BRANCH.test(r.ref))
- if (bad) return refuse(res, refs, (r) => (AGENT_BRANCH.test(r.ref) ? L('o push tinha outra branch fora de agent/*', 'the push had another branch outside agent/*') : L('o Tucano aceita so branches agent/<assunto>', 'Tucano only accepts agent/<topic> branches')))
- }
-
- const upstream = await this.f(`${this.deps.upstream ?? 'https://github.com'}/${repo}.git/${path}${query}`, {
- method: req.method,
- headers: {
- Authorization: `Basic ${Buffer.from(`x-access-token:${gh}`).toString('base64')}`,
- 'User-Agent': String(req.headers['user-agent'] ?? 'git/tucano'),
- ...pick(req.headers, ['content-type', 'accept', 'git-protocol', 'content-encoding'])
- },
- body: body ? new Uint8Array(body) : undefined
- })
- const out = Buffer.from(await upstream.arrayBuffer())
- res.writeHead(upstream.status, pick(Object.fromEntries(upstream.headers), ['content-type', 'cache-control', 'expires', 'pragma']))
- res.end(out)
-
- if (refs && upstream.ok) {
- const branches = refs.map((r) => `${ZERO.test(r.next) ? L('apagou', 'deleted') : L('publicou', 'published')} \`${r.ref.replace('refs/heads/', '')}\``).join(', ')
- const conv = this.deps.db.lastConversationOf(agent.id)
- if (conv) this.deps.post(conv, L(`**${agent.name}** ${branches} no GitHub (${repo}).`, `**${agent.name}** ${branches} on GitHub (${repo}).`))
- }
- }
-
- // ---------- the PR, once approved ----------
-
- async openPr(args: Record<string, unknown>): Promise<{ url: string; number: number }> {
- const gh = await this.deps.secrets.get(TOKEN)
- if (!gh) throw new Error(L('o GitHub não está conectado no app', "GitHub isn't connected in the app"))
- const repo = String(args['repo'])
- const res = await this.f(`https://api.github.com/repos/${repo}/pulls`, {
- method: 'POST',
- headers: { ...headers(gh), 'Content-Type': 'application/json' },
- body: JSON.stringify({ title: args['title'], head: args['head'], base: args['base'], body: args['body'], draft: false }),
- signal: AbortSignal.timeout(20_000)
- })
- const body = (await res.json().catch(() => ({}))) as { html_url?: string; number?: number; message?: string; errors?: { message?: string }[] }
- if (!res.ok) throw new Error(L(`o GitHub recusou: ${body.errors?.[0]?.message ?? body.message ?? res.status}`, `GitHub refused: ${body.errors?.[0]?.message ?? body.message ?? res.status}`))
- return { url: body.html_url!, number: body.number! }
- }
-}
-
-const headers = (token: string): Record<string, string> => ({ Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'User-Agent': 'tucano', 'X-GitHub-Api-Version': '2022-11-28' })
-
-function pick(h: Record<string, string | string[] | undefined>, keys: string[]): Record<string, string> {
- const out: Record<string, string> = {}
- for (const k of keys) if (typeof h[k] === 'string') out[k] = h[k]
- return out
-}
-
-const pkt = (s: string | Buffer): Buffer => {
- const b = Buffer.isBuffer(s) ? s : Buffer.from(s)
- return Buffer.concat([Buffer.from((b.length + 4).toString(16).padStart(4, '0')), b])
-}
-
-// A refused push answered like a git server would, so git shows
-// "! [remote rejected] main -> main (o Tucano aceita so branches agent/<assunto>)".
-function refuse(res: ServerResponse, refs: { ref: string; caps?: string }[], why: (r: { ref: string }) => string): void {
- const report = Buffer.concat([pkt('unpack ok\n'), ...refs.map((r) => pkt(`ng ${r.ref} ${why(r)}\n`)), Buffer.from('0000')])
- const banded = refs[0]?.caps?.includes('side-band') ? Buffer.concat([pkt(Buffer.concat([Buffer.from([1]), report])), Buffer.from('0000')]) : report
- res.writeHead(200, { 'Content-Type': 'application/x-git-receive-pack-result', 'Cache-Control': 'no-cache' }).end(banded)
-}
-
-function send(res: ServerResponse, status: number, text: string): void {
- if (res.headersSent) return void res.end()
- res.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8' }).end(text)
-}
-
-function read(req: IncomingMessage, max: number): Promise<Buffer> {
- return new Promise((ok, fail) => {
- const chunks: Buffer[] = []
- let size = 0
- req.on('data', (c: Buffer) => {
- size += c.length
- if (size > max) {
- fail(new Error(L('push grande demais', 'push too big')))
- req.destroy()
- } else chunks.push(c)
- })
- req.on('end', () => ok(Buffer.concat(chunks)))
- req.on('error', fail)
- })
-}
diff --git a/src/core/guide/celular.md b/src/core/guide/celular.md
index f9dffa5..a10a8e6 100644
--- a/src/core/guide/celular.md
+++ b/src/core/guide/celular.md
@@ -4,7 +4,7 @@
Com um bot do Telegram seu, você decide aprovações, responde às perguntas dos agentes (é só responder a mensagem) e recebe o fim das rotinas de qualquer lugar. É útil pra rotina que pede aprovação de madrugada. O app busca as mensagens no Telegram, então nada precisa chegar até o seu computador.
## Ligar
-1. Em **Configurações › Celular e GitHub** (Settings › Phone and GitHub), card **Celular (Telegram)**.
+1. Em **Configurações › Celular** (Settings › Phone), card **Celular (Telegram)**.
2. No Telegram, abra o @BotFather, mande `/newbot` e escolha um nome. Ele devolve um token.
3. Cole o token em **Token do bot** e **Salvar**.
4. Abra o seu bot no Telegram e mande o código que o app mostra (`/start <código>`). Só quem mandar esse código fica com o bot.
diff --git a/src/core/guide/comecar.md b/src/core/guide/comecar.md
index de87328..cd60876 100644
--- a/src/core/guide/comecar.md
+++ b/src/core/guide/comecar.md
@@ -24,4 +24,4 @@ O Tuca fica no topo da barra lateral. Ele monta agentes: você conta uma tarefa,
- **Geral** (General): nome do workspace, como os agentes te chamam, idioma, **Contexto** (o que todo agente lê antes de cada resposta), ditado, notificações, atualizações, time e backup, área de perigo.
- **Modelos** (Models): os harnesses e as contas, o **Roteador** (Router) e o modelo da **Memória**.
- **Agentes** (Agents): navegador dos agentes, rotinas (abrir ao ligar, horário de silêncio) e limites.
-- **Celular e GitHub** (Phone and GitHub): o bot do Telegram e o token do GitHub.
+- **Celular** (Phone): o bot do Telegram.
diff --git a/src/core/guide/computadores.md b/src/core/guide/computadores.md
index d7e6eb8..45b1e0a 100644
--- a/src/core/guide/computadores.md
+++ b/src/core/guide/computadores.md
@@ -1,5 +1,5 @@
# Computador, pastas, GitHub e navegador
-> Onde um agente roda comandos (Linux isolado ou este computador), pastas emprestadas, serviços no ar, push e PR no GitHub, e o navegador do agente.
+> Onde um agente roda comandos (Linux isolado ou este computador), pastas emprestadas, serviços no ar e o navegador do agente.
## O computador do agente
Na página do agente, aba **Ferramentas** › **Computador**:
@@ -15,10 +15,8 @@ Um site ou app que o agente sobe aparece com a **porta** e o estado (**no ar** o
## Pastas do seu computador
Em **Pastas do seu computador**, **Emprestar pasta…** dá ao agente a pasta de um projeto. Pra cada uma: **Só ler** ou **Pode mudar**, e **Devolver**. Ele mexe nos arquivos de verdade, então use git pra poder desfazer. Emprestar ou devolver reinicia o computador do agente: os serviços param, o que ele instalou fica.
-## GitHub: push e PR
-Em **Configurações › Celular e GitHub** › **GitHub (push e PR)**, cole um token fine-grained (github.com → Settings → Developer settings → Fine-grained tokens) só com os repositórios das pastas emprestadas e as permissões **Contents: read and write** e **Pull requests: read and write**. O token fica no cofre do sistema e nunca entra no computador dos agentes.
-- O agente só consegue publicar em branches `agent/<assunto>`; `main` e as outras são recusadas.
-- Abrir o PR vira um pedido de aprovação. Quando você aprova, o link chega numa nova mensagem.
+## GitHub
+O computador do agente não tem credenciais: `git push` não funciona nele. Pra publicar no GitHub (criar uma branch, mandar arquivos, abrir uma PR), o agente usa o **conector do GitHub** (em **Conectores**), com as permissões e aprovações de qualquer conector.
## O navegador do agente
Na aba **Ferramentas**, **Navegador**: um Chrome só dele, com logins separados dos seus. Ele abre páginas, clica, preenche e lê como uma pessoa. Um clique que compra, publica, envia ou apaga pede sua aprovação.
@@ -30,4 +28,3 @@ Na aba **Ferramentas**, **Navegador**: um Chrome só dele, com logins separados
## Quando dá errado
- **sem Docker** / "Precisa do Docker aberto": abra o Docker Desktop e clique em **Verificar de novo**.
- **não ligou**: tente ligar de novo; se continuar, **Apagar computador** e começar do zero.
-- Push recusado: o agente tentou uma branch fora de `agent/*`, ou o token não tem o repositório.
diff --git a/src/core/index.ts b/src/core/index.ts
index c72beb9..3569832 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -35,7 +35,6 @@ import { harnessMcps, publicMcp, type FoundMcp } from './harness-mcp'
import { Gateway } from './gateway'
import { createServer } from 'node:http'
import { checkJevKey, JEV_MODEL, JEV_SECRET } from './jev'
-import { GitHub } from './github'
import { report } from './report'
import { usage } from './usage'
import { Skills } from './skills'
@@ -154,7 +153,7 @@ const ready = Promise.all([gateway.start(), (fake ? Promise.resolve() : adoptLog
const settings = (): Settings => {
const s = db.getSettings(DEFAULTS)
setLang(s.language)
- return { ...s, engines: withChoice(engines, s.harnesses), jevKey: db.getSecret(JEV_SECRET) !== undefined, telegram: telegram?.info(), github: githubInfo(), accounts: (s.accounts ?? []).map((a) => ({ ...a, ...accountLogins.get(a.id) })) }
+ return { ...s, engines: withChoice(engines, s.harnesses), jevKey: db.getSecret(JEV_SECRET) !== undefined, telegram: telegram?.info(), accounts: (s.accounts ?? []).map((a) => ({ ...a, ...accountLogins.get(a.id) })) }
}
// More logins of Claude Code and Codex (Settings › Accounts): each in its own folder, checked with
@@ -182,8 +181,7 @@ function watchAccount(id: string): void {
}, 4_000)
watchingAccount.unref()
}
-// github is made further down; settings can be asked for before.
-const githubInfo = (): Settings['github'] => githubRef?.info()
+
const engineImpls: Record<EngineId, Engine> = fake
? { claude: fakeEngine('claude'), codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
@@ -259,7 +257,6 @@ function emit(event: CoreEvent): void {
// The phone gets each new approval and question as it happens (spec §19).
let telegram: Telegram | undefined
-let githubRef: GitHub | undefined
const sentToPhone = new Set<string>()
function toPhone(e: CoreEvent): void {
if (!telegram) return
@@ -347,7 +344,6 @@ process.parentPort.on('message', (e) => {
routines.stop()
telegram?.stop()
hooks.close()
- github.stop()
runner.stopAll()
void (async () => {
await runner.idle()
@@ -550,20 +546,7 @@ gateway.route('/oauth/callback', oauthCallback)
const memory = new Memories({ db, engines: engineImpls, settings: () => ready.then(settings), emit, workDir: join(dataDir, 'agents') })
-// Issue to PR: the GitHub proxy agents' computers push through (spec §22).
-const github: GitHub = new GitHub({
- secrets,
- db,
- post: (conversationId, text) => {
- const m: Message = { id: randomUUID(), conversationId, author: { kind: 'system' }, text, at: Date.now() }
- db.saveMessage(m)
- emit({ type: 'message', message: m })
- },
- changed: () => emit({ type: 'settings', settings: settings() })
-})
-
-githubRef = github
-const computers = new Computers({ db, dataDir, emit, shoot, gitRemote: (agentId) => github.gitRemote(agentId) })
+const computers = new Computers({ db, dataDir, emit, shoot })
const backups = join(dataDir, 'backups')
// The runner runs routines, and agents schedule routines through the runner's tools.
@@ -636,7 +619,6 @@ const runner = new Runner({
notify: (title, body, conversationId, kind, threadId) =>
kind ? toMain({ type: 'notify', title, body, conversationId, threadId, kind, sound: settings().sounds !== false }) : notifyAll(title, body, conversationId, undefined, { threadId }),
jev: { key: () => secrets.get(JEV_SECRET) },
- github,
onBusy: (busy) => toMain({ type: 'busy', busy }),
onQuota: (quota) => {
db.setSettings({ quota })
@@ -703,14 +685,10 @@ void ready.then(async () => {
setInterval(() => void runner.expireApprovals(), 60_000).unref()
// A thread that went quiet gets its own summary, and the memories in it.
setInterval(() => void memory.sweep().catch((e: unknown) => console.error('[memory]', e)), 60_000).unref()
- // Nothing here waits on the keychain: the first use after an update can be a
- // macOS prompt that stays open until someone answers it.
- void github.start().catch((e: unknown) => console.error('[github]', e))
if (!fake) {
// A port taken (another Tucano open, say) is logged and the rest goes on: a call there reaches
// a server that doesn't know its token, never this workspace's data.
hooks.listen(runtimePorts.webhook, '127.0.0.1')
- github.listen()
void telegram?.start()
}
routines.start()
@@ -1062,7 +1040,6 @@ const api: Api = {
if (!telegram) throw new Error(L('O Telegram fica no workspace padrão.', 'Telegram belongs to the default workspace.'))
return telegram.setToken(token)
},
- setGithubToken: ({ token }) => github.setToken(token),
exportTeam: () => exportTeam(db),
importTeam: ({ text }) => {
const r = importTeam(db, text, settings().defaultLimit)
diff --git a/src/core/runs.ts b/src/core/runs.ts
index dd8158a..9fa11b6 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -13,7 +13,6 @@ import { BROWSER_TOOL_NAMES, browserStep, browserTools, NAVEGADOR, type Browser
import { APP_TOOL_NAMES, APPS, appStep, appTools, type DesktopApps } from './apps'
import { COMPUTER_TOOL_NAMES, computerTools, stepFor, type Computers } from './computer'
import { AGENDAR, CANCELAR, outcome, ROUTINE_TOOL_NAMES, type Routines } from './routines'
-import { ABRIR_PR, GITHUB, type GitHub } from './github'
import { LER_SKILL, PROPOR_SKILL, SKILL_TOOL_NAMES, type Skills } from './skills'
import { availableModels, builderSection, draftFrom, helperSection, PROPOR_AGENTE, PROPOR_TIME, teamFrom } from './tuca'
import { LER_GUIA, readGuide } from './guide'
@@ -32,6 +31,10 @@ import { awaitDone, idleSleepSeconds, isStatusTool, pendingOf, pollTool } from '
import { callError, contentText, errorReason } from './connectors'
import { commandStep, execSummary, keyArg, maskSecrets, resultSummary } from './step-text'
+// An old approval of the push-from-the-computer PRs (they left Tucano): still decided, never run.
+const GITHUB = 'github'
+const ABRIR_PR = 'abrir_pr'
+
const MAX_CONCURRENT = 4
const MAX_TURN_IMAGES = 6 // attached images a reply sees as images; older ones only by name
const mimeOf = (name: string): string => ({ png: 'image/png', gif: 'image/gif', webp: 'image/webp' })[name.split('.').pop()!.toLowerCase()] ?? 'image/jpeg'
@@ -87,7 +90,6 @@ export interface RunnerDeps {
jev?: { key(): Promise<string | undefined>; fetch?: typeof fetch } // the TypeSafe router, when chosen in settings
onBusy?: (busy: boolean) => void // some reply is running (the Mac shouldn't sleep) or none is
onQuota?: (q: Quota) => void // the subscription's windows, as the CLI reports them
- github?: Pick<GitHub, 'pushable' | 'openPr'> // without it, agents can't open PRs
skills?: Pick<Skills, 'forAgent' | 'read' | 'propose'> // without it, agents have no skills
models?: () => { id: string; label: string }[] // what the Tuca may propose; without it, the plans' listed models
wiki?: Pick<Wiki, 'indexText' | 'search' | 'page' | 'count' | 'kinds'> // without it, agents have no wiki
@@ -784,7 +786,7 @@ export class Runner {
const services: string[] = []
const routineIds: string[] = []
const exposed = new Map<string, Exposed>()
- const taken = new Set<string>([ASK_USER.name, ACCESS_REQUEST, ABRIR_PR, LEMBRAR.name, BUSCAR_THREADS.name, LER_THREAD.name, ...COMPUTER_TOOL_NAMES, ...BROWSER_TOOL_NAMES, ...APP_TOOL_NAMES, ...ROUTINE_TOOL_NAMES, ...SKILL_TOOL_NAMES])
+ const taken = new Set<string>([ASK_USER.name, ACCESS_REQUEST, LEMBRAR.name, BUSCAR_THREADS.name, LER_THREAD.name, ...COMPUTER_TOOL_NAMES, ...BROWSER_TOOL_NAMES, ...APP_TOOL_NAMES, ...ROUTINE_TOOL_NAMES, ...SKILL_TOOL_NAMES])
for (const c of this.deps.connectors?.list() ?? []) {
// Dropped for a moment, its tools stay: the next call connects again. An error that needs the person
// (a refused token, a sign-in to finish) takes them away.
@@ -812,32 +814,9 @@ export class Runner {
}
}
: undefined
- // abrir_pr: when a folder lent to this agent is a GitHub repository it can push to.
- const repos = (this.deps.gateway && this.deps.github?.pushable(agent)) || []
- const prTool: ToolDef | undefined = repos.length
- ? {
- name: ABRIR_PR,
- description: L(
- `Pede pra abrir uma pull request em ${repos.join(' ou ')} com uma branch agent/* que você já publicou com git push. Vira um pedido de aprovação; aprovada, o app abre a PR e você recebe o link.`,
- `Asks to open a pull request on ${repos.join(' or ')} from an agent/* branch you already published with git push. It becomes an approval request; once approved, the app opens the PR and you get the link.`
- ),
- inputSchema: {
- type: 'object',
- properties: {
- ...(repos.length > 1 ? { repositorio: { type: 'string', enum: repos } } : {}),
- branch: { type: 'string', description: L('A branch publicada, ex.: agent/lembrete-duplicado.', 'The published branch, e.g. agent/duplicate-reminder.') },
- titulo: { type: 'string' },
- descricao: { type: 'string', description: L('Em Markdown: o que mudou, por quê, como foi testado, o que falta conferir (ex.: o build no Xcode).', "In Markdown: what changed, why, how it was tested, what's left to check (e.g. the Xcode build).") },
- base: { type: 'string', description: L('A branch de destino. Default: main.', 'The target branch. Default: main.') }
- },
- required: [...(repos.length > 1 ? ['repositorio'] : []), 'branch', 'titulo', 'descricao']
- }
- }
- : undefined
const toolDefs: ToolDef[] = [
ASK_USER,
...(accessTool ? [accessTool] : []),
- ...(prTool ? [prTool] : []),
...(canRemember ? [LEMBRAR] : []),
...(canSearch ? [BUSCAR_MEMORIAS] : []),
...(canSeekThreads ? [BUSCAR_THREADS, LER_THREAD] : []),
@@ -1213,44 +1192,6 @@ export class Runner {
return clip(out.result)
}
- if (name === ABRIR_PR && prTool) {
- const repo = repos.length > 1 ? repos.find((r) => r === args['repositorio']) : repos[0]
- if (!repo) return textResult(L(`Diga o repositório: ${repos.join(' ou ')}.`, `Say the repository: ${repos.join(' or ')}.`), true)
- const branch = typeof args['branch'] === 'string' ? args['branch'].trim().replace(/^refs\/heads\//, '') : ''
- const title = typeof args['titulo'] === 'string' ? args['titulo'].trim() : ''
- if (!/^agent\/[A-Za-z0-9._\/-]+$/.test(branch)) return textResult(L('A branch precisa ser agent/<assunto>, já publicada com git push.', 'The branch must be agent/<topic>, already published with git push.'), true)
- if (!title) return textResult(L('Faltou o título.', 'Missing the title.'), true)
- if (question || approval) return textResult(L('Já existe um pedido esperando decisão nesta mensagem. Encerre agora.', 'There is already a request waiting for a decision in this message. End now.'), true)
- const prArgs = { repo, head: branch, base: typeof args['base'] === 'string' && args['base'].trim() ? args['base'].trim() : 'main', title, body: typeof args['descricao'] === 'string' ? args['descricao'] : '' }
- approval = {
- id: randomUUID(),
- hash: approvalHash(GITHUB, ABRIR_PR, prArgs),
- agentId: agent.id,
- conversationId: conv.id,
- messageId: msg.id,
- connectorId: GITHUB,
- connectorName: 'GitHub',
- tool: ABRIR_PR,
- args: prArgs,
- why: title,
- highRisk: false,
- state: 'pending',
- createdAt: Date.now(),
- expiresAt: Date.now() + settings.approvalTtlHours * 3_600_000
- }
- db.createApproval(approval)
- emit({ type: 'approval', approval })
- msg.run = { ...msg.run!, approvalId: approval.id }
- addSteps({ id: randomUUID(), label: L('Pediu pra abrir a PR', 'Asked to open the PR'), detail: `${branch} → ${prArgs.base}`, status: 'done' })
- this.deps.notify?.(L(`${agent.name} quer abrir uma PR`, `${agent.name} wants to open a PR`), `${repo}: ${title}`, conv.id, 'approval', msg.threadId)
- return textResult(
- L(
- `Pedido de PR criado. A PR ainda NÃO existe. Encerre sua resposta agora dizendo em uma frase o que vai na PR. Quando ${settings.workspaceName} aprovar, você recebe o link numa nova mensagem.`,
- `PR request created. The PR does NOT exist yet. End your reply now saying in one sentence what goes in the PR. When ${settings.workspaceName} approves, you get the link in a new message.`
- )
- )
- }
-
if (name === ACCESS_REQUEST && accessTool) {
const c = this.deps.connectors?.list().find((x) => x.name === args['conector'])
const nivel = args['nivel'] === 'read_write' ? 'read_write' : 'read'
@@ -1481,7 +1422,6 @@ export class Runner {
routines: routines?.forAgent(agent.id),
skills: skills && mySkills,
wiki: wiki ? { pages: wiki.count(), kinds: wiki.kinds() } : undefined,
- publish: repos,
connectors: exposed.size > 0,
builder: proposes
? [builderSection(settings, { models: this.deps.models?.() ?? availableModels(settings), connectors: this.deps.connectors?.list() ?? [], team: db.agents().filter((a) => !a.archived && a.kind !== 'tuca'), own: agent.modelId, tuca: helps, me: settings.workspaceName }), helps && helperSection()].filter(Boolean).join('\n\n')
@@ -1709,33 +1649,13 @@ export class Runner {
let ok = false // whether the approved thing went through
let task: string
if (ap.connectorId === GITHUB && ap.tool === ABRIR_PR) {
- if (decision === 'approved') {
- try {
- const work = db.message(ap.messageId)?.run?.work
- const cost = work ? db.costByWork(0).find((w) => w.work === work) : undefined
- const footer = L(
- `\n\n---\nFeita por ${agent?.name ?? 'um agente'} no Tucano${cost ? ` · ${work}: ${tokenCount(cost.tokens)} tokens em ${cost.replies} resposta${cost.replies > 1 ? 's' : ''} até aqui` : ''}.`,
- `\n\n---\nMade by ${agent?.name ?? 'an agent'} in Tucano${cost ? ` · ${work}: ${tokenCount(cost.tokens)} tokens in ${cost.replies} repl${cost.replies > 1 ? 'ies' : 'y'} so far` : ''}.`
- )
- const pr = await this.deps.github!.openPr({ ...ap.args, body: `${String(ap.args['body'] ?? '')}${footer}` })
- ok = true
- outcome = L(`Abriu a PR #${pr.number}.`, `Opened PR #${pr.number}.`)
- task = L(`${me} aprovou, e o app abriu a PR #${pr.number}: ${pr.url}\n\nAvise ${me} com o link em uma frase.`, `${me} approved, and the app opened PR #${pr.number}: ${pr.url}\n\nTell ${me} with the link in one sentence.`)
- } catch (e) {
- const err = e instanceof Error ? e.message : String(e)
- outcome = L(`Falhou: ${err}`, `Failed: ${err}`)
- task = L(
- `${me} aprovou a PR, mas ela não abriu: ${err}. Conte a ${me} e diga o que fazer (a branch foi publicada? já existe uma PR dela?).`,
- `${me} approved the PR, but it didn't open: ${err}. Tell ${me} and say what to do (was the branch published? is there already a PR for it?).`
- )
- }
- } else {
- outcome = decision === 'refused' ? L('Nada foi aberto.', 'Nothing was opened.') : expired
- task = L(
- `${me} ${decision === 'refused' ? `recusou a PR${reason ? `: "${reason}"` : ''}` : 'não respondeu ao pedido de PR'}. Nada foi aberto. Responda considerando isso.`,
- `${me} ${decision === 'refused' ? `turned down the PR${reason ? `: "${reason}"` : ''}` : "didn't answer the PR request"}. Nothing was opened. Reply with that in mind.`
- )
- }
+ // A PR asked for before pushing from the agent's computer left Tucano: nothing is opened.
+ // The GitHub connector does it now, with the person's approval like any of its tools.
+ outcome = decision === 'expired' ? expired : L('Nada foi aberto: abrir PR assim saiu do Tucano.', 'Nothing was opened: opening a PR this way left Tucano.')
+ task = L(
+ `${me} ${decision === 'approved' ? 'aprovou' : decision === 'refused' ? 'recusou' : 'não respondeu a'} um pedido de PR antigo, mas abrir PR pelo computador saiu do Tucano e nada foi aberto. Se você tem o conector do GitHub, abra a PR por ele; senão, diga a ${me} que ele precisa dar a você o conector do GitHub.`,
+ `${me} ${decision === 'approved' ? 'approved' : decision === 'refused' ? 'turned down' : "didn't answer"} an old PR request, but opening a PR from the computer left Tucano and nothing was opened. If you have the GitHub connector, open the PR with it; otherwise, tell ${me} you need the GitHub connector.`
+ )
} else if (ap.connectorId === APPS) {
// A click or key in one of the person's apps: made on the same app, on the same element.
const onde = typeof ap.args['onde'] === 'string' ? ap.args['onde'] : ''
diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsx
index 1ae9ce2..afb1302 100644
--- a/src/renderer/src/components/Pages.tsx
+++ b/src/renderer/src/components/Pages.tsx
@@ -28,7 +28,6 @@ import {
browserAction,
setTelegramToken,
unpairTelegram,
- setGithubToken,
exportTeam,
importAgents,
importTeam,
@@ -1402,7 +1401,7 @@ const SETTINGS_TABS = (): TabList => [
['geral', L('Geral', 'General')],
['modelos', L('Modelos', 'Models')],
['agentes', L('Agentes', 'Agents')],
- ['integracoes', L('Celular e GitHub', 'Phone and GitHub')],
+ ['integracoes', L('Celular', 'Phone')],
...(hasServers() ? [['servidores', L('Servidores', 'Servers')] as [string, string]] : [])
]
const AGENT_TABS = (): TabList => [
@@ -1525,58 +1524,6 @@ export function LanguagePicker({ className = '' }: { className?: string }): Reac
}
// Issue to PR (spec §22): the token the app pushes agent/* branches and opens PRs with.
-function GithubCard({ info }: { info?: { user?: string; error?: string } }): ReactNode {
- const [token, setToken] = useState('')
- const [busy, setBusy] = useState(false)
- const [error, setError] = useState('')
- const save = (value: string | null): void => {
- setBusy(true)
- setError('')
- setGithubToken(value)
- .then(() => setToken(''))
- .catch((e: unknown) => setError(e instanceof Error ? e.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, '') : String(e)))
- .finally(() => setBusy(false))
- }
- return (
- <Card
- title={L('GitHub (push e PR)', 'GitHub (push and PR)')}
- lead={L(
- 'Pros agentes publicarem o que fazem nas pastas que você emprestou: o git do computador deles passa pelo app, que põe o token fora do computador e só aceita push em branches agent/*. Abrir PR é um pedido de aprovação.',
- 'So agents can publish what they do in the folders you lent: their computer’s git goes through the app, which keeps the token outside the computer and only accepts pushes to agent/* branches. Opening a PR is an approval request.'
- )}
- >
- {info?.user ? (
- <div className="row row--center">
- <span className="tag tag--ok">{L('Conectado', 'Connected')}</span>
- <span className="small grow">
- {L('como', 'as')} <strong>{info.user}</strong>
- </span>
- <button className="btn btn--sm btn--ghost" onClick={() => save(null)}>
- {L('Remover token', 'Remove token')}
- </button>
- </div>
- ) : (
- <>
- <p className="small">
- {L('Crie um token fine-grained em github.com → Settings → Developer settings →', 'Create a fine-grained token at github.com → Settings → Developer settings →')} <strong>Fine-grained tokens</strong>
- {L(', só com os repositórios dessas pastas e as permissões', ', with only these folders’ repositories and the permissions')} <strong>Contents: read and write</strong> {L('e', 'and')} <strong>Pull requests: read and write</strong>.
- </p>
- <div className="row">
- <input className="grow" type="password" value={token} placeholder="github_pat_…" onChange={(e) => setToken(e.target.value)} />
- <button className="btn" disabled={busy || !token.trim()} onClick={() => save(token)}>
- {busy ? L('Conferindo…', 'Checking…') : L('Salvar', 'Save')}
- </button>
- </div>
- </>
- )}
- {(error || info?.error) && <p className="note note--error">{error || info?.error}</p>}
- <p className="hint">
- <Icon name="shield" size={13} /> {L('O token fica no cofre do sistema e nunca entra no computador dos agentes. main e as outras branches são recusadas no caminho.', 'The token stays in the system’s vault and never enters the agents’ computer. main and the other branches are refused on the way.')}
- </p>
- </Card>
- )
-}
-
// The team as a file, and backups of everything.
const MAX_UPLOAD = 40_000_000 // a browser's request has a cap (64 MB) and base64 grows a third
function TeamCard(): ReactNode {
@@ -2091,7 +2038,6 @@ export function SettingsPage(): ReactNode {
</Card>
)}
- {pane('integracoes') && <GithubCard info={settings.github} />}
{pane('geral') && <TeamCard />}
{pane('servidores') && <ServersCard />}
diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.ts
index 28e232c..a77eb56 100644
--- a/src/renderer/src/store.ts
+++ b/src/renderer/src/store.ts
@@ -614,7 +614,6 @@ export const skillVersions = (skillId: string): Promise<SkillVersion[]> => call(
export const checkTrigger = (trigger: Trigger): Promise<string> => call('checkTrigger', { trigger })
export const setTelegramToken = (token: string | null): Promise<void> => call('setTelegramToken', { token })
export const unpairTelegram = (): void => void fire(L('Não consegui desconectar o Telegram.', "I couldn't disconnect Telegram."), 'unpairTelegram')
-export const setGithubToken = (token: string | null): Promise<void> => call('setGithubToken', { token })
export const exportTeam = (): Promise<string> => call('exportTeam')
export const importTeam = (text: string): Promise<string> => call('importTeam', { text })
export const importAgents = (p: { path?: string; data?: string }): Promise<string> => call('importAgents', p)
diff --git a/src/shared/rpc.ts b/src/shared/rpc.ts
index bb8b97b..f8560de 100644
--- a/src/shared/rpc.ts
+++ b/src/shared/rpc.ts
@@ -117,7 +117,6 @@ export interface Api {
openBackups(): void
report(p: { week?: number }): Report // the calendar week starting at `week` (a Monday); this one by default
usage(): UsageReport
- setGithubToken(p: { token: string | null }): Promise<void> // checked with GitHub; throws why it's refused
removeRoutine(p: { id: string }): void
runRoutine(p: { id: string }): void
// The wiki: pages in a folder of Markdown, linked, searched and kept with their history.
diff --git a/src/shared/types.ts b/src/shared/types.ts
index e1ff0c7..4272185 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -282,7 +282,6 @@ export interface Settings {
paused?: boolean // "Pausar tudo": no agent starts working, no routine runs
quietHours?: { from: string; to: string } | null // "HH:MM": routines and triggers wait, and run late when it ends; null: off
quota?: Quota // the Claude subscription's windows, from the last reply (spec §21)
- github?: { user?: string; error?: string } // computed: the GitHub account the app pushes and opens PRs with (spec §22)
// The harnesses agents may run on, picked in the introduction. Unset: every one that's ready.
harnesses?: EngineId[]
// The first-run introduction: unset on an existing install (no intro), done:false to show it (a new install, or "Rever a introdução")
diff --git a/test/github.test.ts b/test/github.test.ts
deleted file mode 100644
index acbabe4..0000000
--- a/test/github.test.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
-import type { AddressInfo } from 'node:net'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
-import type { Agent, Message, Settings } from '../src/shared/types'
-import { Db } from '../src/core/db'
-import { callTool, fakeEngine } from '../src/core/engines/fake'
-import type { Engine } from '../src/core/engines/types'
-import { Gateway } from '../src/core/gateway'
-import { GitHub, githubRepo, pushedRefs } from '../src/core/github'
-import { Runner } from '../src/core/runs'
-
-const pkt = (s: string): string => (s.length + 4).toString(16).padStart(4, '0') + s
-const Z = '0'.repeat(40)
-const A = 'a'.repeat(40)
-const push = (...refs: string[]): Buffer => Buffer.concat([Buffer.from(refs.map((r, i) => pkt(`${Z} ${A} ${r}${i === 0 ? '\0report-status' : ''}\n`)).join('') + '0000'), Buffer.from('PACK…')])
-
-describe('reading the repository', () => {
- it('finds the GitHub repo of a folder from its config, worktrees included', () => {
- const main = mkdtempSync(join(tmpdir(), 'repo-'))
- mkdirSync(join(main, '.git', 'worktrees', 'agentes'), { recursive: true })
- writeFileSync(join(main, '.git', 'config'), '[core]\n\tbare = false\n[remote "origin"]\n\turl = https://github.com/eduwxyz/simula-oab.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n')
- writeFileSync(join(main, '.git', 'worktrees', 'agentes', 'commondir'), '../..\n')
- const wt = mkdtempSync(join(tmpdir(), 'wt-'))
- writeFileSync(join(wt, '.git'), `gitdir: ${join(main, '.git', 'worktrees', 'agentes')}\n`)
- expect(githubRepo(main)).toBe('eduwxyz/simula-oab')
- expect(githubRepo(wt)).toBe('eduwxyz/simula-oab')
- writeFileSync(join(main, '.git', 'config'), '[remote "origin"]\n\turl = [email protected]:eduwxyz/outro.git\n')
- expect(githubRepo(main)).toBe('eduwxyz/outro')
- })
-
- it('reads the branches a push updates', () => {
- expect(pushedRefs(push('refs/heads/agent/x', 'refs/heads/main'))!.map((r) => r.ref)).toEqual(['refs/heads/agent/x', 'refs/heads/main'])
- expect(pushedRefs(Buffer.from('garbage'))).toBeUndefined()
- })
-})
-
-describe('the proxy key', () => {
- it("isn't made until GitHub is connected, so opening the app never touches the system's vault", async () => {
- const store = new Map<string, string>()
- const sets: string[] = []
- const secrets = { get: async (k: string) => store.get(k), set: async (k: string, v?: string) => void (sets.push(k), v === undefined ? store.delete(k) : store.set(k, v)) }
- const fetch = (async () => new Response(JSON.stringify({ login: 'edu' }), { status: 200 })) as typeof globalThis.fetch
- const gh = new GitHub({ secrets, db: new Db(':memory:'), post: () => {}, changed: () => {}, fetch })
- await gh.start()
- expect(sets).toEqual([])
- expect(gh.agentToken('a1')).toBeUndefined()
- await gh.setToken('ghp_x')
- expect(sets).toEqual(['github:token', 'github:proxy-key'])
- expect(gh.agentToken('a1')).toMatch(/^[0-9a-f]{32}$/)
- })
-})
-
-describe('the proxy and the PR', () => {
- let db: Db
- let gh: GitHub
- let base: string
- let upstream: { url: string; auth?: string; body?: number }[]
- let posted: string[]
- let folder: string
- let store: Map<string, string>
-
- const agent = (id: string, handle: string): Agent => ({ id, name: handle[0]!.toUpperCase() + handle.slice(1), handle, role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'read', computer: true, archived: false })
-
- beforeEach(async () => {
- db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-gh-')), 'test.db'))
- folder = mkdtempSync(join(tmpdir(), 'proj-'))
- mkdirSync(join(folder, '.git'))
- writeFileSync(join(folder, '.git', 'config'), '[remote "origin"]\n\turl = https://github.com/eduwxyz/simula-oab.git\n')
- db.saveAgent(agent('staff', 'staff'))
- db.saveAgent(agent('rev', 'revisor'))
- db.createConversation({ id: 'c1', kind: 'channel', name: 'simula-oab', members: ['staff', 'rev'] })
- db.saveMessage({ id: 'm0', conversationId: 'c1', author: { kind: 'agent', id: 'staff' }, text: 'Corrigindo.', at: 1 }) // the push notice goes where it's working
- db.setFolders('staff', [{ name: 'simula-oab', path: folder, readOnly: false }])
- db.setFolders('rev', [{ name: 'simula-oab', path: folder, readOnly: true }])
- upstream = []
- posted = []
- store = new Map([['github:token', 'ghp_test']])
- const f = (async (url: string, init?: RequestInit) => {
- if (url === 'https://api.github.com/user') return Response.json({ login: 'eduwxyz' })
- if (url.endsWith('/pulls')) {
- upstream.push({ url, body: JSON.parse(String(init?.body)) })
- return Response.json({ html_url: 'https://github.com/eduwxyz/simula-oab/pull/7', number: 7 }, { status: 201 })
- }
- upstream.push({ url, auth: (init?.headers as Record<string, string>)['Authorization'], body: init?.body ? (init.body as Uint8Array).length : 0 })
- return new Response('ok-from-github', { status: 200, headers: { 'content-type': 'application/x-git-receive-pack-result' } })
- }) as unknown as typeof fetch
- gh = new GitHub({ secrets: { get: async (k) => store.get(k), set: async (k, v) => void (v === undefined ? store.delete(k) : store.set(k, v)) }, db, post: (_c, t) => posted.push(t), changed: () => {}, fetch: f })
- await gh.start()
- const server = gh.listen(0)
- await new Promise((r) => server.once('listening', r))
- base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
- })
- afterEach(() => gh.stop())
-
- const url = (agentId: string, path: string): string => `${base}/git/${gh.agentToken(agentId)}/eduwxyz/simula-oab.git/${path}`
-
- it('adds the token on the way out, and lets through only agent/* branches', async () => {
- const ok = await fetch(url('staff', 'git-receive-pack'), { method: 'POST', body: new Uint8Array(push('refs/heads/agent/lembrete')) })
- expect(ok.status).toBe(200)
- expect(await ok.text()).toBe('ok-from-github')
- expect(upstream[0]!.url).toBe('https://github.com/eduwxyz/simula-oab.git/git-receive-pack')
- expect(upstream[0]!.auth).toBe(`Basic ${Buffer.from('x-access-token:ghp_test').toString('base64')}`)
- expect(posted).toEqual(['**Staff** publicou `agent/lembrete` no GitHub (eduwxyz/simula-oab).'])
-
- const main = await fetch(url('staff', 'git-receive-pack'), { method: 'POST', body: new Uint8Array(push('refs/heads/agent/ok', 'refs/heads/main')) })
- const report = await main.text()
- expect(report).toContain('ng refs/heads/main o Tucano aceita so branches agent/<assunto>')
- expect(report).toContain('ng refs/heads/agent/ok o push tinha outra branch fora de agent/*')
- expect(upstream).toHaveLength(1) // nothing reached GitHub
- })
-
- it('a read-only agent fetches but never pushes; other repos and unknown agents get nothing', async () => {
- expect((await fetch(url('rev', 'info/refs?service=git-upload-pack'))).status).toBe(200)
- expect((await fetch(url('rev', 'info/refs?service=git-receive-pack'))).status).toBe(403)
- expect((await fetch(url('rev', 'git-receive-pack'), { method: 'POST', body: new Uint8Array(push('refs/heads/agent/x')) })).status).toBe(403)
- expect((await fetch(`${base}/git/${gh.agentToken('staff')}/eduwxyz/outro.git/info/refs?service=git-upload-pack`)).status).toBe(403)
- expect((await fetch(`${base}/git/${'0'.repeat(32)}/eduwxyz/simula-oab.git/info/refs`)).status).toBe(403)
- })
-
- it('abrir_pr becomes an approval; approved, the app opens the PR with the cost of the issue', async () => {
- const ready = { installed: true, loggedIn: true }
- const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
- const gateway = new Gateway()
- await gateway.start()
- const claude: Engine = {
- id: 'claude',
- async *run(turn) {
- if (!turn.prompt.includes('abriu a PR')) await callTool(turn.mcpUrl!, 'abrir_pr', { branch: 'agent/lembrete', titulo: 'Corrige lembrete duplicado', descricao: 'Testado no Core.' })
- yield { type: 'done', text: 'ok', usage: { inputTokens: 1000, cacheReadTokens: 0, outputTokens: 10 } }
- }
- }
- const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'w-')), gateway, github: gh, computers: { call: async () => ({ result: { content: [] } }) } })
- await r.send('c1', '@staff corrige a OAB-66')
- await r.idle()
- const [ap] = db.approvals()
- expect(ap).toMatchObject({ connectorName: 'GitHub', tool: 'abrir_pr', args: { repo: 'eduwxyz/simula-oab', head: 'agent/lembrete', base: 'main', title: 'Corrige lembrete duplicado' } })
- expect(upstream).toHaveLength(0)
- await r.decide(ap!.id, 'approved')
- await r.idle()
- expect(upstream[0]).toMatchObject({ url: 'https://api.github.com/repos/eduwxyz/simula-oab/pulls', body: { head: 'agent/lembrete', base: 'main' } })
- expect((upstream[0]!.body as unknown as { body: string }).body).toMatch(/Testado no Core\.\n\n---\nFeita por Staff no Tucano · OAB-66: \d+ mil tokens em 1 resposta até aqui\./)
- expect(db.approval(ap!.id)!.outcome).toBe('Abriu a PR #7.')
- const last = db.messages().filter((m: Message) => m.author.kind === 'agent').at(-1)!
- expect(last.run?.work).toBe('OAB-66')
- await gateway.stop()
- })
-})