Skip to content
Merged
43 changes: 43 additions & 0 deletions src/cli/handlers/account.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,49 @@ describe('account CLI handlers', () => {
expect(logSpy).not.toHaveBeenCalled()
})

it.each(['claude', 'codex'])(
'rejects OpenCode login flags for %s before login',
async (agent) => {
await expect(
ACCOUNT_HANDLERS['account add']({
...context(agent),
flags: new Map([
['agent', agent],
['method', 'device']
])
})
).rejects.toThrow('only supported with --agent opencode')
expect(callMock).not.toHaveBeenCalled()
expect(spawnMock).not.toHaveBeenCalled()
}
)

it('keeps OpenCode form answer values out of the login failure message', async () => {
callMock.mockResolvedValue({
id: 'test',
ok: true,
result: { capabilities: [DATA_ACCOUNT_RUNTIME_CAPABILITY] },
_meta: { runtimeId: 'test-runtime' }
})
resolveCliCommandMock.mockImplementation((command: string) => `/tools/${command}`)
spawnProcessMock.mockImplementation(() => helpChild('--standalone'))
spawnMock.mockImplementation(() => {
const child = new EventEmitter()
queueMicrotask(() => child.emit('exit', 1))
return child
})
const failure = ACCOUNT_HANDLERS['account add']({
...context('opencode'),
flags: new Map([
['agent', 'opencode'],
['answer', 'token=secret-value']
])
})
await expect(failure).rejects.toThrow('--answer token=<redacted> --standalone')
await expect(failure).rejects.not.toThrow('secret-value')
expect(spawnMock.mock.calls[0][1]).toContain('token=secret-value')
})

it('rejects `--agent` with no value instead of defaulting to Claude', async () => {
await expect(
ACCOUNT_HANDLERS['account add']({ ...context('claude'), flags: new Map([['agent', true]]) })
Expand Down
11 changes: 9 additions & 2 deletions src/cli/handlers/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,13 @@ import {
withInteractiveLoginCleanup
} from './interactive-login-interruption'
import { getWslAccountTarget } from './account-wsl-location'
import { addDataAccount, listDataAccounts, mutateDataAccount } from './data-account-commands'
import {
addDataAccount,
listDataAccounts,
mutateDataAccount,
redactLoginAnswers,
rejectOpenCodeLoginFlagsForAgent
} from './data-account-commands'
import { formatAccountsBlock, formatDataAccounts } from './account-list-format'
import { resolveOpenCodeLoginCommand } from './opencode-account-login-command'

Expand Down Expand Up @@ -140,7 +146,7 @@ async function runAgentLoginInTerminal(
rejectPromise(
new RuntimeClientError(
'internal',
`\`${command} ${args.join(' ')}\` exited with code ${code ?? 'null'}.`
`\`${[command, ...redactLoginAnswers(args)].join(' ')}\` exited with code ${code ?? 'null'}.`
)
)
})
Expand Down Expand Up @@ -268,6 +274,7 @@ export const ACCOUNT_HANDLERS: Record<string, CommandHandler> = {
)
}
rejectAccountRemoteSelectionFlags(ctx, 'orca account add')
rejectOpenCodeLoginFlagsForAgent(ctx, agent)
if (agent === 'opencode' || agent === 'devin') {
await addDataAccount(ctx, agent, runAgentLoginInTerminal)
return
Expand Down
62 changes: 62 additions & 0 deletions src/cli/handlers/data-account-commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { tmpdir } from 'node:os'
import { parseArgs, REPEATED_FLAG_SEPARATOR, specPaths } from '../args'
import { ACCOUNT_COMMAND_SPECS } from '../specs/account'
import { RuntimeClient } from '../runtime-client'
import { DATA_ACCOUNT_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities'
import { addDataAccount, listDataAccounts } from './data-account-commands'
Expand Down Expand Up @@ -82,4 +84,64 @@ describe('managed data account enrollment', () => {
})
expect(existsSync(directory)).toBe(false)
})

it('passes OpenCode login method and answers before the standalone flag', async () => {
vi.spyOn(client, 'call')
.mockResolvedValueOnce({
id: 'test',
ok: true,
result: { capabilities: [DATA_ACCOUNT_RUNTIME_CAPABILITY] },
_meta: { runtimeId: 'test' }
})
.mockRejectedValueOnce(new Error('capture failed'))
const login = vi.fn(async (_command: string, args: string[]) => {
expect(args).toEqual([
'auth',
'login',
'github-copilot',
'--method',
'device',
'--answer',
'deployment=github.com',
'--answer',
'note=a=b',
'--standalone'
])
})
const flags = new Map<string, string | boolean>([
['integration', 'github-copilot'],
['method', 'device'],
['answer', ['deployment=github.com', 'note=a=b'].join(REPEATED_FLAG_SEPARATOR)]
])
await expect(addDataAccount({ ...context, flags }, 'opencode', login)).rejects.toThrow(
'capture failed'
)
expect(login).toHaveBeenCalledOnce()
})

it.each([
['devin', new Map([['method', 'device']]), 'only supported with --agent opencode'],
['opencode', new Map([['method', ' ']]), '--method requires'],
['opencode', new Map([['answer', 'deployment']]), 'key=value'],
['opencode', new Map([['answer', '=github.com']]), 'key=value'],
[
'opencode',
parseArgs(
['account', 'add', '--answer=', '--answer', 'deployment=github.com'],
ACCOUNT_COMMAND_SPECS.flatMap(specPaths),
ACCOUNT_COMMAND_SPECS
).flags,
'key=value'
]
] as const)('refuses invalid %s login options before login', async (provider, flags, message) => {
vi.spyOn(client, 'call').mockResolvedValue({
id: 'test',
ok: true,
result: { capabilities: [DATA_ACCOUNT_RUNTIME_CAPABILITY] },
_meta: { runtimeId: 'test' }
})
const login = vi.fn()
await expect(addDataAccount({ ...context, flags }, provider, login)).rejects.toThrow(message)
expect(login).not.toHaveBeenCalled()
})
})
43 changes: 43 additions & 0 deletions src/cli/handlers/data-account-commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { HandlerContext } from '../dispatch'
import { REPEATED_FLAG_SEPARATOR } from '../args'
import { printResult } from '../format'
import { RuntimeClientError } from '../runtime-client'
import { DATA_ACCOUNT_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities'
Expand Down Expand Up @@ -59,6 +60,7 @@ export async function addDataAccount(
'--integration requires an OpenCode integration ID or name.'
)
}
const loginOptions = readOpenCodeLoginOptions(ctx, provider)
const directory = mkdtempSync(join(tmpdir(), `orca-account-add-${provider}-`))
const session: InteractiveLoginSession = {
child: null,
Expand All @@ -79,6 +81,7 @@ export async function addDataAccount(
'auth',
'login',
...(typeof integration === 'string' ? [integration] : []),
...loginOptions,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
'--standalone'
]
: ['auth', 'login', '--force-manual-token-flow'],
Expand Down Expand Up @@ -109,6 +112,46 @@ export async function addDataAccount(
printResult(result, ctx.json, (state) => formatDataAccounts(provider, state))
}

// Form answers can hold secrets, so failure messages show only their keys.
export function redactLoginAnswers(args: string[]): string[] {
return args.map((arg, index) =>
args[index - 1] === '--answer' ? `${arg.slice(0, arg.indexOf('=') + 1)}<redacted>` : arg
)
}

export function rejectOpenCodeLoginFlagsForAgent(ctx: HandlerContext, agent: string): void {
if (agent !== 'opencode' && (ctx.flags.has('method') || ctx.flags.has('answer'))) {
throw new RuntimeClientError(
'invalid_argument',
'--method and --answer are only supported with --agent opencode.'
)
}
}

function readOpenCodeLoginOptions(
ctx: HandlerContext,
provider: ManagedDataAccountProvider
): string[] {
rejectOpenCodeLoginFlagsForAgent(ctx, provider)
const method = ctx.flags.get('method')
if (method !== undefined && (typeof method !== 'string' || !method.trim())) {
throw new RuntimeClientError(
'invalid_argument',
'--method requires an OpenCode login method ID.'
)
}
const answer = ctx.flags.get('answer')
// Split without dropping empty entries so `--answer=` is rejected instead of skipped.
const answers = typeof answer === 'string' ? answer.split(REPEATED_FLAG_SEPARATOR) : []
if (answer !== undefined && (answers.length === 0 || answers.some((a) => !/^[^=\s]+=/.test(a)))) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
throw new RuntimeClientError('invalid_argument', '--answer must be written as key=value.')
}
return [
...(typeof method === 'string' ? ['--method', method.trim()] : []),
...answers.flatMap((value) => ['--answer', value])
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
]
}

export async function listDataAccounts(ctx: HandlerContext, provider: unknown): Promise<void> {
if (provider !== 'opencode' && provider !== 'devin') {
throw new RuntimeClientError('invalid_argument', 'Use --agent opencode or --agent devin.')
Expand Down
12 changes: 9 additions & 3 deletions src/cli/specs/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,24 @@ export const ACCOUNT_COMMAND_SPECS: CommandSpec[] = [
path: ['account', 'add'],
summary: 'Add a managed agent account by signing in on this Orca host',
usage:
'orca account add [--agent claude|codex|opencode|devin] [--label <name>] [--integration <id>] [--json]',
allowedFlags: [...LOCAL_COMMAND_FLAGS, 'agent', 'label', 'integration'],
'orca account add [--agent claude|codex|opencode|devin] [--label <name>] [--integration <id>] [--method <id>] [--answer <key=value>]... [--json]',
allowedFlags: [...LOCAL_COMMAND_FLAGS, 'agent', 'label', 'integration', 'method', 'answer'],
repeatableFlags: ['answer'],
notes: [
'Runs the agent login (`claude login` / `codex login`) in this terminal, then registers the account with the local Orca runtime.',
'Codex uses device authorization so the browser can complete sign-in from a different machine.',
'OpenCode 2 uses `opencode auth login --standalone` in private XDG directories. Devin uses `devin auth login --force-manual-token-flow`.',
'Use --integration <id> to skip the OpenCode integration picker; --label names the saved OpenCode or Devin profile.',
'Use --method <id> and repeated --answer <key=value> to pass OpenCode its login method and form answers, so sign-in can finish without an interactive terminal.',
'OpenCode and Devin profiles apply to new explicit host agent launches. Direct SSH relay and Windows-hosted WSL selection are not supported; run the command on a headless Orca runtime on that host.',
'Sign in with the account you want to add (e.g. use a private/incognito browser window for a second account).',
'--agent defaults to claude. Requires the Orca runtime to be running on this machine.'
],
examples: ['orca account add', 'orca account add --agent codex']
examples: [
'orca account add',
'orca account add --agent codex',
'orca account add --agent opencode --integration github-copilot --method <id> --answer <key=value>'
]
},
{
path: ['account', 'list'],
Expand Down