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.

Let agents run on more than one Claude Code or Codex account (#71)

Eduardo Machadoff200e9865d6
diff --git a/src/core/db.ts b/src/core/db.ts
index 9f548d9..7af8cb9 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -224,6 +224,9 @@ const MIGRATIONS = [
`,
`
ALTER TABLE agents ADD COLUMN fallback_model TEXT;
+ `,
+ `
+ ALTER TABLE agents ADD COLUMN account TEXT;
`
]
@@ -307,6 +310,7 @@ export class Db {
color: str(r['color']) as AgentColor,
instructions: str(r['instructions']),
modelId: str(r['model']),
+ ...(str(r['account']) ? { accountId: str(r['account']) } : {}),
...(str(r['fallback_model']) ? { fallbackModelId: str(r['fallback_model']) } : {}),
effort: str(r['effort']) as Effort,
limit: Number(r['limit_tokens']),
@@ -337,14 +341,14 @@ export class Db {
saveAgent(a: Agent): void {
this.db
.prepare(
- `INSERT INTO agents (id, name, handle, role, color, instructions, model, fallback_model, effort, limit_tokens, grants, memory_mode, computer, computer_kind, web, browser, apps, auto_approve, archived, kind, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `INSERT INTO agents (id, name, handle, role, color, instructions, model, fallback_model, account, effort, limit_tokens, grants, memory_mode, computer, computer_kind, web, browser, apps, auto_approve, archived, kind, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (id) DO UPDATE SET name = excluded.name, handle = excluded.handle, role = excluded.role,
- color = excluded.color, instructions = excluded.instructions, model = excluded.model, fallback_model = excluded.fallback_model, effort = excluded.effort,
+ color = excluded.color, instructions = excluded.instructions, model = excluded.model, fallback_model = excluded.fallback_model, account = excluded.account, effort = excluded.effort,
limit_tokens = excluded.limit_tokens, grants = excluded.grants, memory_mode = excluded.memory_mode,
computer = excluded.computer, computer_kind = excluded.computer_kind, web = excluded.web, browser = excluded.browser, apps = excluded.apps, auto_approve = excluded.auto_approve, archived = excluded.archived, kind = COALESCE(excluded.kind, agents.kind)`
)
- .run(a.id, a.name, a.handle, a.role, a.color, a.instructions, a.modelId, a.fallbackModelId || null, a.effort, a.limit, JSON.stringify(a.grants), a.memory ?? 'auto', a.computer ? 1 : 0, a.computerKind === 'mac' ? 'mac' : 'linux', a.web === false ? 0 : 1, a.browser ? 1 : 0, JSON.stringify(a.apps ?? []), JSON.stringify(a.autoApprove ?? []), a.archived ? 1 : 0, a.kind ?? null, Date.now())
+ .run(a.id, a.name, a.handle, a.role, a.color, a.instructions, a.modelId, a.fallbackModelId || null, a.accountId || null, a.effort, a.limit, JSON.stringify(a.grants), a.memory ?? 'auto', a.computer ? 1 : 0, a.computerKind === 'mac' ? 'mac' : 'linux', a.web === false ? 0 : 1, a.browser ? 1 : 0, JSON.stringify(a.apps ?? []), JSON.stringify(a.autoApprove ?? []), a.archived ? 1 : 0, a.kind ?? null, Date.now())
}
// Kept apart from saveAgent: folders change only after the core checks them.
diff --git a/src/core/engines/claude.ts b/src/core/engines/claude.ts
index acff0d7..6ea1da2 100644
--- a/src/core/engines/claude.ts
+++ b/src/core/engines/claude.ts
@@ -178,7 +178,7 @@ export function claudeEngine(bin: () => string | undefined, provider: () => Prom
}
// The gateway's token goes in the environment, never in the arguments (other processes can read those).
const p = await provider()
- yield* runCli({ bin: path, args: claudeArgs(turn, p.apiKeyHelper), stdin: claudeInput(turn), cwd: turn.cwd, signal: turn.signal, parser: claudeParser(), env: { ...process.env, ...p.env, MCP_TOOL_TIMEOUT: '900000' } })
+ yield* runCli({ bin: path, args: claudeArgs(turn, p.apiKeyHelper), stdin: claudeInput(turn), cwd: turn.cwd, signal: turn.signal, parser: claudeParser(), env: { ...process.env, ...p.env, ...(turn.account ? { CLAUDE_CONFIG_DIR: turn.account } : {}), MCP_TOOL_TIMEOUT: '900000' } })
}
}
}
diff --git a/src/core/engines/codex.ts b/src/core/engines/codex.ts
index 73442da..733c5dc 100644
--- a/src/core/engines/codex.ts
+++ b/src/core/engines/codex.ts
@@ -182,7 +182,7 @@ export function codexEngine(
const p = await provider()
const shell = await shellEnv() // read once per launch
const keys = Object.fromEntries(p.envNames.flatMap((n) => (shell[n] ? [[n, shell[n]]] : [])))
- yield* runCli({ bin: path, args: codexArgs(turn, p.config), stdin: turn.prompt, cwd: turn.cwd, signal: turn.signal, parser: codexParser(), env: { ...codexEnv(home), ...keys, ...p.env } })
+ yield* runCli({ bin: path, args: codexArgs(turn, p.config), stdin: turn.prompt, cwd: turn.cwd, signal: turn.signal, parser: codexParser(), env: { ...codexEnv(turn.account ?? home), ...keys, ...p.env } })
}
}
}
diff --git a/src/core/engines/detect.ts b/src/core/engines/detect.ts
index f26a7b6..b16669b 100644
--- a/src/core/engines/detect.ts
+++ b/src/core/engines/detect.ts
@@ -4,7 +4,7 @@ import { existsSync, readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
import { L } from '../../shared/lang'
-import type { EngineId, EngineStatus } from '../../shared/types'
+import type { AccountEngine, EngineId, EngineStatus } from '../../shared/types'
import { executableNames, isWin, pathDirs, spawnable, withInstallDirs } from '../platform'
import { userProvider } from './claude'
import { codexEnv, userCodexProvider } from './codex'
@@ -90,6 +90,34 @@ const gatewayHost = (url: string | undefined): string | undefined => {
}
// Checks the app's own Codex login (see codexEnv), not the user's.
+// Whether another login of Claude Code or Codex (Settings › Accounts) is signed in, and on which
+// plan, from the CLI's own status for that folder. The parsing is pure, to test it on their output.
+export function accountLogin(engine: AccountEngine, out: { code: number; stdout: string; stderr: string }): { loggedIn: boolean; detail?: string } {
+ if (engine === 'claude') {
+ let status: Record<string, unknown> = {}
+ try {
+ status = JSON.parse(out.stdout) as Record<string, unknown>
+ } catch {
+ // not signed in, or an older CLI
+ }
+ if (status['loggedIn'] !== true) return { loggedIn: false }
+ const plan = typeof status['subscriptionType'] === 'string' ? status['subscriptionType'] : undefined
+ const email = typeof status['email'] === 'string' ? status['email'] : undefined
+ const what = status['authMethod'] === 'claude.ai' ? `${L('Plano Claude', 'Claude plan')}${plan ? ` ${plan[0]!.toUpperCase()}${plan.slice(1)}` : ''}` : L('Chave de API', 'API key')
+ return { loggedIn: true, detail: email ? `${what} · ${email}` : what }
+ }
+ const text = `${out.stdout}\n${out.stderr}`
+ const loggedIn = out.code === 0 && /logged in/i.test(text) && !/not logged in/i.test(text)
+ return loggedIn ? { loggedIn, detail: /chatgpt/i.test(text) ? L('Plano ChatGPT', 'ChatGPT plan') : L('Chave de API', 'API key') } : { loggedIn }
+}
+
+export const accountDir = (dataDir: string, id: string): string => join(dataDir, 'accounts', id)
+
+export async function accountStatus(engine: AccountEngine, bin: string, dir: string): Promise<{ loggedIn: boolean; detail?: string }> {
+ const out = engine === 'claude' ? await run(bin, ['auth', 'status'], 15_000, { ...process.env, CLAUDE_CONFIG_DIR: dir }) : await run(bin, ['login', 'status'], 15_000, codexEnv(dir))
+ return accountLogin(engine, out)
+}
+
export async function detectCodex(home: string): Promise<EngineStatus> {
const path = await which('codex')
if (!path) return { installed: false, loggedIn: false }
diff --git a/src/core/engines/types.ts b/src/core/engines/types.ts
index d45b449..2405938 100644
--- a/src/core/engines/types.ts
+++ b/src/core/engines/types.ts
@@ -11,6 +11,7 @@ export interface Turn {
signal: AbortSignal
mcpUrl?: string // the app's gateway for this turn: the only tools the CLI gets, besides the web ones
web?: boolean // the CLI's own web search and page reading
+ account?: string // the folder of another login of this harness (Settings › Accounts); unset: its usual one
}
// An image file, shown to the model right after block `block` (the message it came with).
diff --git a/src/core/index.ts b/src/core/index.ts
index 8299a62..87831cd 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -2,14 +2,14 @@
// live here so the window never waits on agent work. The renderer talks to it
// over a MessagePort handed out by the main process.
import { execFile, spawn } from 'node:child_process'
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { userInfo } from 'node:os'
import { join } from 'node:path'
import { randomUUID } from 'node:crypto'
import type { MessagePortMain } from 'electron'
import { L, langOf, locale, setLang, type Lang } from '../shared/lang'
import type { Api, CoreEvent, Method, Request, Wire } from '../shared/rpc'
-import { channelName, ENGINES, inQuietHours, modelInfo, rememberModels, WEBHOOK_PORT, type Agent, type BrowserReply, type Message, type EngineId, type EngineStatus, type Settings } from '../shared/types'
+import { channelName, ENGINES, inQuietHours, modelInfo, rememberModels, WEBHOOK_PORT, type Account, type AccountEngine, type Agent, type BrowserReply, type Message, type EngineId, type EngineStatus, type Settings } from '../shared/types'
import { listModels, quietClaude, quietCodex, withChoice } from './harness'
import { Db } from './db'
import { claudeEngine, userProvider } from './engines/claude'
@@ -17,7 +17,7 @@ import { codexEngine, userCodexProvider } from './engines/codex'
import { opencodeEngine } from './engines/opencode'
import { piEngine } from './engines/pi'
import { geminiAppDir, geminiEngine } from './engines/gemini'
-import { adoptLoginShellPath, detectEngines, type CodexModel } from './engines/detect'
+import { accountDir, accountStatus, adoptLoginShellPath, detectEngines, type CodexModel } from './engines/detect'
import { fakeEngine } from './engines/fake'
import { DesktopApps, macApps, SELF } from './apps'
import { linuxApps, windowsApps, type SystemApp } from './apps-os'
@@ -92,10 +92,29 @@ async function detect(): Promise<void> {
engines = { claude: fakeStatus('0.0.0'), codex: fakeStatus('0.0.0'), opencode: { ...fakeStatus('0.0.0'), route: 'providers', account: 'OpenAI, OpenCode · 3 modelos' }, pi: { installed: false, loggedIn: false }, gemini: { installed: false, loggedIn: false } }
listed = { opencode: ['openai/gpt-5.5', 'opencode/big-pickle', 'opencode-go/qwen3.8-max'] }
} else ({ engines, listed, codexCatalog } = await detectEngines(codexHome))
+ await checkAccounts()
rememberModels(codexCatalog.map((m) => ({ id: m.slug, engine: 'codex', label: m.label, hint: m.description ?? '' })))
gatewayLists.clear()
emit({ type: 'settings', settings: settings() })
}
+// The harness's own sign-in, in a terminal, with the variables that say which login it is.
+function openLogin(engine: EngineId, vars: Record<string, string>): { opened: boolean; command: string } {
+ const bin = engines[engine].path ?? ENGINES[engine].cli
+ const sub = ENGINES[engine].login.split(' ').slice(1).join(' ')
+ if (isWin) {
+ // A new console window running a small script, its paths in the environment.
+ openWindowsConsole(join(dataDir, 'login.cmd'), [`call "%TUCANO_CLI%" ${sub}`], { TUCANO_CLI: bin, ...vars })
+ return { opened: true, command: `"${bin}" ${sub}` }
+ }
+ const q = (s: string): string => `'${s.replace(/'/g, `'\\''`)}'`
+ const cmd = [...Object.entries(vars).map(([k, v]) => `${k}=${q(v)}`), q(bin), sub].filter(Boolean).join(' ')
+ if (fake) return { opened: true, command: cmd } // test engines: nothing to sign into
+ const term = terminalCommand(cmd, osOf(), onPath)
+ // Its own process, so the terminal outlives the app if the person quits it mid-login.
+ if (term) spawn(term.bin, term.args, { detached: true, stdio: 'ignore' }).on('error', () => {}).unref()
+ return { opened: !!term, command: cmd }
+}
+
// After a sign-in or an install in a terminal, the harness is checked again every few
// seconds until it shows up (for 10 minutes at most): it appears with no "Check again".
let watching: ReturnType<typeof setInterval> | undefined
@@ -115,7 +134,33 @@ 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() }
+ 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) })) }
+}
+
+// More logins of Claude Code and Codex (Settings › Accounts): each in its own folder, checked with
+// the CLI's own status when the harnesses are, and every few seconds after a sign-in.
+const accountLogins = new Map<string, { loggedIn: boolean; detail?: string }>()
+const savedAccounts = (): Account[] => (db.getSettings(DEFAULTS).accounts ?? []).map(({ id, engine, name }) => ({ id, engine, name }))
+async function checkAccounts(only?: string): Promise<void> {
+ await Promise.all(
+ savedAccounts()
+ .filter((a) => !only || a.id === only)
+ .map(async (a) => {
+ const bin = engines[a.engine].path
+ if (fake) accountLogins.set(a.id, { loggedIn: true, detail: L('Motor de teste', 'Test engine') })
+ else accountLogins.set(a.id, bin ? await accountStatus(a.engine, bin, accountDir(dataDir, a.id)) : { loggedIn: false })
+ })
+ )
+}
+let watchingAccount: NodeJS.Timeout | null = null
+function watchAccount(id: string): void {
+ if (watchingAccount) clearInterval(watchingAccount)
+ const until = Date.now() + 10 * 60_000
+ watchingAccount = setInterval(() => {
+ if (accountLogins.get(id)?.loggedIn || Date.now() > until || !savedAccounts().some((a) => a.id === id)) return void clearInterval(watchingAccount!)
+ void checkAccounts(id).then(() => emit({ type: 'settings', settings: settings() }))
+ }, 4_000)
+ watchingAccount.unref()
}
// github is made further down; settings can be asked for before.
const githubInfo = (): Settings['github'] => githubRef?.info()
@@ -772,7 +817,7 @@ const api: Api = {
return { ok: true, message: L(`${m.id} respondeu em ${secs} s: “${text.trim().slice(0, 60)}”`, `${m.id} answered in ${secs} s: “${text.trim().slice(0, 60)}”`) }
},
- updateSettings: ({ patch: { jevKey: _computed, telegram: _phone, ...patch } }) => {
+ updateSettings: ({ patch: { jevKey: _computed, telegram: _phone, accounts: _own, ...patch } }) => {
db.setSettings(patch)
if (patch.paused !== undefined) runner.setPaused(patch.paused)
if (patch.openAtLogin !== undefined) toMain({ type: 'login_item', open: patch.openAtLogin })
@@ -861,21 +906,38 @@ const api: Api = {
// Login always happens in the CLI's own flow; the app never sees credentials.
// Codex logs into the app's own home (see codexEnv), separate from the user's.
loginEngine: ({ engine }) => {
- const bin = engines[engine].path ?? ENGINES[engine].cli
- const sub = ENGINES[engine].login.split(' ').slice(1).join(' ')
// The sign-in happens in a terminal: check again until it lands, wherever the person is.
watchEngine(engine, (s) => s.loggedIn)
- if (isWin) {
- // A new console window running a small script, its paths in the environment.
- openWindowsConsole(join(dataDir, 'login.cmd'), [`call "%TUCANO_CLI%" ${sub}`], { TUCANO_CLI: bin, ...(engine === 'codex' ? { HOME: codexHome, CODEX_HOME: join(codexHome, '.codex') } : {}) })
- return { opened: true, command: `"${bin}" ${sub}` }
+ return openLogin(engine, engine === 'codex' ? { HOME: codexHome, CODEX_HOME: join(codexHome, '.codex') } : {})
+ },
+
+ // Another login of Claude Code or Codex: a folder of its own, signed into in a terminal like the first.
+ addAccount: ({ engine, name }) => {
+ const account: Account = { id: randomUUID().slice(0, 8), engine, name: name.trim() || ENGINES[engine].label }
+ mkdirSync(join(accountDir(dataDir, account.id), '.codex'), { recursive: true })
+ db.setSettings({ accounts: [...savedAccounts(), account] })
+ void checkAccounts(account.id).then(() => emit({ type: 'settings', settings: settings() }))
+ emit({ type: 'settings', settings: settings() })
+ return account
+ },
+ loginAccount: ({ id }) => {
+ const a = savedAccounts().find((x) => x.id === id)
+ if (!a) return { opened: false, command: '' }
+ const dir = accountDir(dataDir, a.id)
+ watchAccount(a.id)
+ return openLogin(a.engine, a.engine === 'claude' ? { CLAUDE_CONFIG_DIR: dir } : { HOME: dir, CODEX_HOME: join(dir, '.codex') })
+ },
+ // Its agents go back to the harness's usual login; the folder, with the login in it, goes away.
+ removeAccount: ({ id }) => {
+ db.setSettings({ accounts: savedAccounts().filter((a) => a.id !== id) })
+ accountLogins.delete(id)
+ for (const agent of db.agents().filter((x) => x.accountId === id)) {
+ const { accountId: _gone, ...rest } = agent
+ db.saveAgent(rest)
+ emit({ type: 'agent', agent: db.agent(agent.id)! })
}
- const q = (s: string): string => `'${s.replace(/'/g, `'\\''`)}'`
- const cmd = engine === 'codex' ? `HOME=${q(codexHome)} CODEX_HOME=${q(join(codexHome, '.codex'))} ${q(bin)} ${sub}` : `${q(bin)} ${sub}`
- const term = terminalCommand(cmd, osOf(), onPath)
- // Its own process, so the terminal outlives the app if the person quits it mid-login.
- if (term) spawn(term.bin, term.args, { detached: true, stdio: 'ignore' }).on('error', () => {}).unref()
- return { opened: !!term, command: cmd }
+ rmSync(accountDir(dataDir, id), { recursive: true, force: true })
+ emit({ type: 'settings', settings: settings() })
},
// The harness's own installer, in a terminal the person sees: its progress, its
diff --git a/src/core/runs.ts b/src/core/runs.ts
index cee9102..b641ba3 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -16,6 +16,7 @@ import { LER_SKILL, PROPOR_SKILL, SKILL_TOOL_NAMES, type Skills } from './skills
import { availableModels, builderSection, draftFrom, PROPOR_AGENTE } from './tuca'
import type { Db } from './db'
import type { Engine, TurnImage } from './engines/types'
+import { accountDir } from './engines/detect'
import { outOfQuota } from './engines/cli'
import { textResult, type Gateway, type ToolDef } from './gateway'
import { JEV_MODEL, routeJev } from './jev'
@@ -477,8 +478,25 @@ export class Runner {
return msg
}
+ // Another login of this harness (Settings › Accounts), when the agent has one.
+ let account = agent.accountId ? settings.accounts?.find((a) => a.id === agent.accountId && a.engine === engineId) : undefined
+ if (account && !account.loggedIn) {
+ save({
+ run: {
+ status: 'failed',
+ depth: opts.depth,
+ steps: [],
+ ...again,
+ error: L(
+ `A conta “${account.name}” do ${ENGINES[engineId].label} não está logada. Entre nela em Configurações › Modelos › Contas e mande de novo.`,
+ `The “${account.name}” ${ENGINES[engineId].label} account isn't signed in. Sign in under Settings › Models › Accounts and send it again.`
+ )
+ }
+ })
+ return msg
+ }
const status = settings.engines[engineId]
- if (!status.installed || !status.loggedIn) {
+ if (!status.installed || (!status.loggedIn && !account)) {
save({
run: {
status: 'failed',
@@ -1092,7 +1110,8 @@ export class Runner {
cwd,
signal: control.ctl.signal,
mcpUrl: session?.url,
- web: agent.web !== false
+ web: agent.web !== false,
+ account: account && this.deps.dataDir ? accountDir(this.deps.dataDir, account.id) : undefined
})
for await (const ev of events) {
sign()
@@ -1110,7 +1129,7 @@ export class Runner {
if (counted > budget * BUDGET_OVERRUN) halt('budget')
}
} else if (ev.type === 'quota') {
- this.deps.onQuota?.(ev.quota)
+ if (!account) this.deps.onQuota?.(ev.quota) // the windows shown are the usual login's
} else if (ev.type === 'web') {
// Not through the gateway, so it can't be refused or warned: the same search over and over is a loop.
acted = true
@@ -1136,6 +1155,7 @@ export class Runner {
modelName = reserve.id
engineId = reserve.engine
engineLabel = `${ENGINES[engineId].label} · ${reserve.label}`
+ account = undefined // the agent's account is a login of its main harness; the reserve runs on its harness's usual one
addSteps({ id: randomUUID(), label: L('Foi pro modelo reserva', 'Moved to the reserve model'), detail: L(`${from} está sem limite agora; segue no ${engineLabel}`, `${from} is out of quota for now; going on with ${engineLabel}`), status: 'done' })
error = null
progress = { tokens: 0, cacheRead: 0 }
diff --git a/src/renderer/src/components/Harness.tsx b/src/renderer/src/components/Harness.tsx
index f44d442..8103a37 100644
--- a/src/renderer/src/components/Harness.tsx
+++ b/src/renderer/src/components/Harness.tsx
@@ -5,8 +5,12 @@
import { L } from '../../../shared/lang'
import { useEffect, useState, type ReactNode } from 'react'
import {
+ ACCOUNT_ENGINES,
+ addAccount,
ENGINES,
ENGINE_IDS,
+ loginAccount,
+ removeAccount,
MODELS,
startsPicked,
codexValue,
@@ -22,6 +26,9 @@ import {
testEngine,
updateSettings,
useStore,
+ type Account,
+ type AccountEngine,
+ type Agent,
type EngineId,
type EngineStatus,
type HarnessMcp,
@@ -365,3 +372,93 @@ export function HarnessMcps({ onAdded }: { onAdded: (id: string) => void }): Rea
</section>
)
}
+
+// More logins of Claude Code and Codex: a work account beside a personal one. Each lives in a
+// folder of its own and is signed into through the CLI, in a terminal; an agent picks one on its page.
+export function AccountsCard(): ReactNode {
+ const accounts = useStore((s) => s.settings.accounts ?? [])
+ const engines = useStore((s) => s.settings.engines)
+ const [engine, setEngine] = useState<AccountEngine>('claude')
+ const [name, setName] = useState('')
+ const [manual, setManual] = useState<Record<string, string>>({})
+ const [removing, setRemoving] = useState<string | null>(null)
+ const add = async (): Promise<void> => {
+ const a = await addAccount(engine, name)
+ setName('')
+ const r = await loginAccount(a.id)
+ if (!r.opened) setManual((m) => ({ ...m, [a.id]: r.command }))
+ }
+ return (
+ <div className="accounts">
+ {accounts.map((a: Account) => (
+ <div key={a.id} className="key-row">
+ <Icon name="user" />
+ <div className="grow">
+ <strong>{a.name}</strong>
+ <p className="muted small">
+ {ENGINES[a.engine].label} · {a.loggedIn ? (a.detail ?? L('Pronta', 'Ready')) : L('Falta entrar', 'Not signed in')}
+ </p>
+ {manual[a.id] && !a.loggedIn && (
+ <>
+ <span className="hint">{L('Não achei um terminal pra abrir. Pra entrar, cole no seu terminal:', "Couldn't find a terminal to open. To sign in, paste in your terminal:")}</span>
+ <code className="harness__cmd">{manual[a.id]}</code>
+ </>
+ )}
+ </div>
+ {!a.loggedIn && (
+ <button className="btn btn--sm btn--primary" onClick={() => void loginAccount(a.id).then((r) => setManual((m) => ({ ...m, [a.id]: r.opened ? '' : r.command })))}>
+ {L('Entrar', 'Sign in')}
+ </button>
+ )}
+ {removing === a.id ? (
+ <button className="btn btn--sm btn--danger" onClick={() => void removeAccount(a.id).then(() => setRemoving(null))}>
+ {L('Remover mesmo', 'Remove it')}
+ </button>
+ ) : (
+ <button className="btn btn--ghost btn--sm" onClick={() => setRemoving(a.id)}>
+ {L('Remover', 'Remove')}
+ </button>
+ )}
+ </div>
+ ))}
+ <div className="row row--center accounts__add">
+ <select value={engine} onChange={(e) => setEngine(e.target.value as AccountEngine)}>
+ {ACCOUNT_ENGINES.filter((e) => engines[e].installed).map((e) => (
+ <option key={e} value={e}>
+ {ENGINES[e].label}
+ </option>
+ ))}
+ </select>
+ <input className="grow" placeholder={L('Nome da conta (ex.: Trabalho)', 'Account name (e.g. Work)')} value={name} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && void add()} />
+ <button className="btn btn--sm" disabled={!engines[engine].installed} onClick={() => void add()}>
+ {L('Adicionar e entrar', 'Add and sign in')}
+ </button>
+ </div>
+ {removing && <p className="hint hint--warn">{L('Os agentes dessa conta voltam pro login de sempre do harness, e o login dela sai deste computador.', 'Its agents go back to the harness’s usual login, and its sign-in leaves this computer.')}</p>}
+ </div>
+ )
+}
+
+// Which login of its harness an agent runs on: the usual one, or one of the accounts added in Settings.
+export function AccountPicker({ draft, patch }: { draft: Agent; patch: (p: Partial<Agent>) => void }): ReactNode {
+ const engine = modelInfo(draft.modelId)?.engine
+ const accounts = useStore((s) => (s.settings.accounts ?? []).filter((a) => a.engine === engine))
+ if (!accounts.length || !engine) return null
+ const value = accounts.some((a) => a.id === draft.accountId) ? draft.accountId! : ''
+ const chosen = accounts.find((a) => a.id === value)
+ return (
+ <label className="field">
+ <span className="field__label">{L('Conta', 'Account')}</span>
+ <select value={value} onChange={(e) => patch({ accountId: e.target.value || undefined })}>
+ <option value="">{L(`A de sempre do ${ENGINES[engine].label}`, `${ENGINES[engine].label}’s usual one`)}</option>
+ {accounts.map((a) => (
+ <option key={a.id} value={a.id}>
+ {a.name}
+ {a.loggedIn ? '' : L(' (falta entrar)', ' (not signed in)')}
+ </option>
+ ))}
+ </select>
+ {chosen && !chosen.loggedIn && <span className="hint hint--warn">{L('Essa conta ainda não entrou: o agente não responde até você entrar nela em Configurações › Modelos.', 'This account isn’t signed in yet: the agent won’t reply until you sign in under Settings › Models.')}</span>}
+ </label>
+ )
+}
diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsx
index 59c5f26..4c4133e 100644
--- a/src/renderer/src/components/Pages.tsx
+++ b/src/renderer/src/components/Pages.tsx
@@ -56,7 +56,7 @@ import {
isTeam,
reachable
} from '../store'
-import { HarnessList, HarnessMcps, ModelPicker, onGateway, OutsideGateway, usableEngines } from './Harness'
+import { AccountPicker, AccountsCard, HarnessList, HarnessMcps, ModelPicker, onGateway, OutsideGateway, usableEngines } from './Harness'
import { AppsCard } from './Apps'
import { ApprovalCard } from './Conversation'
import { AgentAvatar, Icon, NumberInput, SleepingToucan, time, tokens, UsageBar } from './ui'
@@ -524,8 +524,9 @@ export function AgentPage({ id, draft: proposed, fromMessage }: { id?: string; d
{pane('perfil') && (
<Card title={L('Harness e modelo', 'Harness and model')} lead={L('O agente roda num dos harnesses que você usa, como você o configurou: no seu plano, no gateway da empresa ou no seu provedor.', 'The agent runs on one of the harnesses you use, the way you set it up: on your plan, your company’s gateway or your provider.')}>
<ModelPicker value={draft.modelId} onChange={(modelId) => patch({ modelId })} />
+ <AccountPicker draft={draft} patch={patch} />
<ReserveModel draft={draft} patch={patch} />
- {!engineStatus.loggedIn && (
+ {!engineStatus.loggedIn && !draft.accountId && (
<p className="hint hint--warn">
<Icon name="lock" size={13} />{' '}
{L(
@@ -1582,6 +1583,18 @@ export function SettingsPage(): ReactNode {
</Card>
)}
+ {pane('modelos') && (
+ <Card
+ title={L('Contas', 'Accounts')}
+ lead={L(
+ 'Mais de um login do Claude Code ou do Codex, como a conta do trabalho e a pessoal. Cada agente escolhe a conta na página dele. O login acontece no próprio CLI: o Tucano não vê nem guarda a senha.',
+ 'More than one Claude Code or Codex login, like a work account and a personal one. Each agent picks its account on its page. You sign in through the CLI itself: Tucano never sees or stores the password.'
+ )}
+ >
+ <AccountsCard />
+ </Card>
+ )}
+
{pane('modelos') && (
<Card title="Router" lead={L('Modelo pequeno que lê a conversa e decide quem responde. Não concede permissão nenhuma.', 'A small model that reads the conversation and decides who replies. It grants no permissions at all.')}>
<Field label={L('Modelo do router', 'Router model')} hint={L('Prefira um modelo rápido: ele roda antes de cada resposta num canal.', 'Go for a fast model: it runs before every reply in a channel.')}>
diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.ts
index 8fe9acb..7a7867f 100644
--- a/src/renderer/src/store.ts
+++ b/src/renderer/src/store.ts
@@ -4,6 +4,8 @@ import { useRef, useSyncExternalStore } from 'react'
import { L, setLang } from '../../shared/lang'
import type { CoreEvent } from '../../shared/rpc'
import {
+ type Account,
+ type AccountEngine,
MODELS,
modelInfo,
type EngineId,
@@ -326,6 +328,10 @@ export function updateSettings(patch: Partial<Omit<Settings, 'engines'>>): void
export const refreshEngines = (): void => void call('refreshEngines')
export const loginEngine = (engine: keyof Settings['engines']): Promise<{ opened: boolean; command: string }> => call('loginEngine', { engine })
+// More logins of Claude Code and Codex, each signed into in a terminal.
+export const addAccount = (engine: AccountEngine, name: string): Promise<Account> => call('addAccount', { engine, name })
+export const loginAccount = (id: string): Promise<{ opened: boolean; command: string }> => call('loginAccount', { id })
+export const removeAccount = (id: string): Promise<void> => call('removeAccount', { id })
export const installEngine = (engine: keyof Settings['engines']): Promise<{ opened: boolean; command: string; needsNode?: boolean }> => call('installEngine', { engine })
// The person's own apps, through agent-desktop.
export const desktopStatus = (): Promise<{ installed: boolean; version?: string; accessibility?: string; suggestion?: string; server?: boolean }> => call('desktopStatus')
diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.css
index 5552197..b4a1817 100644
--- a/src/renderer/src/styles.css
+++ b/src/renderer/src/styles.css
@@ -3921,6 +3921,23 @@ table.csv th {
font-size: 13px;
line-height: 1.5;
}
+/* More logins of a harness, in Settings › Models. */
+.accounts {
+ display: grid;
+ gap: 4px;
+}
+.accounts__add {
+ margin-top: 8px;
+}
+.accounts__add select {
+ flex: 0 0 auto;
+ width: auto;
+}
+.accounts__add input {
+ flex: 1 1 200px;
+ min-width: 0;
+}
+
/* An agent's reserve model, under the main one. */
.reserve {
display: grid;
diff --git a/src/shared/rpc.ts b/src/shared/rpc.ts
index 8296f80..2e32eae 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, 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'
+import type { Os, Account, AccountEngine, 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
@@ -40,6 +40,9 @@ export interface Api {
updateSettings(p: { patch: Partial<Omit<Settings, 'engines'>> }): void
refreshEngines(): void
loginEngine(p: { engine: EngineId }): { opened: boolean; command: string } // not opened: no terminal to open, the person runs the command
+ addAccount(p: { engine: AccountEngine; name: string }): Account
+ loginAccount(p: { id: string }): { opened: boolean; command: string }
+ removeAccount(p: { id: string }): void
installEngine(p: { engine: EngineId }): { opened: boolean; command: string; needsNode?: boolean } // needsNode: an npm install with no npm here
desktopStatus(): Promise<{ installed: boolean; version?: string; accessibility?: string; suggestion?: string; server?: boolean }> // agent-desktop, for the person's apps
installedApps(): Promise<{ name: string; bundleId?: string; path?: string; icon?: string }[]> // the person's installed apps (a Mac's), kept on disk
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 4bf6626..59157a4 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -60,6 +60,7 @@ export interface Agent {
// Where a reply goes when modelId's subscription is out (its 5-hour or weekly limit, a 429): tried
// only when the main model failed before doing anything, and the next reply tries the main one again.
fallbackModelId?: string
+ accountId?: string // one of settings.accounts, for its harness; unset: the harness's own login
effort: Effort
limit: number // tokens per month
used: number // tokens used this month, computed from receipts
@@ -213,6 +214,7 @@ export interface Settings {
onboarding?: { done: boolean; checklistHidden?: boolean }
folded?: string[] // the ids of what I folded in the sidebar
sounds?: boolean // the toucan's chirp on a notification; unset: on
+ accounts?: Account[] // more logins of Claude Code or Codex, beside the one each already has
}
// Which chirp a notification plays: a knock when an agent needs me, two notes when the work
@@ -223,6 +225,19 @@ export function chirpOf(kind: 'approval' | 'question' | 'done' | undefined, soun
return kind === 'approval' || kind === 'question' ? 'chama' : 'pronto'
}
+// Another login of a harness (a work account beside a personal one), in a folder of its own
+// in the app's data: Claude Code's CLAUDE_CONFIG_DIR (with its own Keychain entry), Codex's
+// CODEX_HOME. The person signs in through the CLI itself; the app never sees the credentials.
+export const ACCOUNT_ENGINES = ['claude', 'codex'] as const satisfies readonly EngineId[]
+export type AccountEngine = (typeof ACCOUNT_ENGINES)[number]
+export interface Account {
+ id: string
+ engine: AccountEngine
+ name: string // what the person calls it ("Trabalho")
+ loggedIn?: boolean // computed, from the CLI's own status
+ detail?: string // computed: the plan it's on, as the CLI says
+}
+
// 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' | 'input'
diff --git a/test/accounts.test.ts b/test/accounts.test.ts
new file mode 100644
index 0000000..d1e797e
--- /dev/null
+++ b/test/accounts.test.ts
@@ -0,0 +1,102 @@
+import { mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { beforeEach, describe, expect, it } from 'vitest'
+import type { Account, Agent, EngineId, Message, Settings } from '../src/shared/types'
+import { Db } from '../src/core/db'
+import { accountDir, accountLogin } from '../src/core/engines/detect'
+import { claudeEngine } from '../src/core/engines/claude'
+import { fakeEngine } from '../src/core/engines/fake'
+import type { Engine, Turn } from '../src/core/engines/types'
+import { Runner } from '../src/core/runs'
+
+const ready = { installed: true, loggedIn: true }
+const agent = (extra: Partial<Agent> = {}): Agent => ({ id: 'a1', name: 'lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false, ...extra })
+const counted = (engine: Engine): Engine & { turns: Turn[] } => {
+ const turns: Turn[] = []
+ return { id: engine.id, turns, run: (t) => (turns.push(t), engine.run(t)) }
+}
+
+let db: Db
+let data: string
+let settings: Settings
+let claude: ReturnType<typeof counted>
+const work: Account = { id: 'w1', engine: 'claude', name: 'Trabalho', loggedIn: true }
+
+function runner(): Runner {
+ claude = counted(fakeEngine('claude', { delayMs: 1 }))
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini') }
+ return new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-work-')), dataDir: data })
+}
+const reply = (): Message => db.messages().find((m) => m.author.kind === 'agent')!
+
+beforeEach(() => {
+ data = mkdtempSync(join(tmpdir(), 'ad-data-'))
+ db = new Db(join(data, 'test.db'))
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt', accounts: [work] }
+ db.saveAgent(agent({ accountId: 'w1' }))
+ db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
+})
+
+describe('accounts', () => {
+ it('keeps the agent’s account, and clears it', () => {
+ expect(db.agent('a1')!.accountId).toBe('w1')
+ db.saveAgent(agent())
+ expect(db.agent('a1')!.accountId).toBeUndefined()
+ })
+
+ it('runs the agent on its account’s folder, even with the usual login signed out', async () => {
+ settings = { ...settings, engines: { ...settings.engines, claude: { installed: true, loggedIn: false } } }
+ const r = runner()
+ await r.send('d1', 'oi')
+ await r.idle()
+ expect(reply().run?.status).toBe('done')
+ expect(claude.turns[0]!.account).toBe(accountDir(data, 'w1'))
+ })
+
+ it('runs on the usual login without an account, or with one of another harness', async () => {
+ db.saveAgent(agent({ accountId: undefined }))
+ let r = runner()
+ await r.send('d1', 'oi')
+ await r.idle()
+ expect(claude.turns[0]!.account).toBeUndefined()
+
+ settings = { ...settings, accounts: [{ ...work, engine: 'codex' }] }
+ db.saveAgent(agent({ accountId: 'w1' }))
+ r = runner()
+ await r.send('d1', 'de novo')
+ await r.idle()
+ expect(claude.turns[0]!.account).toBeUndefined()
+ })
+
+ it('says so, without starting the CLI, when the account isn’t signed in', async () => {
+ settings = { ...settings, accounts: [{ ...work, loggedIn: false }] }
+ const r = runner()
+ await r.send('d1', 'oi')
+ await r.idle()
+ expect(reply().run?.status).toBe('failed')
+ expect(reply().run?.error).toContain('Trabalho')
+ expect(claude.turns).toHaveLength(0)
+ })
+
+ it('reads the CLIs’ own status for an account', () => {
+ expect(accountLogin('claude', { code: 1, stdout: '{"loggedIn": false, "authMethod": "none"}', stderr: '' })).toEqual({ loggedIn: false })
+ expect(accountLogin('claude', { code: 0, stdout: '{"loggedIn": true, "authMethod": "claude.ai", "subscriptionType": "max", "email": "[email protected]"}', stderr: '' })).toEqual({ loggedIn: true, detail: 'Plano Claude Max · [email protected]' })
+ expect(accountLogin('codex', { code: 0, stdout: 'Logged in using ChatGPT', stderr: '' })).toEqual({ loggedIn: true, detail: 'Plano ChatGPT' })
+ expect(accountLogin('codex', { code: 1, stdout: 'Not logged in', stderr: '' })).toEqual({ loggedIn: false })
+ })
+
+ // The stand-in CLI is a shell script, which Windows can't run.
+ it.skipIf(process.platform === 'win32')('points Claude Code at the account’s folder', async () => {
+ // A stand-in CLI that prints the folder it was given, as a result line.
+ const dir = mkdtempSync(join(tmpdir(), 'ad-bin-'))
+ const bin = join(dir, 'claude')
+ const { writeFileSync, chmodSync } = await import('node:fs')
+ writeFileSync(bin, '#!/bin/sh\ncat >/dev/null\necho "{\\"type\\":\\"result\\",\\"subtype\\":\\"success\\",\\"result\\":\\"$CLAUDE_CONFIG_DIR\\",\\"usage\\":{}}"\n')
+ chmodSync(bin, 0o755)
+ const turn = { model: 'sonnet', effort: 'low' as const, system: '', prompt: 'oi', cwd: dir, signal: new AbortController().signal, account: '/contas/w1' }
+ const texts: string[] = []
+ for await (const ev of claudeEngine(() => bin, async () => ({ env: {} })).run(turn)) if (ev.type === 'done') texts.push(ev.text)
+ expect(texts).toEqual(['/contas/w1'])
+ })
+})