Add --org flag to headless mode to allow org selection (#166)

* feat: select org

* feat: make it possible to use org by slug

* improv: clean up

* fix: types

* improv: comment

* fix: add discriminator

* improv: comment

* fix: types

* improv: clean up

* test: org flag

* improv: clean up

* fix: test

* improv: clean up

* Update src/shared-options.ts

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
This commit is contained in:
Tomasz Stefaniak 2025-08-08 12:50:54 -07:00 • committed by GitHub
parent ddffaf643a
commit a96170cef8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 494 additions and 19 deletions

View file

@ -7,6 +7,7 @@ import { env } from "./env.js";
export interface CommandLineArgs {
configPath?: string;
organizationSlug?: string; // Organization slug to use for this session
prompt?: string; // Optional prompt argument
resume?: boolean; // Resume from last session
readonly?: boolean; // Start in plan mode (backward compatibility)
@ -143,6 +144,14 @@ export function parseArgs(): CommandLineArgs {
result.configPath = args[configIndex + 1];
}
// Get organization slug from --org flag
const orgIndex = args.indexOf("--org");
if (orgIndex !== -1 && orgIndex + 1 < args.length) {
const orgValue = args[orgIndex + 1];
// Convert "personal" to undefined right away to simplify downstream logic
result.organizationSlug = orgValue.toLowerCase() === "personal" ? undefined : orgValue;
}
// Get rules from --rule flags (can be specified multiple times)
const ruleIndices: number[] = [];
for (let i = 0; i < args.length; i++) {
@ -161,7 +170,7 @@ export function parseArgs(): CommandLineArgs {
}
// Find the last argument that's not a flag or a flag value
const flagsWithValues = ["--config", "--rule", "--format"];
const flagsWithValues = ["--config", "--org", "--rule", "--format"];
const nonFlagArgs = args.filter((arg, index) => {
// Skip flags (starting with --)
if (arg.startsWith("--") || arg === "-p") return false;

199
src/auth/workos-org.test.ts Normal file
View file

@ -0,0 +1,199 @@
import chalk from "chalk";
import { describe, expect, test, beforeEach, vi } from "vitest";
import { getApiClient } from "../config.js";
import { ensureOrganization } from "./workos.js";
import type { AuthenticatedConfig, EnvironmentAuthConfig } from "./workos.js";
// Mock dependencies
vi.mock("../config.js", () => ({
getApiClient: vi.fn(() => ({
listOrganizations: vi.fn(),
})),
}));
vi.mock("fs", () => ({
default: {
existsSync: vi.fn(() => false),
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
unlinkSync: vi.fn(),
},
}));
describe("ensureOrganization with CLI organization slug", () => {
const mockAuthConfig: AuthenticatedConfig = {
userId: "user-123",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "refresh-token",
expiresAt: Date.now() + 3600000,
organizationId: null,
};
const mockEnvAuthConfig: EnvironmentAuthConfig = {
accessToken: "env-token",
organizationId: null,
};
const mockOrganizations = [
{ id: "org-1", name: "Organization One", slug: "org-one" },
{ id: "org-2", name: "Organization Two", slug: "org-two" },
{ id: "org-3", name: "Test Org", slug: "test-org" },
];
beforeEach(() => {
vi.clearAllMocks();
// Suppress console output during tests
vi.spyOn(console, "error").mockImplementation(() => {});
vi.spyOn(console, "info").mockImplementation(() => {});
});
describe("Organization resolution by slug", () => {
test("should resolve organization by exact slug match", async () => {
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const result = await ensureOrganization(mockAuthConfig, true, "org-one");
expect(result).toMatchObject({
organizationId: "org-1",
});
expect(apiClient.listOrganizations).toHaveBeenCalled();
});
test("should show available organizations when slug not found", async () => {
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const consoleInfoSpy = vi.spyOn(console, "info");
await expect(
ensureOrganization(mockAuthConfig, true, "invalid-org")
).rejects.toThrow('Organization "invalid-org" not found');
expect(consoleInfoSpy).toHaveBeenCalledWith(
chalk.yellow("Available organizations:"),
expect.stringContaining("personal")
);
});
});
describe("Mode restriction", () => {
test("should reject --org flag in interactive mode", async () => {
const consoleErrorSpy = vi.spyOn(console, "error");
const processExitSpy = vi
.spyOn(process, "exit")
.mockImplementation(() => {
throw new Error("Process exit");
});
await expect(
ensureOrganization(mockAuthConfig, false, "org-one")
).rejects.toThrow("Process exit");
expect(consoleErrorSpy).toHaveBeenCalledWith(
chalk.red(
"The --org flag is only supported in headless mode (with -p/--print flag)"
)
);
expect(processExitSpy).toHaveBeenCalledWith(1);
processExitSpy.mockRestore();
});
});
describe("Auth type handling", () => {
test("should work with authenticated config and return updated organizationId", async () => {
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const result = await ensureOrganization(mockAuthConfig, true, "test-org");
expect(result).toMatchObject({
userId: "user-123",
organizationId: "org-3",
});
});
test("should work with environment auth config and return updated organizationId", async () => {
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const result = await ensureOrganization(
mockEnvAuthConfig,
true,
"org-two"
);
expect(result).toMatchObject({
accessToken: "env-token",
organizationId: "org-2",
});
});
test("should override existing organization with CLI slug", async () => {
const authWithOrg = {
...mockAuthConfig,
organizationId: "existing-org",
};
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const result = await ensureOrganization(authWithOrg, true, "org-one");
expect(result).toMatchObject({
organizationId: "org-1",
});
});
test("should keep existing organization when no slug provided", async () => {
const authWithOrg = {
...mockAuthConfig,
organizationId: "existing-org",
};
const result = await ensureOrganization(authWithOrg, true);
expect(result).toMatchObject({
organizationId: "existing-org",
});
});
});
describe("Error handling", () => {
test("should handle API errors during organization fetch", async () => {
const apiClient = {
listOrganizations: vi.fn().mockRejectedValue(new Error("API Error")),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
await expect(
ensureOrganization(mockAuthConfig, true, "org-one")
).rejects.toThrow("API Error");
});
});
});

View file

@ -30,8 +30,15 @@ export interface AuthenticatedConfig {
// Represents configuration when using environment variable auth
export interface EnvironmentAuthConfig {
/**
* This userId?: undefined; field a trick to help TypeScript differentiate between
* AuthenticatedConfig and EnvironmentAuthConfig. Otherwise AuthenticatedConfig is
* a possible subtype of EnvironmentAuthConfig and TypeScript gets confused where
* type guards are involved.
*/
userId?: undefined;
accessToken: string;
organizationId: null; // Environment auth always uses personal organization
organizationId: string | null; // Can be set via --org flag in headless mode
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
modelName?: string; // Name of the selected model
}
@ -259,7 +266,11 @@ export function isAuthenticated(): boolean {
return true;
}
// Check if token is expired
/**
* THIS CODE DOESN'T WORK.
* .catch() will never return in a non-async function.
* It's a hallucination.
**/
if (Date.now() > config.expiresAt) {
// Try refreshing the token
refreshToken(config.refreshToken).catch(() => {
@ -525,15 +536,75 @@ export async function login(): Promise<AuthConfig> {
return authConfig;
}
/**
* Helper function to resolve organization by slug
*/
async function resolveOrganizationBySlug(
apiClient: ReturnType<typeof getApiClient>,
organizationSlug: string
): Promise<{ id: string; slug: string }> {
const resp = await apiClient.listOrganizations();
const organizations = resp.organizations;
// Find organization by slug (case-insensitive)
const matchedOrg = organizations.find(
(org) => org?.slug?.toLowerCase() === organizationSlug.toLowerCase()
);
if (matchedOrg) {
return { id: matchedOrg.id, slug: matchedOrg.slug };
} else {
// Organization not found - show available options
const availableSlugs = organizations
.map((org) => org?.slug)
.filter(Boolean);
const availableOptions = ["personal", ...availableSlugs];
console.info(
chalk.yellow("Available organizations:"),
availableOptions.join(", ")
);
throw new Error(`Organization "${organizationSlug}" not found`);
}
}
/**
* Ensures the user has selected an organization, automatically selecting the first one if available
*/
export async function ensureOrganization(
authConfig: AuthConfig,
isHeadless: boolean = false
isHeadless: boolean = false,
cliOrganizationSlug?: string
): Promise<AuthConfig> {
// If using CONTINUE_API_KEY environment variable, don't require organization selection
if (isEnvironmentAuthConfig(authConfig)) {
// Handle CLI organization slug if provided (undefined means no --org flag or --org personal)
if (cliOrganizationSlug) {
// Only allow --org flag in headless mode
if (!isHeadless) {
console.error(
chalk.red(
"The --org flag is only supported in headless mode (with -p/--print flag)"
)
);
process.exit(1);
}
// For environment auth configs
if (isEnvironmentAuthConfig(authConfig)) {
const apiClient = getApiClient(authConfig.accessToken);
const resolvedOrg = await resolveOrganizationBySlug(
apiClient,
cliOrganizationSlug
);
// Return modified environment auth config with organization ID
return {
...authConfig,
organizationId: resolvedOrg.id,
};
}
} else if (isEnvironmentAuthConfig(authConfig)) {
// No CLI organization slug (or "personal" was specified) - return as-is
return authConfig;
}
@ -543,7 +614,24 @@ export async function ensureOrganization(
}
// TypeScript now knows authConfig is AuthenticatedConfig
const authenticatedConfig = authConfig;
const authenticatedConfig: AuthenticatedConfig = authConfig;
// If a CLI organization slug is provided, try to use it (for authenticated configs)
if (cliOrganizationSlug) {
const apiClient = getApiClient(authenticatedConfig.accessToken);
const resolvedOrg = await resolveOrganizationBySlug(
apiClient,
cliOrganizationSlug
);
const updatedConfig: AuthenticatedConfig = {
...authenticatedConfig,
organizationId: resolvedOrg.id,
};
saveAuthConfig(updatedConfig);
return updatedConfig;
}
// If already have organization ID (including null for personal), return as-is
if (authenticatedConfig.organizationId !== undefined) {
@ -630,7 +718,7 @@ export async function ensureOrganization(
* Gets the list of available organizations for the user
*/
export async function listUserOrganizations(): Promise<
{ id: string; name: string }[] | null
{ id: string; name: string; slug: string }[] | null
> {
const authConfig = loadAuthConfig();
@ -647,7 +735,14 @@ export async function listUserOrganizations(): Promise<
try {
const resp = await apiClient.listOrganizations();
return resp.organizations || [];
// Map the organizations to include slug field
return (
resp.organizations?.map((org) => ({
id: org.id,
name: org.name,
slug: org.slug,
})) || []
);
} catch {
return null;
}

View file

@ -82,6 +82,7 @@ export interface ChatOptions extends ExtendedCommandOptions {
rule?: string[]; // Array of rule specifications
format?: "json"; // Output format for headless mode
silent?: boolean; // Strip <think></think> tags and excess whitespace
org?: string; // Organization slug to use for this session
}
export async function initializeChatHistory(
@ -326,6 +327,7 @@ async function runHeadlessMode(
await initializeServices({
configPath: options.config,
organizationSlug: options.org,
rules: options.rule,
headless: true,
toolPermissionOverrides: permissionOverrides,
@ -406,6 +408,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
// Initialize services with onboarding handled internally
const initResult = await initializeServices({
configPath: options.config,
organizationSlug: options.org,
rules: options.rule,
headless: false,
toolPermissionOverrides: permissionOverrides,
@ -424,6 +427,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
prompt,
options.resume,
options.config,
options.org,
options.rule,
permissionOverrides,
true

View file

@ -0,0 +1,105 @@
import {
createTestContext,
cleanupTestContext,
runCLI,
createTestConfig,
} from "../test-helpers/cli-helpers.js";
describe("E2E: Headless Mode with --org flag", () => {
let context: any;
const testConfig = `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`;
const testEnv = {
OPENAI_API_KEY: "test-key",
CONTINUE_API_KEY: "test-api-key",
};
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
await cleanupTestContext(context);
});
describe("--org flag mode restriction", () => {
it("should fail when --org is used without -p flag (interactive mode)", async () => {
await createTestConfig(context, testConfig);
const result = await runCLI(context, {
args: [
"--config",
context.configPath,
"--org",
"my-org",
"Test prompt",
],
env: testEnv,
expectError: true,
});
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain(
"--org flag is only supported in headless mode"
);
});
it("should accept --org flag with -p flag (headless mode)", async () => {
await createTestConfig(context, testConfig);
// This will fail due to missing actual auth, but should get past the flag validation
const result = await runCLI(context, {
args: [
"-p",
"--config",
context.configPath,
"--org",
"my-org",
"Test prompt",
],
env: testEnv,
expectError: true,
});
// Should fail for a different reason (no actual auth/API), not because of flag validation
expect(result.stderr).not.toContain(
"--org flag is only supported in headless mode"
);
});
});
describe("--org flag inheritance", () => {
it("should inherit --org flag from parent command", async () => {
await createTestConfig(context, testConfig);
// Test with chat subcommand
const result = await runCLI(context, {
args: [
"--org",
"test-org",
"chat",
"-p",
"--config",
context.configPath,
"Test prompt",
],
env: testEnv,
expectError: true,
});
// The org flag should be inherited and work in headless mode
expect(result.stderr).not.toContain(
"--org flag is only supported in headless mode"
);
});
});
});

View file

@ -136,6 +136,59 @@ describe('AuthService', () => {
'Not authenticated - cannot ensure organization'
);
});
test('should pass organization slug to ensureOrganization in headless mode', async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockReturnValue(true);
await service.initialize();
const updatedConfig = { ...mockAuthConfig, organizationId: 'org-456' };
vi.mocked(ensureOrganization).mockResolvedValue(updatedConfig);
const state = await service.ensureOrganization(true, 'org-slug');
expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, true, 'org-slug');
expect(state).toEqual({
authConfig: updatedConfig,
isAuthenticated: true,
organizationId: 'org-456'
});
});
test('should handle personal organization slug', async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockReturnValue(true);
await service.initialize();
const personalConfig = { ...mockAuthConfig, organizationId: null };
vi.mocked(ensureOrganization).mockResolvedValue(personalConfig);
const state = await service.ensureOrganization(true, 'personal');
expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, true, 'personal');
expect(state).toEqual({
authConfig: personalConfig,
isAuthenticated: true,
organizationId: undefined
});
});
test('should work without organization slug parameter', async () => {
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
vi.mocked(isAuthenticated).mockReturnValue(true);
await service.initialize();
vi.mocked(ensureOrganization).mockResolvedValue(mockAuthConfig);
const state = await service.ensureOrganization(false);
expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, false, undefined);
expect(state).toEqual({
authConfig: mockAuthConfig,
isAuthenticated: true,
organizationId: 'org-123'
});
});
});
describe('switchOrganization()', () => {
@ -189,8 +242,8 @@ describe('AuthService', () => {
await service.initialize();
const mockOrgs = [
{ id: 'org-1', name: 'Org 1' },
{ id: 'org-2', name: 'Org 2' }
{ id: 'org-1', name: 'Org 1', slug: 'org-1' },
{ id: 'org-2', name: 'Org 2', slug: 'org-2' }
];
vi.mocked(listUserOrganizations).mockResolvedValue(mockOrgs);
@ -234,8 +287,8 @@ describe('AuthService', () => {
await service.initialize();
vi.mocked(listUserOrganizations).mockResolvedValue([
{ id: 'org-1', name: 'Org 1' },
{ id: 'org-2', name: 'Org 2' }
{ id: 'org-1', name: 'Org 1', slug: 'org-1' },
{ id: 'org-2', name: 'Org 2', slug: 'org-2' }
]);
const hasMultiple = await service.hasMultipleOrganizations();

View file

@ -96,7 +96,8 @@ export class AuthService extends BaseService<AuthServiceState> {
* Ensure organization is selected, prompting if necessary
*/
async ensureOrganization(
isHeadless: boolean = false
isHeadless: boolean = false,
cliOrganizationSlug?: string
): Promise<AuthServiceState> {
if (!this.currentState.authConfig) {
throw new Error("Not authenticated - cannot ensure organization");
@ -105,11 +106,13 @@ export class AuthService extends BaseService<AuthServiceState> {
logger.debug("Ensuring organization is selected", {
currentOrgId: this.currentState.organizationId,
isHeadless,
cliOrganizationSlug,
});
const updatedConfig = await ensureOrganization(
this.currentState.authConfig,
isHeadless
isHeadless,
cliOrganizationSlug
);
this.setState({

View file

@ -112,11 +112,12 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom
serviceContainer.get<ApiClientServiceState>(SERVICE_NAMES.API_CLIENT),
]);
// Ensure organization is selected if authenticated and not headless
// Ensure organization is selected if authenticated
let finalAuthState = authState;
if (authState.authConfig && !options.headless) {
if (authState.authConfig) {
finalAuthState = await authService.ensureOrganization(
options.headless ?? false
options.headless ?? false,
options.organizationSlug
);
// Update the auth service state in container
serviceContainer.set(SERVICE_NAMES.AUTH, finalAuthState);

View file

@ -82,6 +82,7 @@ export const SERVICE_NAMES = {
*/
export interface ServiceInitOptions {
configPath?: string;
organizationSlug?: string; // Organization slug to use for this session
rules?: string[];
headless?: boolean;
skipOnboarding?: boolean; // Skip onboarding check even in TUI mode

View file

@ -4,6 +4,7 @@ import { Command } from "commander";
export function addCommonOptions(command: Command): Command {
return command
.option("--config <path>", "Path to configuration file")
.option("--org <slug>", "Organization slug to use for this session (supported only in headless mode)")
.option("--readonly", "Start in plan mode (read-only tools)")
.option("--auto", "Start in auto mode (all tools allowed)")
.option("-v, --verbose", "Enable verbose logging")
@ -57,6 +58,7 @@ export function mergeParentOptions(parentCommand: Command, options: any): any {
// List of options to inherit from parent if not present in subcommand
const inheritableOptions = [
'config',
'org',
'readonly',
'auto',
'tools',

View file

@ -41,7 +41,8 @@ const OrganizationSelector: React.FC<OrganizationSelectorProps> = ({
const options: Organization[] = [
{
id: "personal",
name: "Personal"
name: "Personal",
slug: "personal"
},
...organizations,
];

View file

@ -13,6 +13,7 @@ export async function startTUIChat(
initialPrompt?: string,
resume?: boolean,
configPath?: string,
organizationSlug?: string,
additionalRules?: string[],
toolPermissionOverrides?: {
allow?: string[];
@ -26,6 +27,7 @@ export async function startTUIChat(
if (!skipOnboarding) {
initializeServices({
configPath,
organizationSlug,
rules: additionalRules,
headless: false,
toolPermissionOverrides,