@gravity-rail/cli 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/errors.ts","../src/lib/pagination.ts","../src/lib/args.ts","../../client/src/index.ts","../../client/src/api/admin.ts","../../client/src/client/client.ts","../../client/src/client/bindings/admin.ts","../src/lib/context.ts","../src/lib/output.ts","../src/lib/realm.ts","../src/lib/org-auth.ts","../src/lib/input.ts","../src/lib/crud.ts","../src/lib/registry.ts","../src/lib/types.ts","../src/domains/agent-tasks.ts","../src/domains/agents.ts","../src/domains/chats.ts","../src/domains/members.ts","../src/domains/tasks.ts","../src/domains/workflows.ts","../src/domains/workflow-versions.ts","../src/domains/workspaces.ts","../src/domains/assignments.ts","../src/domains/calendars.ts","../src/domains/data-types.ts","../src/domains/events.ts","../src/domains/files.ts","../src/domains/journeys.ts","../src/domains/personas.ts","../src/domains/qualifications.ts","../src/domains/sites.ts","../src/domains/access-grants.ts","../src/domains/ai-models.ts","../src/domains/api-keys.ts","../src/domains/apps.ts","../src/domains/auth-manage.ts","../src/domains/billing-portal.ts","../src/lib/concierge-api.ts","../src/domains/concierge.ts","../src/domains/custom-toolkits.ts","../src/domains/features.ts","../src/domains/inboxes.ts","../src/domains/mcp-servers.ts","../src/domains/member-memories.ts","../src/domains/milestones.ts","../src/domains/notification-rules.ts","../src/domains/oauth.ts","../src/domains/operator-groups.ts","../src/domains/org.ts","../src/domains/org-phone-numbers.ts","../src/domains/phone-numbers.ts","../src/domains/pronunciations.ts","../src/domains/reports.ts","../src/domains/subscriptions.ts","../src/domains/prompts.ts","../src/domains/support.ts","../src/domains/supervisors.ts","../src/domains/sync.ts","../src/domains/integrations/app-connections.ts","../src/domains/integrations/confluence.ts","../src/domains/integrations/discord-bots.ts","../src/domains/integrations/fhir-connections.ts","../src/domains/integrations/hubspot.ts","../src/domains/integrations/monday.ts","../src/domains/integrations/salesforce.ts","../src/domains/integrations/slack-apps.ts","../src/domains/integrations/teams-apps.ts","../src/domains/index.ts","../src/commands/auth-browser.ts","../src/lib/chat-session.ts","../src/lib/realtime-client.ts","../src/lib/chat-tui.ts","../src/lib/audio.ts","../src/commands/concierge.ts","../src/commands/dev.ts","../src/commands/login.ts","../src/commands/manage.ts","../src/commands/organizations.ts","../src/commands/whoami.ts"],"sourcesContent":["export class CLIError extends Error {\n constructor(\n message: string,\n public exitCode: number = 1\n ) {\n super(message);\n this.name = 'CLIError';\n }\n}\n\nexport class AuthRequiredError extends CLIError {\n constructor(message = 'Not authenticated. Run `gr login` or set GRAVITY_RAIL_API_KEY.') {\n super(message, 2);\n this.name = 'AuthRequiredError';\n }\n}\n\nexport function handleError(err: unknown): never {\n if (err instanceof CLIError) {\n process.stderr.write(`Error: ${err.message}\\n`);\n process.exit(err.exitCode);\n }\n\n if (err instanceof Error) {\n process.stderr.write(`Error: ${err.message}\\n`);\n if ('errors' in err && Array.isArray((err as any).errors)) {\n for (const e of (err as any).errors) {\n process.stderr.write(` - ${e}\\n`);\n }\n }\n if ('statusCode' in err && (err as any).statusCode === 401) {\n process.stderr.write(\n `\\nHint: Run \"gr login\" to authenticate, or set GRAVITY_RAIL_API_KEY for non-interactive use.\\n`\n );\n }\n process.exit(1);\n }\n\n process.stderr.write(`Error: ${String(err)}\\n`);\n process.exit(1);\n}\n","import type { ArgDef, ParsedArgs } from './types';\nimport { CLIError } from './errors';\n\n// ── Response shape detection ─────────────────────────────────────────\n\n/** Metadata extracted from a paginated API response */\nexport interface PaginationMeta {\n /** Total number of items across all pages (page-based only) */\n total?: number;\n /** Current page number (page-based only) */\n page?: number;\n /** Total pages (page-based only) */\n totalPages?: number;\n /** Whether more pages exist (cursor-based only) */\n hasMore?: boolean;\n /** Cursor for next page (cursor-based only) */\n nextCursor?: string;\n}\n\n/** Explicit pagination contract passed from commands to outputData */\nexport interface ListResult {\n items: unknown[];\n meta?: PaginationMeta;\n supportsAll?: boolean;\n}\n\n/** Type guard: is the value a ListResult (explicit contract)? */\nexport function isListResult(data: unknown): data is ListResult {\n if (!data || typeof data !== 'object' || Array.isArray(data)) return false;\n const obj = data as Record<string, unknown>;\n return (\n Array.isArray(obj.items) &&\n ('supportsAll' in obj ||\n ('meta' in obj && (obj.meta === undefined || typeof obj.meta === 'object')))\n );\n}\n\n/** Check if a response looks like a page-based paginated envelope.\n * Matches both `{ items, total, totalPages, page }` (standard) and\n * `{ items, total, page, pageSize }` (legacy — e.g. InvitationListResponse,\n * InquiryListResponse). This is a pure type guard with no side effects;\n * totalPages computation for legacy shapes happens in extractPaginationMeta. */\nexport function isPagePaginatedResponse(data: unknown): data is {\n items: unknown[];\n total: number;\n page: number;\n totalPages?: number;\n pageSize?: number;\n} {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n if (!Array.isArray(obj.items) || typeof obj.page !== 'number') return false;\n\n // Standard shape: has totalPages\n if (typeof obj.totalPages === 'number') return true;\n\n // Legacy shape: has total + pageSize but no totalPages\n if (typeof obj.total === 'number' && typeof obj.pageSize === 'number') return true;\n\n return false;\n}\n\n/** Check if a response looks like a cursor-based paginated envelope */\nexport function isCursorPaginatedResponse(data: unknown): data is {\n items: unknown[];\n hasMore: boolean;\n nextCursor?: string;\n} {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n return Array.isArray(obj.items) && typeof obj.hasMore === 'boolean';\n}\n\n/** Check if a response is any paginated envelope ({ items: [...], ... }) */\nexport function isPaginatedResponse(data: unknown): boolean {\n return isPagePaginatedResponse(data) || isCursorPaginatedResponse(data);\n}\n\n/** Extract pagination metadata from a response, or return undefined for non-paginated responses.\n * For legacy shapes without totalPages, computes it from total/pageSize. */\nexport function extractPaginationMeta(data: unknown): PaginationMeta | undefined {\n if (isPagePaginatedResponse(data)) {\n const totalPages =\n data.totalPages ?? (data.pageSize ? Math.ceil(data.total / data.pageSize) : undefined);\n return {\n total: data.total,\n page: data.page,\n totalPages,\n };\n }\n if (isCursorPaginatedResponse(data)) {\n return {\n hasMore: data.hasMore,\n nextCursor: data.nextCursor,\n };\n }\n return undefined;\n}\n\n// ── Warning formatting ───────────────────────────────────────────────\n\n/** Format a pagination warning for stderr. Returns undefined if no warning needed.\n * When `supportsAll` is false, the \"Use --all\" hint is omitted because the\n * command does not actually expose the --all flag. */\nexport function formatPaginationWarning(\n meta: PaginationMeta | undefined,\n supportsAll: boolean = true\n): string | undefined {\n if (!meta) return undefined;\n\n const allHint = supportsAll ? ' Use --all to fetch all pages.' : '';\n\n // Page-based: warn when there are multiple pages\n if (meta.totalPages !== undefined && meta.totalPages > 1) {\n const pageNum = meta.page ?? 1;\n return `Showing page ${pageNum} of ${meta.totalPages} (${meta.total} total items).${allHint}`;\n }\n\n // Cursor-based: warn when more pages exist\n if (meta.hasMore === true) {\n return `More results available.${allHint}`;\n }\n\n return undefined;\n}\n\n// ── Unwrapping ───────────────────────────────────────────────────────\n\n/** Unwrap items from a paginated response or return the data as-is if it's an array */\nexport function unwrapItems(data: unknown): unknown[] {\n if (Array.isArray(data)) return data;\n if (\n data &&\n typeof data === 'object' &&\n 'items' in data &&\n Array.isArray((data as Record<string, unknown>).items)\n ) {\n return (data as Record<string, unknown>).items as unknown[];\n }\n return [data];\n}\n\n// ── Arg definitions ──────────────────────────────────────────────────\n\n/** Default pagination args for list commands (page, page-size, all). No search. */\nexport const LIST_PAGINATION_ARGS: ArgDef[] = [\n { name: 'page', description: 'Page number' },\n { name: 'page-size', description: 'Page size' },\n { name: 'all', description: 'Fetch all pages and return combined results', isFlag: true },\n];\n\n// ── Arg-to-options helpers ───────────────────────────────────────────\n\n/** Convert parsed CLI args to API pagination options */\nexport function parsePaginationArgs(args: ParsedArgs): {\n page?: number;\n pageSize?: number;\n all?: boolean;\n} {\n const result: { page?: number; pageSize?: number; all?: boolean } = {};\n\n if (args.all === true) {\n result.all = true;\n }\n\n if (args.page !== undefined) {\n const num = Number(args.page);\n if (isNaN(num) || num < 1) throw new CLIError('--page must be a positive integer');\n result.page = num;\n }\n\n if (args['page-size'] !== undefined) {\n const num = Number(args['page-size']);\n if (isNaN(num) || num < 1) throw new CLIError('--page-size must be a positive integer');\n if (num > 100) throw new CLIError('--page-size must be at most 100 (API limit)');\n result.pageSize = num;\n }\n\n return result;\n}\n\n// ── fetchAll helpers ─────────────────────────────────────────────────\n\nconst MAX_PAGE_SIZE = 100;\nconst MAX_PAGES = 200; // Safety limit to prevent infinite loops\n\n/**\n * Fetch all pages from a page-based paginated endpoint.\n * The fetcher receives { page, pageSize } and should return the raw API response.\n * Throws CLIError if MAX_PAGES is reached without exhausting all pages.\n */\nexport async function fetchAllPages(\n fetcher: (opts: { page: number; pageSize: number }) => Promise<unknown>\n): Promise<unknown[]> {\n const allItems: unknown[] = [];\n let page = 1;\n\n while (page <= MAX_PAGES) {\n const result = await fetcher({ page, pageSize: MAX_PAGE_SIZE });\n const items = unwrapItems(result);\n allItems.push(...items);\n\n // Use server metadata for termination\n const meta = extractPaginationMeta(result);\n if (meta?.totalPages !== undefined) {\n if (page >= meta.totalPages) break;\n } else if (!isPagePaginatedResponse(result)) {\n // Raw array or no metadata — single fetch is enough\n if (items.length < MAX_PAGE_SIZE) break;\n }\n\n if (page === MAX_PAGES) {\n throw new CLIError(\n `Reached maximum page limit (${MAX_PAGES}). Results may be incomplete.`\n );\n }\n\n page++;\n }\n\n return allItems;\n}\n\n/**\n * Fetch all pages from a cursor-based paginated endpoint.\n * The fetcher receives { cursor? } and should return the raw API response.\n * Throws CLIError if MAX_PAGES is reached without exhausting all pages.\n */\nexport async function fetchAllCursorPages(\n fetcher: (opts: { cursor?: string }) => Promise<unknown>\n): Promise<unknown[]> {\n const allItems: unknown[] = [];\n let cursor: string | undefined;\n let pages = 0;\n\n while (pages < MAX_PAGES) {\n const result = await fetcher({ cursor });\n const items = unwrapItems(result);\n allItems.push(...items);\n pages++;\n\n if (isCursorPaginatedResponse(result) && result.hasMore && result.nextCursor) {\n cursor = result.nextCursor;\n } else {\n break;\n }\n\n if (pages === MAX_PAGES) {\n throw new CLIError(\n `Reached maximum page limit (${MAX_PAGES}). Results may be incomplete.`\n );\n }\n }\n\n return allItems;\n}\n\n// ── ListResult factory ──────────────────────────────────────────────\n\n/**\n * Wrap a raw API response into a ListResult with explicit pagination metadata.\n * Works with both page-based and cursor-based responses, as well as plain arrays.\n *\n * @param data - Raw API response (paginated envelope or plain array)\n * @param supportsAll - Whether the calling command exposes --all\n */\nexport function listResult(data: unknown, supportsAll: boolean = false): ListResult {\n return {\n items: unwrapItems(data),\n meta: extractPaginationMeta(data),\n supportsAll,\n };\n}\n","import type { ArgDef, ParsedArgs } from './types';\nimport { CLIError } from './errors';\nimport { LIST_PAGINATION_ARGS } from './pagination';\n\nexport { LIST_PAGINATION_ARGS };\n\n/** Standard pagination args used by admin list commands (includes search).\n * @deprecated Use LIST_PAGINATION_ARGS (page/page-size/all only) plus domain-specific filter args instead. */\nexport const PAGINATION_ARGS: ArgDef[] = [\n { name: 'search', description: 'Search by name' },\n ...LIST_PAGINATION_ARGS,\n];\n\n/** Common args automatically available to all commands */\nconst COMMON_ARGS: ArgDef[] = [\n { name: 'workspace', alias: 'w', description: 'Workspace UUID' },\n { name: 'data', alias: 'd', description: 'JSON data string' },\n { name: 'file', alias: 'f', description: 'Path to JSON file' },\n { name: 'id', description: 'Entity ID' },\n { name: 'uuid', description: 'Entity UUID' },\n];\n\nexport function parseArgs(defs: ArgDef[], argv: string[]): ParsedArgs {\n const allDefs = [...COMMON_ARGS, ...defs];\n const result: ParsedArgs = {};\n\n // Apply defaults\n for (const def of allDefs) {\n if (def.default !== undefined) {\n result[def.name] = def.default;\n }\n }\n\n // Known global options that parseGlobalOptions already consumed\n const KNOWN_GLOBAL_FLAGS = new Set([\n '--env',\n '--realm',\n '--output-format',\n '-o',\n '--verbose',\n '-v',\n '--allow-write',\n '--help',\n '-h',\n '--version',\n ]);\n\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n\n // Support --flag=value and -f=value syntax\n const eqIdx = arg.indexOf('=');\n const flagPart = eqIdx !== -1 ? arg.slice(0, eqIdx) : arg;\n const inlineValue = eqIdx !== -1 ? arg.slice(eqIdx + 1) : undefined;\n\n const def = findDef(allDefs, flagPart);\n if (!def) {\n // Warn about unknown flags (typos etc.) but don't fail\n if (\n (flagPart.startsWith('--') || flagPart.startsWith('-')) &&\n !KNOWN_GLOBAL_FLAGS.has(flagPart)\n ) {\n process.stderr.write(`Warning: unknown flag \"${flagPart}\" (ignored)\\n`);\n }\n continue;\n }\n if (def.isFlag) {\n result[def.name] = true;\n } else {\n const value = inlineValue ?? argv[++i];\n if (value === undefined) {\n throw new CLIError(`Missing value for --${def.name}`);\n }\n result[def.name] = value;\n }\n }\n\n // Validate required\n for (const def of allDefs) {\n if (def.required && result[def.name] === undefined) {\n throw new CLIError(`Missing required argument: --${def.name}`);\n }\n }\n\n return result;\n}\n\nfunction findDef(defs: ArgDef[], arg: string): ArgDef | undefined {\n for (const def of defs) {\n if (arg === `--${def.name}`) return def;\n if (def.alias && arg === `-${def.alias}`) return def;\n if (def.aliases) {\n for (const a of def.aliases) {\n if (arg === `--${a}`) return def;\n }\n }\n }\n return undefined;\n}\n","/**\n * @gravity-rail/client — Internal full-surface API client.\n *\n * Re-exports the entire public SDK surface via `@gravity-rail/sdk/internal`\n * (which includes admin TypeScript types), and adds the admin runtime classes\n * (`AdminApi`, `ApiClient`, `AdminBindings`, `bindAdminMethods`).\n *\n * Consumers in the monorepo should continue importing from `@gravity-rail/client`\n * as before — nothing externally visible has changed. The admin runtime classes\n * are physically absent from the public `@gravity-rail/sdk` package.\n */\n\nexport * from '@gravity-rail/sdk/internal';\n\n// Admin-only runtime\nexport { AdminApi } from './api/admin';\nexport { ApiClient } from './client/client';\nexport type { AdminBindings } from './client/bindings/admin';\nexport { bindAdminMethods } from './client/bindings/admin';\n","import {\n AccountLookupResponse,\n CreateCustomerRequest,\n CreateResellerRequest,\n Customer,\n DataExportResponse,\n DeletionCancelResponse,\n DeletionRequestResponse,\n CustomerAccount,\n LinkResellerAccountRequest,\n Reseller,\n ResellerAccount,\n UpdateCustomerRequest,\n UpdateResellerRequest,\n AccountSortField,\n AdminAccount,\n AdminBulkWorkflowAccessValidationResponse,\n HealthDetailRequest,\n HealthMetricsRequest,\n HealthMetricsResponse,\n WorkspaceHealthDetail,\n AdminAccountFormData,\n AdminAccountMembership,\n AdminAccountOrgMembership,\n AdminOrganization,\n AdminUpdateProductRequest,\n AdminChat,\n AdminChatDetail,\n AdminChatsOptions,\n MemberOrgView,\n AdminWorkspace,\n AdminWorkspaceFormData,\n AdminWorkspaceMemberFormData,\n UsageDashboardResponse,\n CompareWithStripeResponse,\n UsageReport,\n UsageReportRequest,\n VoiceMetricsResponse,\n AdminTemporalDetailQuery,\n AdminTemporalFailedQuery,\n AdminTemporalStuckQuery,\n AdminTemporalSummaryQuery,\n FailedWorkflowsResponse,\n StuckWorkflowsResponse,\n TemporalAdminConfig,\n TemporalSummaryResponse,\n WorkflowDetailResponse,\n CreateOrganizationRequest,\n CreateProductRequest,\n GenerateSummariesResponse,\n Inbox,\n InboxMappingDetailResponse,\n LogoUploadRequest,\n LogoUploadResponse,\n Member,\n MemberRole,\n MergeMembersRequest,\n MergeMembersResponse,\n MissingMembershipItem,\n OrgMember,\n PaginatedResponse,\n PaginatedSubscriptionsResponse,\n PhoneNumber,\n UnmappedPhoneNumber,\n Product,\n ChangeWorkspaceProductRequest,\n ChangeWorkspaceProductResponse,\n ProvisionPlanRequest,\n ProvisionPlanResponse,\n SiteMapping,\n SiteMappingFormData,\n SortOrder,\n StripeCustomer,\n StripeCustomerCreateRequest,\n StripeCustomerUpdateRequest,\n StripePaymentMethod,\n BillingPeriod,\n Invoice,\n RecordPaymentRequest,\n DirectSubscriptionCreateRequest,\n StripeSubscriptionCreateRequest,\n StripeSubscriptionUpdateRequest,\n Subscription,\n SyncProductToStripeRequest,\n SyncProductToStripeResponse,\n ThemesListResponse,\n OrgA2PStatus,\n ProviderPhoneNumber,\n UpdateOrganizationRequest,\n Workspace,\n WorkspaceHealthResponse,\n WorkspaceSortField,\n CreateSupportRequestCommentRequest,\n CreateSupportRequestNoteRequest,\n SupportRequest,\n SupportRequestListParams,\n SupportRequestListResponse,\n UpdateSupportRequestAttributesRequest,\n UpdateSupportRequestStatusRequest,\n} from '@gravity-rail/sdk/internal';\nimport { BaseApiClient } from '@gravity-rail/sdk/internal';\n\nfunction supportRequestParams(params?: SupportRequestListParams): string {\n const searchParams = new URLSearchParams();\n if (params?.page) searchParams.append('page', params.page.toString());\n if (params?.pageSize) searchParams.append('pageSize', params.pageSize.toString());\n if (params?.status) searchParams.append('status', params.status);\n if (params?.supportRequestType) {\n searchParams.append('supportRequestType', params.supportRequestType);\n }\n if (params?.severity) searchParams.append('severity', params.severity);\n if (params?.source) searchParams.append('source', params.source);\n if (params?.organizationId !== undefined) {\n searchParams.append('organizationId', params.organizationId.toString());\n }\n if (params?.workspaceId !== undefined) {\n searchParams.append('workspaceId', params.workspaceId.toString());\n }\n if (params?.linearLinked !== undefined) {\n searchParams.append('linearLinked', params.linearLinked.toString());\n }\n const query = searchParams.toString();\n return query ? `?${query}` : '';\n}\n\nexport class AdminApi extends BaseApiClient {\n // Support Requests API\n async listSupportRequestsAsAdmin(\n params?: SupportRequestListParams\n ): Promise<SupportRequestListResponse> {\n return this.fetch<SupportRequestListResponse>(\n `admin/support-requests${supportRequestParams(params)}`\n );\n }\n\n async getSupportRequestAsAdmin(uuid: string): Promise<SupportRequest> {\n return this.fetch<SupportRequest>(`admin/support-requests/${uuid}`);\n }\n\n async commentOnSupportRequestAsAdmin(\n uuid: string,\n data: CreateSupportRequestCommentRequest\n ): Promise<SupportRequest> {\n return this.fetch<SupportRequest>(`admin/support-requests/${uuid}/comments`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async noteOnSupportRequestAsAdmin(\n uuid: string,\n data: CreateSupportRequestNoteRequest\n ): Promise<SupportRequest> {\n return this.fetch<SupportRequest>(`admin/support-requests/${uuid}/notes`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateSupportRequestStatusAsAdmin(\n uuid: string,\n data: UpdateSupportRequestStatusRequest\n ): Promise<SupportRequest> {\n return this.fetch<SupportRequest>(`admin/support-requests/${uuid}/status`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateSupportRequestAttributesAsAdmin(\n uuid: string,\n data: UpdateSupportRequestAttributesRequest\n ): Promise<SupportRequest> {\n return this.fetch<SupportRequest>(`admin/support-requests/${uuid}/attributes`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async createSupportRequestLinearIssueAsAdmin(uuid: string): Promise<SupportRequest> {\n return this.fetch<SupportRequest>(`admin/support-requests/${uuid}/linear-issue`, {\n method: 'POST',\n });\n }\n\n // Admin Accounts API\n async getAccounts(options: {\n search?: string;\n createdAfter?: string;\n createdBefore?: string;\n isActive?: boolean;\n organizationId?: number;\n pendingDeletion?: boolean;\n sortBy?: AccountSortField;\n sortOrder?: SortOrder;\n page?: number;\n pageSize?: number;\n }): Promise<PaginatedResponse<AdminAccount>> {\n const params = new URLSearchParams();\n if (options.search) params.append('search', options.search);\n if (options.createdAfter) params.append('created_after', options.createdAfter);\n if (options.createdBefore) params.append('created_before', options.createdBefore);\n if (options.sortBy) params.append('sortBy', options.sortBy);\n if (options.sortOrder) params.append('sortOrder', options.sortOrder);\n if (options.page) params.append('page', options.page.toString());\n if (options.pageSize) params.append('pageSize', options.pageSize.toString());\n if (options.isActive !== undefined) params.append('isActive', options.isActive.toString());\n if (options.organizationId !== undefined)\n params.append('organizationId', options.organizationId.toString());\n if (options.pendingDeletion !== undefined)\n params.append('pendingDeletion', options.pendingDeletion.toString());\n\n return this.fetch<PaginatedResponse<AdminAccount>>(`admin/accounts?${params.toString()}`);\n }\n\n async getAccountDetails(id: string | number): Promise<AdminAccount> {\n return this.fetch<AdminAccount>(`admin/accounts/${id}`);\n }\n\n async getAccountByUuid(uuid: string): Promise<AdminAccount> {\n return this.fetch<AdminAccount>(`admin/accounts/${uuid}`);\n }\n\n async getAccountMemberships(accountId: number): Promise<AdminAccountMembership[]> {\n return this.fetch<AdminAccountMembership[]>(`admin/accounts/${accountId}/memberships`);\n }\n\n async getAccountOrgMemberships(accountId: number): Promise<AdminAccountOrgMembership[]> {\n return this.fetch<AdminAccountOrgMembership[]>(`admin/accounts/${accountId}/org-memberships`);\n }\n\n async createAccountOrgMembership(\n accountId: number,\n organizationId: number,\n role: 'member' | 'admin' | 'owner' = 'member'\n ): Promise<{\n accountId: number;\n organizationId: number;\n organizationUuid: string;\n organizationName: string;\n role: string;\n message: string;\n }> {\n return this.fetch(`admin/accounts/${accountId}/org-memberships`, {\n method: 'POST',\n body: JSON.stringify({ organizationId, role }),\n });\n }\n\n async deleteAccountOrgMembership(\n accountId: number,\n organizationId: number\n ): Promise<{\n status: string;\n message: string;\n workspaceMembershipsRemoved: number;\n }> {\n return this.fetch(`admin/accounts/${accountId}/org-memberships/${organizationId}`, {\n method: 'DELETE',\n });\n }\n\n async getAccountMembership(\n accountId: number,\n workspaceId: string\n ): Promise<AdminAccountMembership> {\n return this.fetch<AdminAccountMembership>(\n `admin/accounts/${accountId}/memberships/${workspaceId}`\n );\n }\n\n async updateAccountMembership(\n accountId: number,\n workspaceId: string,\n updates: AdminWorkspaceMemberFormData\n ): Promise<AdminAccountMembership> {\n return this.fetch<AdminAccountMembership>(\n `admin/accounts/${accountId}/memberships/${workspaceId}`,\n {\n method: 'PUT',\n body: JSON.stringify(updates),\n }\n );\n }\n\n async createAccountMembership(\n accountId: number,\n workspaceId: string,\n data: { memberRoleId: number }\n ): Promise<AdminAccountMembership> {\n return this.fetch<AdminAccountMembership>(\n `admin/accounts/${accountId}/memberships/${workspaceId}`,\n {\n method: 'POST',\n body: JSON.stringify(data),\n }\n );\n }\n\n async deleteAccountMembership(accountId: number, workspaceId: string): Promise<void> {\n return this.fetch<void>(`admin/accounts/${accountId}/memberships/${workspaceId}`, {\n method: 'DELETE',\n });\n }\n\n async updateAccountAsAdmin(\n id: string | number,\n updates: AdminAccountFormData\n ): Promise<AdminAccount> {\n return this.fetch<AdminAccount>(`admin/accounts/${id}`, {\n method: 'PUT',\n body: JSON.stringify(updates),\n });\n }\n\n async createAccountAsAdmin(data: AdminAccountFormData): Promise<AdminAccount> {\n return this.fetch<AdminAccount>('admin/accounts', {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async deleteAccountAsAdmin(id: number): Promise<void> {\n return this.fetch(`admin/accounts/${id}`, {\n method: 'DELETE',\n });\n }\n\n // GDPR Data Subject Rights (superuser only)\n\n async exportAccountData(accountId: number): Promise<DataExportResponse> {\n return this.fetch(`admin/data-rights/${accountId}/export`, {\n method: 'POST',\n });\n }\n\n async requestAccountDeletion(accountId: number): Promise<DeletionRequestResponse> {\n return this.fetch(`admin/data-rights/${accountId}/delete`, {\n method: 'POST',\n });\n }\n\n async cancelAccountDeletion(accountId: number): Promise<DeletionCancelResponse> {\n return this.fetch(`admin/data-rights/${accountId}/cancel-delete`, {\n method: 'POST',\n });\n }\n\n /**\n * Look up an account by email or phone. Returns verification status.\n * Used to check if a verified account exists before creating a new one.\n */\n async lookupAccount(options: {\n email?: string;\n phone?: string;\n }): Promise<AccountLookupResponse> {\n const params = new URLSearchParams();\n if (options.email) params.append('email', options.email);\n if (options.phone) params.append('phone', options.phone);\n\n return this.fetch<AccountLookupResponse>(`admin/accounts/lookup?${params.toString()}`);\n }\n\n // Admin Organizations API\n async getOrganizations(options?: {\n search?: string;\n page?: number;\n pageSize?: number;\n noSubscription?: boolean;\n sortBy?: string;\n sortOrder?: 'asc' | 'desc';\n }): Promise<PaginatedResponse<AdminOrganization>> {\n const params = new URLSearchParams();\n if (options?.search) params.append('search', options.search);\n if (options?.page) params.append('page', options.page.toString());\n if (options?.pageSize) params.append('pageSize', options.pageSize.toString());\n if (options?.noSubscription) params.append('no_subscription', 'true');\n if (options?.sortBy) params.append('sortBy', options.sortBy);\n if (options?.sortOrder) params.append('sortOrder', options.sortOrder);\n\n return this.fetch<PaginatedResponse<AdminOrganization>>(\n `admin/organizations?${params.toString()}`\n );\n }\n\n /**\n * Get organization by ID or UUID.\n * Returns different response based on user's role:\n * - Admins/Owners: AdminOrganization with full details\n * - Members: MemberOrgView with basic info and workspace list\n *\n * Use `viewType` field to determine the response type:\n * - 'admin': AdminOrganization\n * - 'member': MemberOrgView\n */\n async getOrganization(idOrUuid: number | string): Promise<AdminOrganization | MemberOrgView> {\n return this.fetch<AdminOrganization | MemberOrgView>(`o/${idOrUuid}`);\n }\n\n /**\n * Get organization by numeric ID or UUID via admin endpoint.\n * Does NOT require organization membership — superuser-only.\n */\n async getOrganizationAsAdmin(idOrUuid: number | string): Promise<AdminOrganization> {\n return this.fetch<AdminOrganization>(`admin/organizations/${idOrUuid}`);\n }\n\n async getOrganizationMembersAsAdmin(\n organizationId: number,\n options?: { search?: string; role?: string; page?: number; pageSize?: number }\n ): Promise<PaginatedResponse<OrgMember>> {\n const params = new URLSearchParams();\n if (options?.search) params.append('search', options.search);\n if (options?.role) params.append('role', options.role);\n if (options?.page) params.append('page', options.page.toString());\n if (options?.pageSize) params.append('pageSize', options.pageSize.toString());\n const qs = params.toString();\n return this.fetch<PaginatedResponse<OrgMember>>(\n `admin/organizations/${organizationId}/members${qs ? `?${qs}` : ''}`\n );\n }\n\n async createOrganization(data: CreateOrganizationRequest): Promise<AdminOrganization> {\n return this.fetch<AdminOrganization>('admin/organizations', {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateOrganization(\n id: number,\n data: UpdateOrganizationRequest\n ): Promise<AdminOrganization> {\n return this.fetch<AdminOrganization>(`admin/organizations/${id}`, {\n method: 'PUT',\n body: JSON.stringify(data),\n });\n }\n\n async deleteOrganization(id: number): Promise<void> {\n return this.fetch(`admin/organizations/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * Join an organization with a specified role (superuser only).\n * Creates or updates membership in the target org.\n * @param orgUuid - Organization UUID or numeric ID as string\n */\n async joinOrganization(\n orgUuid: string,\n role: 'member' | 'admin' | 'owner' = 'owner'\n ): Promise<{\n accountId: number;\n organizationId: number;\n organizationUuid: string;\n email: string | null;\n role: string;\n message: string;\n }> {\n return this.fetch(`admin/organizations/${orgUuid}/join`, {\n method: 'POST',\n body: JSON.stringify({ role }),\n });\n }\n\n /**\n * Leave an organization (superuser only).\n * @param orgUuid - Organization UUID or numeric ID as string\n */\n async leaveOrganization(orgUuid: string): Promise<{ status: string; message: string }> {\n return this.fetch(`admin/organizations/${orgUuid}/join`, {\n method: 'DELETE',\n });\n }\n\n async generateLogoUploadUrl(\n organizationUuid: string,\n data: LogoUploadRequest\n ): Promise<LogoUploadResponse> {\n return this.fetch<LogoUploadResponse>(`o/${organizationUuid}/logo-upload-url`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n // Organization Members API - moved to OrgApi at /api/v2/o/{org_uuid}/members\n // See packages/client/src/api/org.ts\n\n // Organization Invitations API - moved to OrgApi at /api/v2/o/{org_uuid}/invitations\n // See packages/client/src/api/org.ts\n\n // Admin Products API\n async importProducts(workspaceId: number): Promise<void> {\n return this.fetch('admin/import-products', {\n method: 'POST',\n body: JSON.stringify({ workspaceId }),\n });\n }\n\n // ===== Product CRUD =====\n\n async createProductAsAdmin(product: CreateProductRequest): Promise<Product> {\n return this.fetch<Product>('admin/products', {\n method: 'POST',\n body: JSON.stringify(product),\n });\n }\n\n async getProductsAsAdmin(workspaceUuid?: string, productTypes?: string[]): Promise<Product[]> {\n const params = new URLSearchParams();\n if (workspaceUuid) {\n params.append('workspace_uuid', workspaceUuid);\n }\n if (productTypes && productTypes.length > 0) {\n productTypes.forEach((type) => params.append('product_types', type));\n }\n const queryString = params.toString();\n return this.fetch<Product[]>(`admin/products${queryString ? `?${queryString}` : ''}`);\n }\n\n async getProductAsAdmin(productId: number): Promise<Product> {\n return this.fetch<Product>(`admin/products/${productId}`);\n }\n\n async updateProductAsAdmin(\n product_id: number,\n product: AdminUpdateProductRequest\n ): Promise<Product> {\n return this.fetch<Product>(`admin/products/${product_id}`, {\n method: 'PUT',\n body: JSON.stringify(product),\n });\n }\n\n async deleteProductAsAdmin(productId: number): Promise<{ message: string }> {\n return this.fetch<{ message: string }>(`admin/products/${productId}`, {\n method: 'DELETE',\n });\n }\n\n // Admin Workspace API\n async getWorkspacesAsAdmin(\n options: {\n page?: number;\n pageSize?: number;\n sortBy?: WorkspaceSortField;\n sortOrder?: SortOrder;\n search?: string;\n isReseller?: boolean;\n organizationId?: number;\n noActiveSubscription?: boolean;\n } = {}\n ): Promise<PaginatedResponse<AdminWorkspace>> {\n const params = new URLSearchParams();\n if (options.page !== undefined) params.append('page', options.page.toString());\n if (options.pageSize !== undefined) params.append('pageSize', options.pageSize.toString());\n if (options.sortBy) params.append('sortBy', options.sortBy);\n if (options.sortOrder) params.append('sortOrder', options.sortOrder);\n if (options.search) params.append('search', options.search);\n if (options.isReseller !== undefined)\n params.append('isReseller', options.isReseller.toString());\n if (options.organizationId !== undefined)\n params.append('organizationId', options.organizationId.toString());\n if (options.noActiveSubscription) params.append('noActiveSubscription', 'true');\n\n return this.fetch<PaginatedResponse<AdminWorkspace>>(`admin/workspaces?${params.toString()}`);\n }\n\n async getWorkspaceAsAdmin(wid: string): Promise<AdminWorkspace> {\n return this.fetch<AdminWorkspace>(`admin/workspaces/${wid}`);\n }\n\n async getWorkspaceByNumericIdAsAdmin(workspace_id: number): Promise<AdminWorkspace> {\n return this.fetch<AdminWorkspace>(`admin/workspaces/id/${workspace_id}`);\n }\n\n async createWorkspaceAsAdmin(ws: AdminWorkspaceFormData): Promise<Workspace> {\n return this.fetch<Workspace>('admin/workspaces', {\n method: 'POST',\n body: JSON.stringify(ws),\n });\n }\n\n async updateWorkspaceAsAdmin(wid: string, ws: AdminWorkspaceFormData): Promise<Workspace> {\n return this.fetch<Workspace>(`admin/workspaces/${wid}`, {\n method: 'PUT',\n body: JSON.stringify(ws),\n });\n }\n\n async deleteWorkspaceAsAdmin(wid: string): Promise<void> {\n return this.fetch(`admin/workspaces/${wid}`, {\n method: 'DELETE',\n });\n }\n\n async createSchemaAsAdmin(wid: string): Promise<AdminWorkspace> {\n return this.fetch(`admin/workspaces/${wid}/provision/create`, {\n method: 'POST',\n });\n }\n\n async migrateSchemaAsAdmin(wid: string): Promise<AdminWorkspace> {\n return this.fetch(`admin/workspaces/${wid}/provision/migrate`, {\n method: 'POST',\n });\n }\n\n async provisionWorkspaceAsAdmin(wid: string): Promise<AdminWorkspace> {\n return this.fetch(`admin/workspaces/${wid}/provision`, {\n method: 'POST',\n });\n }\n\n async refreshProvisionStatusAsAdmin(wid: string): Promise<AdminWorkspace> {\n return this.fetch(`admin/workspaces/${wid}/provision/refresh`, {\n method: 'POST',\n });\n }\n\n async enableMaintenanceMode(wid: string): Promise<AdminWorkspace> {\n return this.fetch(`admin/workspaces/${wid}/maintenance`, {\n method: 'PUT',\n });\n }\n\n async disableMaintenanceMode(wid: string): Promise<AdminWorkspace> {\n return this.fetch(`admin/workspaces/${wid}/maintenance`, {\n method: 'DELETE',\n });\n }\n\n // ===== Workspace Health Check =====\n\n async getWorkspaceHealth(workspaceUuid: string): Promise<WorkspaceHealthResponse> {\n return this.fetch<WorkspaceHealthResponse>(`admin/workspaces/${workspaceUuid}/health`);\n }\n\n async provisionPlanFeatures(\n workspaceUuid: string,\n request?: ProvisionPlanRequest\n ): Promise<ProvisionPlanResponse> {\n return this.fetch<ProvisionPlanResponse>(`admin/workspaces/${workspaceUuid}/provision-plan`, {\n method: 'POST',\n body: JSON.stringify(request || {}),\n });\n }\n\n /**\n * Switch a workspace's plan product on its active SubscriptionItem.\n *\n * Superuser only. Re-syncs ``workspace.features`` from the new product\n * and emits a ``WORKSPACE_PRODUCT_CHANGED`` audit event identifying the\n * actor, target workspace, prior and new product, and feature diff.\n *\n * Stripe is not touched here; price-id changes belong to the dedicated\n * Stripe sync surface (``syncProductToStripe``).\n */\n async changeWorkspaceProduct(\n workspaceUuid: string,\n productId: number\n ): Promise<ChangeWorkspaceProductResponse> {\n const body: ChangeWorkspaceProductRequest = { productId };\n return this.fetch<ChangeWorkspaceProductResponse>(\n `admin/workspaces/${workspaceUuid}/product`,\n {\n method: 'POST',\n body: JSON.stringify(body),\n }\n );\n }\n\n // ===== Workflow Access Validation =====\n\n async validateWorkflowAccessAsAdmin(\n workspaceUuid?: string\n ): Promise<AdminBulkWorkflowAccessValidationResponse> {\n const params = new URLSearchParams();\n if (workspaceUuid) params.append('workspace_uuid', workspaceUuid);\n const qs = params.toString();\n return this.fetch<AdminBulkWorkflowAccessValidationResponse>(\n `admin/workspaces/validate-workflow-access${qs ? `?${qs}` : ''}`\n );\n }\n\n async mergeMembers(wid: string, request: MergeMembersRequest): Promise<MergeMembersResponse> {\n return this.fetch<MergeMembersResponse>(`admin/workspaces/${wid}/merge-members`, {\n method: 'POST',\n body: JSON.stringify(request),\n });\n }\n\n async getAdminWorkspaceMember(wid: string): Promise<Member> {\n return this.fetch(`admin/workspaces/${wid}/me`, {\n method: 'GET',\n });\n }\n\n async createAdminWorkspaceMember(\n wid: string,\n data: AdminWorkspaceMemberFormData\n ): Promise<void> {\n return this.fetch(`admin/workspaces/${wid}/me`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateAdminWorkspaceMember(\n wid: string,\n data: AdminWorkspaceMemberFormData\n ): Promise<void> {\n return this.fetch(`admin/workspaces/${wid}/me`, {\n method: 'PUT',\n body: JSON.stringify(data),\n });\n }\n\n async unarchiveAdminWorkspaceMember(wid: string): Promise<Member> {\n return this.fetch(`admin/workspaces/${wid}/me/unarchive`, {\n method: 'POST',\n });\n }\n\n async getAdminWorkspaceMemberRoles(wid: string): Promise<MemberRole[]> {\n return this.fetch<MemberRole[]>(`admin/workspaces/${wid}/member-roles`);\n }\n\n async getUnmappedPhoneNumbers(): Promise<UnmappedPhoneNumber[]> {\n return this.fetch<UnmappedPhoneNumber[]>(`admin/phone-numbers/unmapped`);\n }\n\n async getWorkspaceUnmappedPhoneNumbers(workspaceId: number): Promise<UnmappedPhoneNumber[]> {\n return this.fetch<UnmappedPhoneNumber[]>(\n `admin/phone-numbers/workspace/${workspaceId}/unmapped`\n );\n }\n\n async getWorkspacePhoneNumbersAsAdmin(workspaceRef: string): Promise<PhoneNumber[]> {\n return this.fetch<PhoneNumber[]>(`admin/workspaces/${workspaceRef}/phone-numbers`);\n }\n\n // Phone Numbers API (Provider phone numbers from Twilio, AWS, etc.)\n async getProviderPhoneNumbers(\n options: {\n search?: string;\n isAssigned?: boolean;\n provider?: string;\n organizationId?: number;\n sortBy?: string;\n sortOrder?: string;\n page?: number;\n pageSize?: number;\n } = {}\n ): Promise<PaginatedResponse<ProviderPhoneNumber>> {\n const params = new URLSearchParams();\n if (options.page) params.append('page', options.page.toString());\n if (options.pageSize) params.append('pageSize', options.pageSize.toString());\n if (options.search) params.append('search', options.search);\n if (options.isAssigned !== undefined)\n params.append('is_assigned', String(options.isAssigned));\n if (options.provider) params.append('provider', options.provider);\n if (options.organizationId !== undefined)\n params.append('organizationId', options.organizationId.toString());\n if (options.sortBy) params.append('sortBy', options.sortBy);\n if (options.sortOrder) params.append('sortOrder', options.sortOrder);\n\n return this.fetch<PaginatedResponse<ProviderPhoneNumber>>(\n `admin/phone-numbers${params.toString() ? `?${params.toString()}` : ''}`\n );\n }\n\n async getProviderPhoneNumber(id: number): Promise<ProviderPhoneNumber> {\n return this.fetch<ProviderPhoneNumber>(`admin/phone-numbers/${id}`);\n }\n\n async updateProviderPhoneNumber(\n id: number,\n data: { organizationId: number | null }\n ): Promise<ProviderPhoneNumber> {\n return this.fetch<ProviderPhoneNumber>(`admin/phone-numbers/${id}`, {\n method: 'PATCH',\n body: JSON.stringify(data),\n });\n }\n\n async mapMainAccountPhone(data: {\n phoneNumber: string;\n workspaceUuid: string;\n name?: string;\n }): Promise<ProviderPhoneNumber> {\n return this.fetch<ProviderPhoneNumber>(`admin/phone-numbers/map-from-main-account`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async unmapPhoneNumber(data: {\n phoneNumber: string;\n }): Promise<{ status: string; phoneNumber: string }> {\n return this.fetch<{ status: string; phoneNumber: string }>(`admin/phone-numbers/unmap`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async searchAvailablePhoneNumbersAsAdmin(data: {\n organizationId: number;\n country?: string;\n numberType?: string;\n areaCode?: string;\n contains?: string;\n limit?: number;\n }): Promise<\n Array<{\n phoneNumber: string;\n friendlyName: string;\n locality: string | null;\n region: string | null;\n isoCountry: string;\n voiceEnabled: boolean;\n smsEnabled: boolean;\n }>\n > {\n return this.fetch(`admin/phone-numbers/search`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async purchasePhoneNumberAsAdmin(data: {\n organizationId: number;\n phoneNumber: string;\n numberType?: string;\n }): Promise<ProviderPhoneNumber> {\n return this.fetch<ProviderPhoneNumber>(`admin/phone-numbers/purchase`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async getOrgA2PStatusAsAdmin(organizationId: number): Promise<OrgA2PStatus> {\n return this.fetch<OrgA2PStatus>(`admin/organizations/${organizationId}/a2p-status`);\n }\n\n async resetOrgA2PStatusAsAdmin(organizationId: number): Promise<{ status: string }> {\n return this.fetch(`admin/organizations/${organizationId}/a2p-status`, {\n method: 'DELETE',\n });\n }\n\n // Site Mappings API\n async getSiteMappings(options?: {\n search?: string;\n page?: number;\n pageSize?: number;\n }): Promise<PaginatedResponse<SiteMapping>> {\n const queryParams = new URLSearchParams();\n if (options?.search) queryParams.append('search', options.search);\n if (options?.page) queryParams.append('page', options.page.toString());\n if (options?.pageSize) queryParams.append('pageSize', options.pageSize.toString());\n\n const queryString = queryParams.toString();\n const url = `admin/site-mappings${queryString ? `?${queryString}` : ''}`;\n\n return this.fetch<PaginatedResponse<SiteMapping>>(url);\n }\n\n async getSiteMapping(siteId: number): Promise<SiteMapping> {\n return this.fetch<SiteMapping>(`admin/site-mappings/${siteId}`);\n }\n\n async updateSiteMapping(siteId: number, data: SiteMappingFormData): Promise<SiteMapping> {\n return this.fetch<SiteMapping>(`admin/site-mappings/${siteId}`, {\n method: 'PUT',\n body: JSON.stringify(data),\n });\n }\n\n async updateSiteMappingWorkspace(siteId: number, workspaceId: number): Promise<SiteMapping> {\n return this.updateSiteMapping(siteId, {\n workspaceId,\n siteUuid: '', // These fields are required by the type but will be ignored on the server\n });\n }\n\n async adminDeleteSiteMapping(siteId: number): Promise<void> {\n return this.fetch<void>(`admin/site-mappings/${siteId}`, {\n method: 'DELETE',\n });\n }\n\n async createSiteMapping(mapping: SiteMappingFormData): Promise<SiteMapping> {\n return this.fetch<SiteMapping>(`admin/site-mappings`, {\n method: 'POST',\n body: JSON.stringify(mapping),\n });\n }\n\n // Keep for backward compatibility\n async createOrUpdateSiteMapping(\n wid: string,\n mapping: SiteMappingFormData\n ): Promise<SiteMapping> {\n return this.fetch<SiteMapping>(`admin/workspaces/${wid}/site-mappings`, {\n method: 'POST',\n body: JSON.stringify(mapping),\n });\n }\n\n async deleteSiteMapping(wid: string, siteUuid: string): Promise<void> {\n return this.fetch(`admin/workspaces/${wid}/site-mappings/${siteUuid}`, {\n method: 'DELETE',\n });\n }\n\n async getWorkspaceInboxesAsAdmin(\n workspaceUuid: string\n ): Promise<{ items: Inbox[]; total: number }> {\n return this.fetch<{ items: Inbox[]; total: number }>(\n `admin/workspaces/${workspaceUuid}/inboxes`\n );\n }\n\n // Admin Inbox Mappings API\n async getInboxMappings(\n options: {\n page?: number;\n pageSize?: number;\n search?: string;\n workspaceId?: number;\n } = {}\n ): Promise<PaginatedResponse<InboxMappingDetailResponse>> {\n const params = new URLSearchParams();\n if (options.page) params.append('page', options.page.toString());\n if (options.pageSize) params.append('pageSize', options.pageSize.toString());\n if (options.search) params.append('search', options.search);\n if (options.workspaceId) params.append('workspaceId', options.workspaceId.toString());\n\n return this.fetch<PaginatedResponse<InboxMappingDetailResponse>>(\n `admin/inbox-mappings${params.toString() ? `?${params.toString()}` : ''}`\n );\n }\n\n async getInboxMapping(id: number): Promise<InboxMappingDetailResponse> {\n return this.fetch<InboxMappingDetailResponse>(`admin/inbox-mappings/${id}`);\n }\n\n async updateInboxMapping(id: number, workspaceId: number): Promise<InboxMappingDetailResponse> {\n return this.fetch<InboxMappingDetailResponse>(`admin/inbox-mappings/${id}`, {\n method: 'PUT',\n body: JSON.stringify({ workspaceId }),\n });\n }\n\n async deleteAdminInboxMapping(id: number): Promise<void> {\n return this.fetch(`admin/inbox-mappings/${id}`, {\n method: 'DELETE',\n });\n }\n\n // Evaluation API\n async generateChatSummaries(options: {\n afterDate?: Date;\n onlyWithoutSummaries?: boolean;\n }): Promise<GenerateSummariesResponse> {\n return this.fetch<GenerateSummariesResponse>('admin/generate-summaries', {\n method: 'POST',\n body: JSON.stringify({\n after_date: options.afterDate\n ? options.afterDate.toISOString().split('T')[0] +\n 'T' +\n options.afterDate.toTimeString().split(' ')[0]\n : undefined,\n only_without_summaries: options.onlyWithoutSummaries ?? true,\n }),\n });\n }\n\n async executeQuery(options: { query: string; workspaceUuid?: string }): Promise<{\n columns: string[];\n rows: any[][];\n rowCount: number;\n }> {\n return this.fetch<{\n columns: string[];\n rows: any[][];\n rowCount: number;\n }>('admin/execute-query', {\n method: 'POST',\n body: JSON.stringify({\n query: options.query,\n workspace_uuid: options.workspaceUuid,\n }),\n });\n }\n\n /**\n * Resolve a Langfuse trace UI URL from a trace ID, chat ID, or message ID.\n *\n * URL-only: never fetches Langfuse payloads, Message content, or\n * tool arguments. Exactly one of ``traceId``, ``chatId``, or\n * ``messageId`` must be set; chat/message forms require a\n * workspaceUuid. See\n * docs/development/observability/llm-call-investigation.md.\n */\n async getTraceUrl(options: {\n traceId?: string;\n chatId?: number;\n messageId?: string;\n workspaceUuid?: string;\n }): Promise<{\n trace_id: string | null;\n observation_id: string | null;\n langfuse_url: string | null;\n }> {\n return this.fetch<{\n trace_id: string | null;\n observation_id: string | null;\n langfuse_url: string | null;\n }>('admin/trace/url', {\n method: 'POST',\n body: JSON.stringify({\n trace_id: options.traceId,\n chat_id: options.chatId,\n message_id: options.messageId,\n workspace_uuid: options.workspaceUuid,\n }),\n });\n }\n\n // Admin Themes API\n async listAllThemes(): Promise<ThemesListResponse> {\n return this.fetch<ThemesListResponse>('admin/themes/list');\n }\n\n // Missing Memberships API\n async getMissingMemberships(workspaceId: string): Promise<MissingMembershipItem[]> {\n return this.fetch<MissingMembershipItem[]>(\n `admin/workspaces/${workspaceId}/missing-memberships`\n );\n }\n\n async linkMissingMembership(\n workspaceId: string,\n memberId: number,\n accountId: number\n ): Promise<{ success: boolean; message: string }> {\n return this.fetch<{ success: boolean; message: string }>(\n `admin/workspaces/${workspaceId}/link-membership?member_id=${memberId}&account_id=${accountId}`,\n {\n method: 'POST',\n }\n );\n }\n\n // Bulk Phone Classification API\n async startBulkPhoneClassification(\n workspaceUuid: string,\n includeUnknown: boolean = false\n ): Promise<{\n success: boolean;\n message: string;\n job_id: string;\n workspace_uuid: string;\n include_unknown: boolean;\n }> {\n const params = new URLSearchParams();\n params.append('include_unknown', includeUnknown.toString());\n\n return this.fetch<{\n success: boolean;\n message: string;\n job_id: string;\n workspace_uuid: string;\n include_unknown: boolean;\n }>(`admin/workspaces/${workspaceUuid}/bulk-classify-phones?${params.toString()}`, {\n method: 'POST',\n });\n }\n\n // Bulk TOS Acceptance API\n async startBulkTOSAcceptance(workspaceUuid: string): Promise<{\n success: boolean;\n message: string;\n updated_count: number;\n workspace_uuid: string;\n }> {\n return this.fetch<{\n success: boolean;\n message: string;\n updated_count: number;\n workspace_uuid: string;\n }>(`admin/workspaces/${workspaceUuid}/bulk-accept-tos`, {\n method: 'POST',\n });\n }\n\n // Token Usage Backfill API\n async startTokenUsageBackfill(workspaceUuid: string): Promise<{\n success: boolean;\n message: string;\n job_id: string;\n workspace_uuid: string;\n }> {\n return this.fetch<{\n success: boolean;\n message: string;\n job_id: string;\n workspace_uuid: string;\n }>(`admin/workspaces/${workspaceUuid}/backfill-token-usage`, {\n method: 'POST',\n });\n }\n\n // ===== Admin Chat Endpoints =====\n\n async listWorkspaceChats(\n workspaceUuid: string,\n options?: AdminChatsOptions\n ): Promise<PaginatedResponse<AdminChat>> {\n const params = new URLSearchParams();\n if (options?.page) params.set('page', String(options.page));\n if (options?.pageSize) params.set('pageSize', String(options.pageSize));\n if (options?.search) params.set('search', options.search);\n if (options?.chatType) params.set('chatType', options.chatType);\n if (options?.channel) params.set('channel', options.channel);\n if (options?.archived !== undefined) params.set('archived', String(options.archived));\n const qs = params.toString();\n return this.fetch<PaginatedResponse<AdminChat>>(\n `admin/workspaces/${workspaceUuid}/chats${qs ? `?${qs}` : ''}`\n );\n }\n\n async getWorkspaceChat(\n workspaceUuid: string,\n chatId: number,\n options?: { page?: number; pageSize?: number }\n ): Promise<AdminChatDetail> {\n const params = new URLSearchParams();\n if (options?.page) params.set('page', String(options.page));\n if (options?.pageSize) params.set('pageSize', String(options.pageSize));\n const qs = params.toString();\n return this.fetch<AdminChatDetail>(\n `admin/workspaces/${workspaceUuid}/chats/${chatId}${qs ? `?${qs}` : ''}`\n );\n }\n\n // Update chat message content\n async updateChatMessage(\n workspaceUuid: string,\n chatId: number,\n messageId: string,\n content: string\n ): Promise<{\n success: boolean;\n message: string;\n messageId: string;\n chatId: number;\n workspaceUuid: string;\n }> {\n return this.fetch<{\n success: boolean;\n message: string;\n messageId: string;\n chatId: number;\n workspaceUuid: string;\n }>(`admin/workspaces/${workspaceUuid}/chats/${chatId}/messages/${messageId}`, {\n method: 'POST',\n body: JSON.stringify({ content }),\n });\n }\n\n async rateWorkspaceChatMessage(\n workspaceUuid: string,\n chatId: number,\n messageId: string,\n rating: number,\n comment?: string\n ): Promise<{ status: string; detail?: string }> {\n return this.fetch<{ status: string; detail?: string }>(\n `admin/workspaces/${workspaceUuid}/chats/${chatId}/messages/${messageId}/rate`,\n {\n method: 'POST',\n body: JSON.stringify({ rating, comment }),\n }\n );\n }\n\n // ===== Stripe Customer Management =====\n\n async getStripeCustomer(accountId: number): Promise<StripeCustomer> {\n return this.fetch<StripeCustomer>(`admin/accounts/${accountId}/stripe/customer`);\n }\n\n async createStripeCustomer(\n accountId: number,\n data: StripeCustomerCreateRequest\n ): Promise<StripeCustomer> {\n return this.fetch<StripeCustomer>(`admin/accounts/${accountId}/stripe/customer`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateStripeCustomer(\n accountId: number,\n data: StripeCustomerUpdateRequest\n ): Promise<StripeCustomer> {\n return this.fetch<StripeCustomer>(`admin/accounts/${accountId}/stripe/customer`, {\n method: 'PUT',\n body: JSON.stringify(data),\n });\n }\n\n // ===== Customer Management =====\n\n async createCustomerFromAccount(accountId: number): Promise<Customer> {\n return this.fetch<Customer>(`admin/accounts/${accountId}/customer`, {\n method: 'POST',\n });\n }\n\n async getCustomers(options?: {\n search?: string;\n page?: number;\n pageSize?: number;\n }): Promise<PaginatedResponse<Customer>> {\n const params = new URLSearchParams();\n if (options?.search) params.set('search', options.search);\n if (options?.page) params.set('page', String(options.page));\n if (options?.pageSize) params.set('page_size', String(options.pageSize));\n const qs = params.toString();\n return this.fetch<PaginatedResponse<Customer>>(`admin/customers${qs ? `?${qs}` : ''}`);\n }\n\n async getCustomer(customerId: number): Promise<Customer> {\n return this.fetch<Customer>(`admin/customers/${customerId}`);\n }\n\n async createCustomer(data: CreateCustomerRequest): Promise<Customer> {\n return this.fetch<Customer>('admin/customers', {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateCustomer(customerId: number, data: UpdateCustomerRequest): Promise<Customer> {\n return this.fetch<Customer>(`admin/customers/${customerId}`, {\n method: 'PUT',\n body: JSON.stringify(data),\n });\n }\n\n async syncCustomerToStripe(customerId: number): Promise<Customer> {\n return this.fetch<Customer>(`admin/customers/${customerId}/stripe/sync`, {\n method: 'POST',\n });\n }\n\n async getCustomerAccounts(customerId: number): Promise<CustomerAccount[]> {\n return this.fetch<CustomerAccount[]>(`admin/customers/${customerId}/accounts`);\n }\n\n async linkCustomerToAccount(\n customerId: number,\n accountId: number,\n role?: string\n ): Promise<CustomerAccount> {\n return this.fetch<CustomerAccount>(`admin/customers/${customerId}/accounts`, {\n method: 'POST',\n body: JSON.stringify({ accountId, role }),\n });\n }\n\n async unlinkCustomerFromAccount(customerId: number, accountId: number): Promise<void> {\n await this.fetch<void>(`admin/customers/${customerId}/accounts/${accountId}`, {\n method: 'DELETE',\n });\n }\n\n // ===== Stripe Subscription Management =====\n\n async getStripeSubscriptions(accountId: number): Promise<Subscription[]> {\n return this.fetch<Subscription[]>(`admin/accounts/${accountId}/stripe/subscriptions`);\n }\n\n async createStripeSubscription(\n customerId: number,\n data: StripeSubscriptionCreateRequest\n ): Promise<Subscription> {\n return this.fetch<Subscription>(`admin/customers/${customerId}/stripe/subscriptions`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async createDirectSubscription(\n customerId: number,\n data: DirectSubscriptionCreateRequest\n ): Promise<Subscription> {\n return this.fetch<Subscription>(`admin/customers/${customerId}/direct/subscriptions`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateStripeSubscription(\n accountId: number,\n subscriptionId: string,\n data: StripeSubscriptionUpdateRequest\n ): Promise<Subscription> {\n return this.fetch<Subscription>(\n `admin/accounts/${accountId}/stripe/subscriptions/${subscriptionId}`,\n {\n method: 'PUT',\n body: JSON.stringify(data),\n }\n );\n }\n\n async cancelStripeSubscription(\n accountId: number,\n subscriptionId: string\n ): Promise<{ message: string; status: string }> {\n return this.fetch<{ message: string; status: string }>(\n `admin/accounts/${accountId}/stripe/subscriptions/${subscriptionId}`,\n {\n method: 'DELETE',\n }\n );\n }\n\n async provisionWorkspaceForSubscription(\n accountId: number,\n subscriptionId: string\n ): Promise<AdminWorkspace> {\n return this.fetch<AdminWorkspace>(\n `admin/accounts/${accountId}/stripe/subscriptions/${subscriptionId}/provision`,\n {\n method: 'POST',\n }\n );\n }\n\n async associateWorkspaceWithSubscription(\n accountId: number,\n subscriptionId: string,\n workspaceId: string | number\n ): Promise<Subscription> {\n return this.fetch<Subscription>(\n `admin/accounts/${accountId}/stripe/subscriptions/${subscriptionId}/associate?workspace_id=${workspaceId}`,\n {\n method: 'POST',\n }\n );\n }\n\n async createSubscriptionPaymentLink(\n accountId: number,\n subscriptionId: string\n ): Promise<{\n needsPayment: boolean;\n paymentUrl?: string;\n amountDue?: number;\n currency?: string;\n status: string;\n invoiceId?: string;\n invoiceStatus?: string;\n dueDate?: number;\n message?: string;\n }> {\n return this.fetch<{\n needsPayment: boolean;\n paymentUrl?: string;\n amountDue?: number;\n currency?: string;\n status: string;\n invoiceId?: string;\n invoiceStatus?: string;\n dueDate?: number;\n message?: string;\n }>(`admin/accounts/${accountId}/stripe/subscriptions/${subscriptionId}/payment-link`, {\n method: 'POST',\n });\n }\n\n // ===== Stripe Payment Methods Management =====\n\n async createSetupIntent(accountId: number): Promise<{\n clientSecret: string;\n setupIntentId: string;\n status: string;\n }> {\n return this.fetch<{\n clientSecret: string;\n setupIntentId: string;\n status: string;\n }>(`admin/accounts/${accountId}/stripe/setup-intent`, {\n method: 'POST',\n });\n }\n\n async getStripePaymentMethods(accountId: number): Promise<StripePaymentMethod[]> {\n return this.fetch<StripePaymentMethod[]>(\n `admin/accounts/${accountId}/stripe/payment-methods`\n );\n }\n\n async attachStripePaymentMethod(\n accountId: number,\n paymentMethodId: string,\n setAsDefault: boolean = false\n ): Promise<{\n success: boolean;\n message: string;\n paymentMethodId: string;\n type: string;\n }> {\n return this.fetch<{\n success: boolean;\n message: string;\n paymentMethodId: string;\n type: string;\n }>(`admin/accounts/${accountId}/stripe/payment-methods/${paymentMethodId}/attach`, {\n method: 'POST',\n body: JSON.stringify({ setAsDefault }),\n });\n }\n\n async detachStripePaymentMethod(\n accountId: number,\n paymentMethodId: string\n ): Promise<{ success: string; message: string }> {\n return this.fetch<{ success: string; message: string }>(\n `admin/accounts/${accountId}/stripe/payment-methods/${paymentMethodId}`,\n {\n method: 'DELETE',\n }\n );\n }\n\n async setDefaultStripePaymentMethod(\n accountId: number,\n paymentMethodId: string\n ): Promise<{ success: string; message: string }> {\n return this.fetch<{ success: string; message: string }>(\n `admin/accounts/${accountId}/stripe/payment-methods/${paymentMethodId}/set-default`,\n {\n method: 'PUT',\n }\n );\n }\n\n // ===== Convert Direct Subscription to Stripe =====\n\n async convertSubscriptionToStripe(\n customerId: number,\n subscriptionId: number\n ): Promise<Subscription> {\n return this.fetch<Subscription>(\n `admin/customers/${customerId}/subscriptions/${subscriptionId}/convert-to-stripe`,\n { method: 'POST' }\n );\n }\n\n // ===== Customer-Level Stripe Payment Methods =====\n\n async createCustomerSetupIntent(customerId: number): Promise<{\n clientSecret: string;\n setupIntentId: string;\n status: string;\n }> {\n return this.fetch<{\n clientSecret: string;\n setupIntentId: string;\n status: string;\n }>(`admin/customers/${customerId}/stripe/setup-intent`, {\n method: 'POST',\n });\n }\n\n async getCustomerPaymentMethods(customerId: number): Promise<StripePaymentMethod[]> {\n return this.fetch<StripePaymentMethod[]>(\n `admin/customers/${customerId}/stripe/payment-methods`\n );\n }\n\n async attachCustomerPaymentMethod(\n customerId: number,\n paymentMethodId: string,\n setAsDefault: boolean = false\n ): Promise<{\n success: boolean;\n message: string;\n paymentMethodId: string;\n type: string;\n }> {\n return this.fetch<{\n success: boolean;\n message: string;\n paymentMethodId: string;\n type: string;\n }>(`admin/customers/${customerId}/stripe/payment-methods/${paymentMethodId}/attach`, {\n method: 'POST',\n body: JSON.stringify({ setAsDefault }),\n });\n }\n\n async detachCustomerPaymentMethod(\n customerId: number,\n paymentMethodId: string\n ): Promise<{ success: string; message: string }> {\n return this.fetch<{ success: string; message: string }>(\n `admin/customers/${customerId}/stripe/payment-methods/${paymentMethodId}`,\n {\n method: 'DELETE',\n }\n );\n }\n\n async setDefaultCustomerPaymentMethod(\n customerId: number,\n paymentMethodId: string\n ): Promise<{ success: string; message: string }> {\n return this.fetch<{ success: string; message: string }>(\n `admin/customers/${customerId}/stripe/payment-methods/${paymentMethodId}/set-default`,\n {\n method: 'PUT',\n }\n );\n }\n\n // ===== Workspace Organization Migration =====\n\n async previewWorkspaceOrganizationChange(\n workspaceUuid: string,\n targetOrganizationId: number,\n newCreatorId: number\n ): Promise<{\n targetOrganization: { id: number; name: string };\n newCreator: { id: number; name: string; email: string };\n currentOrganization: { id: number | null; name: string | null };\n impact: {\n accountsToMove: number;\n accountsToDuplicate: number;\n accountsToRemap: number;\n totalMembers: number;\n };\n details: {\n movableAccounts: Array<{\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n }>;\n duplicateAccounts: Array<{\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n }>;\n remappableAccounts: Array<{\n currentAccount: {\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n };\n targetAccount: {\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n };\n }>;\n };\n }> {\n return this.fetch<{\n targetOrganization: { id: number; name: string };\n newCreator: { id: number; name: string; email: string };\n currentOrganization: { id: number | null; name: string | null };\n impact: {\n accountsToMove: number;\n accountsToDuplicate: number;\n accountsToRemap: number;\n totalMembers: number;\n };\n details: {\n movableAccounts: Array<{\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n }>;\n duplicateAccounts: Array<{\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n }>;\n remappableAccounts: Array<{\n currentAccount: {\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n };\n targetAccount: {\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n };\n }>;\n };\n }>(`admin/workspaces/${workspaceUuid}/change-org/preview`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n targetOrganizationId,\n newCreatorId,\n }),\n });\n }\n\n async changeWorkspaceOrganization(\n workspaceUuid: string,\n targetOrganizationId: number,\n newCreatorId: number\n ): Promise<{\n success: boolean;\n workspace: {\n uuid: string;\n name: string;\n organizationId: number;\n creatorId: number;\n };\n migration: {\n accountsMoved: number;\n accountsCreated: number;\n accountsRemapped: number;\n };\n }> {\n return this.fetch<{\n success: boolean;\n workspace: {\n uuid: string;\n name: string;\n organizationId: number;\n creatorId: number;\n };\n migration: {\n accountsMoved: number;\n accountsCreated: number;\n accountsRemapped: number;\n };\n }>(`admin/workspaces/${workspaceUuid}/change-org`, {\n method: 'POST',\n body: JSON.stringify({\n targetOrganizationId,\n newCreatorId,\n }),\n });\n }\n\n // ===== Stripe Invoice Management =====\n\n async createStripeInvoice(\n accountId: number,\n data: {\n customer: string;\n description?: string;\n collectionMethod: 'charge_automatically' | 'send_invoice';\n daysUntilDue?: number;\n autoAdvance?: boolean;\n metadata?: Record<string, string>;\n }\n ): Promise<{\n id: string;\n number: string;\n status: string;\n collectionMethod: string;\n amountDue: number;\n amountPaid: number;\n amountRemaining: number;\n currency: string;\n created: number;\n dueDate: number | null;\n paid: boolean;\n hostedInvoiceUrl: string | null;\n invoicePdf: string | null;\n customerEmail: string | null;\n description: string | null;\n }> {\n return this.fetch<{\n id: string;\n number: string;\n status: string;\n collectionMethod: string;\n amountDue: number;\n amountPaid: number;\n amountRemaining: number;\n currency: string;\n created: number;\n dueDate: number | null;\n paid: boolean;\n hostedInvoiceUrl: string | null;\n invoicePdf: string | null;\n customerEmail: string | null;\n description: string | null;\n }>(`admin/accounts/${accountId}/stripe/invoices`, {\n method: 'POST',\n body: JSON.stringify({\n customer: data.customer,\n description: data.description,\n collection_method: data.collectionMethod,\n days_until_due: data.daysUntilDue,\n auto_advance: data.autoAdvance,\n metadata: data.metadata,\n }),\n });\n }\n\n async getStripeInvoices(\n accountId: number,\n options?: { limit?: number; startingAfter?: string }\n ): Promise<\n Array<{\n id: string;\n number: string;\n status: string;\n collectionMethod: string;\n amountDue: number;\n amountPaid: number;\n amountRemaining: number;\n currency: string;\n created: number;\n dueDate: number | null;\n paid: boolean;\n hostedInvoiceUrl: string | null;\n invoicePdf: string | null;\n description: string | null;\n periodStart: number | null;\n periodEnd: number | null;\n }>\n > {\n const params = new URLSearchParams();\n if (options?.limit) params.append('limit', options.limit.toString());\n if (options?.startingAfter) params.append('starting_after', options.startingAfter);\n\n return this.fetch<\n Array<{\n id: string;\n number: string;\n status: string;\n collectionMethod: string;\n amountDue: number;\n amountPaid: number;\n amountRemaining: number;\n currency: string;\n created: number;\n dueDate: number | null;\n paid: boolean;\n hostedInvoiceUrl: string | null;\n invoicePdf: string | null;\n description: string | null;\n periodStart: number | null;\n periodEnd: number | null;\n }>\n >(`admin/accounts/${accountId}/stripe/invoices?${params.toString()}`);\n }\n\n async getStripeUpcomingInvoice(\n accountId: number,\n subscriptionId?: string\n ): Promise<{\n amountDue: number;\n amountPaid: number;\n amountRemaining: number;\n currency: string;\n periodStart: number;\n periodEnd: number;\n subtotal: number;\n tax: number;\n total: number;\n lineItems: Array<{\n id: string;\n description: string | null;\n amount: number;\n currency: string;\n quantity: number;\n unitAmount: number;\n productName: string | null;\n productDescription: string | null;\n period: {\n start: number;\n end: number;\n };\n }>;\n customer: string;\n subscription: string | null;\n }> {\n const params = new URLSearchParams();\n if (subscriptionId) params.append('subscription_id', subscriptionId);\n\n return this.fetch<{\n amountDue: number;\n amountPaid: number;\n amountRemaining: number;\n currency: string;\n periodStart: number;\n periodEnd: number;\n subtotal: number;\n tax: number;\n total: number;\n lineItems: Array<{\n id: string;\n description: string | null;\n amount: number;\n currency: string;\n quantity: number;\n unitAmount: number;\n productName: string | null;\n productDescription: string | null;\n period: {\n start: number;\n end: number;\n };\n }>;\n customer: string;\n subscription: string | null;\n }>(`admin/accounts/${accountId}/stripe/upcoming-invoice?${params.toString()}`);\n }\n\n // Billing Dashboard API\n async getWorkspaceUsageDashboard(workspaceUuid: string): Promise<UsageDashboardResponse> {\n return this.fetch<UsageDashboardResponse>(\n `admin/workspaces/${workspaceUuid}/usage-dashboard`\n );\n }\n\n // Product Stripe Sync API\n async compareProductsWithStripe(workspaceUuid?: string): Promise<CompareWithStripeResponse> {\n const params = workspaceUuid ? `?workspace_uuid=${encodeURIComponent(workspaceUuid)}` : '';\n return this.fetch<CompareWithStripeResponse>(`admin/products/compare-stripe${params}`);\n }\n\n async syncProductToStripe(\n productId: number,\n request?: SyncProductToStripeRequest\n ): Promise<SyncProductToStripeResponse> {\n return this.fetch<SyncProductToStripeResponse>(`admin/products/${productId}/sync-stripe`, {\n method: 'POST',\n body: JSON.stringify({ ...request, productId }),\n });\n }\n\n // Search Stripe products\n async searchStripeProducts(\n query: string,\n limit: number = 10\n ): Promise<\n Array<{\n id: string;\n name: string;\n description: string | null;\n active: boolean;\n created: number;\n metadata: Record<string, string>;\n }>\n > {\n const params = new URLSearchParams({ query, limit: limit.toString() });\n return this.fetch<\n Array<{\n id: string;\n name: string;\n description: string | null;\n active: boolean;\n created: number;\n metadata: Record<string, string>;\n }>\n >(`admin/products/stripe/search?${params.toString()}`);\n }\n\n // ===== Subscriptions API =====\n\n async getSubscriptionsAsAdmin(options?: {\n productId?: number;\n productType?: string;\n customerId?: number;\n organizationId?: number;\n accountId?: number;\n isDirect?: boolean;\n status?: string;\n page?: number;\n pageSize?: number;\n }): Promise<PaginatedSubscriptionsResponse> {\n const params = new URLSearchParams();\n if (options?.productId) params.append('product_id', options.productId.toString());\n if (options?.productType) params.append('product_type', options.productType);\n if (options?.customerId) params.append('customer_id', options.customerId.toString());\n if (options?.organizationId)\n params.append('organization_id', options.organizationId.toString());\n if (options?.accountId) params.append('account_id', options.accountId.toString());\n if (options?.isDirect !== undefined) params.append('is_direct', options.isDirect.toString());\n if (options?.status) params.append('status', options.status);\n if (options?.page) params.append('page', options.page.toString());\n if (options?.pageSize) params.append('page_size', options.pageSize.toString());\n const queryString = params.toString();\n return this.fetch<PaginatedSubscriptionsResponse>(\n `admin/subscriptions${queryString ? `?${queryString}` : ''}`\n );\n }\n\n async getSubscriptionAsAdmin(subscriptionId: number): Promise<Subscription> {\n return this.fetch<Subscription>(`admin/subscriptions/${subscriptionId}`);\n }\n\n async updateSubscriptionStatusAsAdmin(\n subscriptionId: number,\n subscriptionStatus: string\n ): Promise<Subscription> {\n return this.fetch<Subscription>(`admin/subscriptions/${subscriptionId}`, {\n method: 'PUT',\n body: JSON.stringify({ subscription_status: subscriptionStatus }),\n });\n }\n\n async updateSubscriptionCreditSettingsAsAdmin(\n subscriptionId: number,\n settings: {\n extra_usage_enabled?: boolean;\n reload_amount_cents?: number | null;\n reload_threshold_cents?: number | null;\n monthly_reload_limit_cents?: number | null;\n }\n ): Promise<Subscription> {\n return this.fetch<Subscription>(`admin/subscriptions/${subscriptionId}`, {\n method: 'PUT',\n body: JSON.stringify(settings),\n });\n }\n\n /** Grant credits to a subscription (superuser only). */\n async grantCreditsAsAdmin(\n subscriptionId: number,\n creditUnits: number,\n grantType: string,\n reason: string\n ): Promise<{\n success: boolean;\n grantId: number;\n creditUnits: number;\n grantedBy: string;\n reason: string;\n }> {\n return this.fetch(`admin/subscriptions/${subscriptionId}/grant-credits`, {\n method: 'POST',\n body: JSON.stringify({ credit_units: creditUnits, grant_type: grantType, reason }),\n });\n }\n\n /** List credit grants for a subscription (superuser only). */\n async listCreditGrantsAsAdmin(subscriptionId: number): Promise<\n {\n id: number;\n uuid: string;\n grantType: string;\n creditUnits: number;\n remainingUnits: number;\n amountCents: number;\n status: string;\n effectiveAt: string | null;\n expiresAt: string | null;\n createdAt: string | null;\n createdBy: string | null;\n reason: string | null;\n }[]\n > {\n return this.fetch(`admin/subscriptions/${subscriptionId}/credit-grants`);\n }\n\n // ===== Usage API =====\n\n async getUsageReport(request: UsageReportRequest): Promise<UsageReport> {\n return this.fetch<UsageReport>('admin/usage', {\n method: 'POST',\n body: JSON.stringify(request),\n });\n }\n\n // Voice Metrics API\n async getVoiceMetrics(options?: {\n hours?: number;\n period?: number;\n workspace_uuid?: string;\n organization_id?: number;\n engine?: string;\n channel?: string;\n }): Promise<VoiceMetricsResponse> {\n const params = new URLSearchParams();\n if (options?.hours) params.append('hours', options.hours.toString());\n if (options?.period) params.append('period', options.period.toString());\n if (options?.workspace_uuid) params.append('workspace_uuid', options.workspace_uuid);\n if (options?.organization_id != null)\n params.append('organization_id', options.organization_id.toString());\n if (options?.engine) params.append('engine', options.engine);\n if (options?.channel) params.append('channel', options.channel);\n const qs = params.toString();\n return this.fetch<VoiceMetricsResponse>(`admin/voice-metrics${qs ? `?${qs}` : ''}`);\n }\n\n // Health Dashboard API\n async getHealthMetrics(request: HealthMetricsRequest): Promise<HealthMetricsResponse> {\n return this.fetch<HealthMetricsResponse>('admin/health/metrics', {\n method: 'POST',\n body: JSON.stringify(request),\n });\n }\n\n async getHealthDetail(\n workspaceUuid: string,\n request: HealthDetailRequest\n ): Promise<WorkspaceHealthDetail> {\n return this.fetch<WorkspaceHealthDetail>(`admin/health/detail/${workspaceUuid}`, {\n method: 'POST',\n body: JSON.stringify(request),\n });\n }\n\n // ===== Reseller Management =====\n\n async getResellers(options?: {\n search?: string;\n page?: number;\n pageSize?: number;\n }): Promise<PaginatedResponse<Reseller>> {\n const params = new URLSearchParams();\n if (options?.search) params.set('search', options.search);\n if (options?.page) params.set('page', String(options.page));\n if (options?.pageSize) params.set('page_size', String(options.pageSize));\n const qs = params.toString();\n return this.fetch<PaginatedResponse<Reseller>>(`admin/resellers${qs ? `?${qs}` : ''}`);\n }\n\n async getReseller(resellerId: number): Promise<Reseller> {\n return this.fetch<Reseller>(`admin/resellers/${resellerId}`);\n }\n\n async createReseller(data: CreateResellerRequest): Promise<Reseller> {\n return this.fetch<Reseller>('admin/resellers', {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateReseller(resellerId: number, data: UpdateResellerRequest): Promise<Reseller> {\n return this.fetch<Reseller>(`admin/resellers/${resellerId}`, {\n method: 'PUT',\n body: JSON.stringify(data),\n });\n }\n\n async getResellerAccounts(resellerId: number): Promise<ResellerAccount[]> {\n return this.fetch<ResellerAccount[]>(`admin/resellers/${resellerId}/accounts`);\n }\n\n async linkResellerToAccount(\n resellerId: number,\n data: LinkResellerAccountRequest\n ): Promise<ResellerAccount> {\n return this.fetch<ResellerAccount>(`admin/resellers/${resellerId}/accounts`, {\n method: 'POST',\n body: JSON.stringify({ account_id: data.accountId, role: data.role }),\n });\n }\n\n async unlinkResellerFromAccount(resellerId: number, accountId: number): Promise<void> {\n await this.fetch<void>(`admin/resellers/${resellerId}/accounts/${accountId}`, {\n method: 'DELETE',\n });\n }\n\n // ===== Invoice Management =====\n\n async generateInvoice(data: {\n subscriptionId: number;\n periodStart: string;\n periodEnd: string;\n regenerate?: boolean;\n }): Promise<Invoice> {\n return this.fetch<Invoice>('admin/invoices/generate', {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async getInvoices(\n subscriptionId?: number,\n pageOpts?: { page?: number; pageSize?: number }\n ): Promise<PaginatedResponse<Invoice>> {\n const params = new URLSearchParams();\n if (subscriptionId !== undefined) params.set('subscription_id', String(subscriptionId));\n if (pageOpts?.page !== undefined) params.set('page', String(pageOpts.page));\n if (pageOpts?.pageSize !== undefined) params.set('pageSize', String(pageOpts.pageSize));\n const qs = params.toString();\n return this.fetch<PaginatedResponse<Invoice>>(`admin/invoices${qs ? `?${qs}` : ''}`);\n }\n\n async getBillingPeriods(subscriptionId: number): Promise<BillingPeriod[]> {\n return this.fetch<BillingPeriod[]>(\n `admin/invoices/periods?subscription_id=${subscriptionId}`\n );\n }\n\n async getInvoiceDownloadUrl(\n invoiceId: number\n ): Promise<{ downloadUrl: string; invoiceNumber: string }> {\n return this.fetch<{ downloadUrl: string; invoiceNumber: string }>(\n `admin/invoices/${invoiceId}/download`\n );\n }\n\n async getReceiptDownloadUrl(\n invoiceId: number\n ): Promise<{ downloadUrl: string; invoiceNumber: string }> {\n return this.fetch<{ downloadUrl: string; invoiceNumber: string }>(\n `admin/invoices/${invoiceId}/receipt`\n );\n }\n\n async recordInvoicePayment(invoiceId: number, data: RecordPaymentRequest): Promise<Invoice> {\n return this.fetch<Invoice>(`admin/invoices/${invoiceId}/record-payment`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n // ===== Admin Temporal Inspection (PHI-safe, read-only) =====\n\n /**\n * Server-enforced bounds for admin Temporal queries (lookback, thresholds,\n * page sizes, history event cap). Superuser only.\n */\n async getTemporalAdminConfig(): Promise<TemporalAdminConfig> {\n return this.fetch<TemporalAdminConfig>('admin/temporal/config');\n }\n\n /**\n * List recent Temporal workflows in FAILED, TIMED_OUT, or TERMINATED\n * status. Returns only PHI-safe operational metadata. Superuser only.\n *\n * Pass `options.status` to filter to a single status and enable\n * deep pagination via `nextPageToken`. Merged mode (no status) returns\n * the first page only and always emits `nextPageToken: null`.\n */\n async listFailedTemporalWorkflows(\n options: AdminTemporalFailedQuery = {}\n ): Promise<FailedWorkflowsResponse> {\n const params = new URLSearchParams();\n if (options.lookbackHours !== undefined)\n params.set('lookback_hours', String(options.lookbackHours));\n if (options.pageSize !== undefined) params.set('page_size', String(options.pageSize));\n if (options.status) params.set('status', String(options.status));\n if (options.nextPageToken) params.set('next_page_token', options.nextPageToken);\n appendTemporalWorkspaceParams(params, options);\n const qs = params.toString();\n return this.fetch<FailedWorkflowsResponse>(\n `admin/temporal/workflows/failed${qs ? `?${qs}` : ''}`\n );\n }\n\n /**\n * List open Temporal workflows older than the stuck threshold.\n * Superuser only.\n */\n async listStuckTemporalWorkflows(\n options: AdminTemporalStuckQuery = {}\n ): Promise<StuckWorkflowsResponse> {\n const params = new URLSearchParams();\n if (options.thresholdMinutes !== undefined)\n params.set('threshold_minutes', String(options.thresholdMinutes));\n if (options.pageSize !== undefined) params.set('page_size', String(options.pageSize));\n if (options.nextPageToken) params.set('next_page_token', options.nextPageToken);\n appendTemporalWorkspaceParams(params, options);\n const qs = params.toString();\n return this.fetch<StuckWorkflowsResponse>(\n `admin/temporal/workflows/stuck${qs ? `?${qs}` : ''}`\n );\n }\n\n /**\n * Return grouped counts for recent Temporal executions. Superuser only.\n */\n async getTemporalSummary(\n options: AdminTemporalSummaryQuery = {}\n ): Promise<TemporalSummaryResponse> {\n const params = new URLSearchParams();\n if (options.lookbackHours !== undefined)\n params.set('lookback_hours', String(options.lookbackHours));\n appendTemporalWorkspaceParams(params, options);\n const qs = params.toString();\n return this.fetch<TemporalSummaryResponse>(\n `admin/temporal/workflows/summary${qs ? `?${qs}` : ''}`\n );\n }\n\n /**\n * Fetch metadata + bounded sanitized history summary for one Temporal\n * workflow. Superuser only. Does not return raw events or payloads.\n */\n async getTemporalWorkflowDetail(\n workflowId: string,\n options: AdminTemporalDetailQuery = {}\n ): Promise<WorkflowDetailResponse> {\n const params = new URLSearchParams();\n if (options.runId) params.set('run_id', options.runId);\n appendTemporalWorkspaceParams(params, options);\n const qs = params.toString();\n const encoded = encodeURIComponent(workflowId);\n return this.fetch<WorkflowDetailResponse>(\n `admin/temporal/workflows/${encoded}${qs ? `?${qs}` : ''}`\n );\n }\n}\n\n/**\n * Append the workspace filter params for admin Temporal endpoints.\n *\n * The server accepts a repeated `workspace_uuid` query parameter. For\n * backward compatibility with callers (including `gr admin temporal`)\n * that still pass a single `workspaceUuid`, we normalize both inputs\n * into the same repeated-parameter wire shape: a single value is\n * appended once; explicit `workspaceUuids` entries are appended in\n * order. Duplicates and blanks are dropped client-side so the final\n * URL stays compact.\n */\nfunction appendTemporalWorkspaceParams(\n params: URLSearchParams,\n options: {\n workspaceUuid?: string;\n workspaceUuids?: string[];\n }\n): void {\n const seen = new Set<string>();\n const push = (raw: string | undefined) => {\n if (!raw) return;\n const trimmed = raw.trim();\n if (!trimmed || seen.has(trimmed)) return;\n seen.add(trimmed);\n params.append('workspace_uuid', trimmed);\n };\n if (options.workspaceUuids) {\n for (const value of options.workspaceUuids) push(value);\n }\n push(options.workspaceUuid);\n}\n","import { GravityRailClient } from '@gravity-rail/sdk';\nimport { AdminApi } from '../api/admin';\nimport { AdminBindings, bindAdminMethods } from './bindings/admin';\n\n/**\n * ApiClient extends GravityRailClient with admin/superuser methods.\n *\n * This is the full-featured client used internally. For the public SDK,\n * use {@link GravityRailClient} from @gravity-rail/sdk which excludes\n * admin functionality.\n */\nexport class ApiClient extends GravityRailClient implements AdminBindings {\n // Admin API\n listSupportRequestsAsAdmin!: AdminBindings['listSupportRequestsAsAdmin'];\n getSupportRequestAsAdmin!: AdminBindings['getSupportRequestAsAdmin'];\n commentOnSupportRequestAsAdmin!: AdminBindings['commentOnSupportRequestAsAdmin'];\n noteOnSupportRequestAsAdmin!: AdminBindings['noteOnSupportRequestAsAdmin'];\n updateSupportRequestStatusAsAdmin!: AdminBindings['updateSupportRequestStatusAsAdmin'];\n updateSupportRequestAttributesAsAdmin!: AdminBindings['updateSupportRequestAttributesAsAdmin'];\n createSupportRequestLinearIssueAsAdmin!: AdminBindings['createSupportRequestLinearIssueAsAdmin'];\n getAccounts!: AdminBindings['getAccounts'];\n getAccountDetails!: AdminBindings['getAccountDetails'];\n getAccountByUuid!: AdminBindings['getAccountByUuid'];\n getAccountMemberships!: AdminBindings['getAccountMemberships'];\n getAccountOrgMemberships!: AdminBindings['getAccountOrgMemberships'];\n createAccountOrgMembership!: AdminBindings['createAccountOrgMembership'];\n deleteAccountOrgMembership!: AdminBindings['deleteAccountOrgMembership'];\n getAccountMembership!: AdminBindings['getAccountMembership'];\n updateAccountMembership!: AdminBindings['updateAccountMembership'];\n createAccountMembership!: AdminBindings['createAccountMembership'];\n deleteAccountMembership!: AdminBindings['deleteAccountMembership'];\n updateAccountAsAdmin!: AdminBindings['updateAccountAsAdmin'];\n createAccountAsAdmin!: AdminBindings['createAccountAsAdmin'];\n deleteAccountAsAdmin!: AdminBindings['deleteAccountAsAdmin'];\n lookupAccount!: AdminBindings['lookupAccount'];\n exportAccountData!: AdminBindings['exportAccountData'];\n requestAccountDeletion!: AdminBindings['requestAccountDeletion'];\n cancelAccountDeletion!: AdminBindings['cancelAccountDeletion'];\n getOrganizations!: AdminBindings['getOrganizations'];\n getOrganization!: AdminBindings['getOrganization'];\n getOrganizationAsAdmin!: AdminBindings['getOrganizationAsAdmin'];\n getOrganizationMembersAsAdmin!: AdminBindings['getOrganizationMembersAsAdmin'];\n createOrganization!: AdminBindings['createOrganization'];\n updateOrganization!: AdminBindings['updateOrganization'];\n deleteOrganization!: AdminBindings['deleteOrganization'];\n joinOrganization!: AdminBindings['joinOrganization'];\n leaveOrganization!: AdminBindings['leaveOrganization'];\n generateLogoUploadUrl!: AdminBindings['generateLogoUploadUrl'];\n importProducts!: AdminBindings['importProducts'];\n createProductAsAdmin!: AdminBindings['createProductAsAdmin'];\n getProductsAsAdmin!: AdminBindings['getProductsAsAdmin'];\n getProductAsAdmin!: AdminBindings['getProductAsAdmin'];\n updateProductAsAdmin!: AdminBindings['updateProductAsAdmin'];\n deleteProductAsAdmin!: AdminBindings['deleteProductAsAdmin'];\n getWorkspacesAsAdmin!: AdminBindings['getWorkspacesAsAdmin'];\n getWorkspaceAsAdmin!: AdminBindings['getWorkspaceAsAdmin'];\n getWorkspaceByNumericIdAsAdmin!: AdminBindings['getWorkspaceByNumericIdAsAdmin'];\n createWorkspaceAsAdmin!: AdminBindings['createWorkspaceAsAdmin'];\n updateWorkspaceAsAdmin!: AdminBindings['updateWorkspaceAsAdmin'];\n deleteWorkspaceAsAdmin!: AdminBindings['deleteWorkspaceAsAdmin'];\n createSchemaAsAdmin!: AdminBindings['createSchemaAsAdmin'];\n migrateSchemaAsAdmin!: AdminBindings['migrateSchemaAsAdmin'];\n provisionWorkspaceAsAdmin!: AdminBindings['provisionWorkspaceAsAdmin'];\n refreshProvisionStatusAsAdmin!: AdminBindings['refreshProvisionStatusAsAdmin'];\n enableMaintenanceMode!: AdminBindings['enableMaintenanceMode'];\n disableMaintenanceMode!: AdminBindings['disableMaintenanceMode'];\n getWorkspaceHealth!: AdminBindings['getWorkspaceHealth'];\n provisionPlanFeatures!: AdminBindings['provisionPlanFeatures'];\n changeWorkspaceProduct!: AdminBindings['changeWorkspaceProduct'];\n validateWorkflowAccessAsAdmin!: AdminBindings['validateWorkflowAccessAsAdmin'];\n mergeMembers!: AdminBindings['mergeMembers'];\n getAdminWorkspaceMember!: AdminBindings['getAdminWorkspaceMember'];\n createAdminWorkspaceMember!: AdminBindings['createAdminWorkspaceMember'];\n updateAdminWorkspaceMember!: AdminBindings['updateAdminWorkspaceMember'];\n unarchiveAdminWorkspaceMember!: AdminBindings['unarchiveAdminWorkspaceMember'];\n getAdminWorkspaceMemberRoles!: AdminBindings['getAdminWorkspaceMemberRoles'];\n getMissingMemberships!: AdminBindings['getMissingMemberships'];\n linkMissingMembership!: AdminBindings['linkMissingMembership'];\n getUnmappedPhoneNumbers!: AdminBindings['getUnmappedPhoneNumbers'];\n getWorkspaceUnmappedPhoneNumbers!: AdminBindings['getWorkspaceUnmappedPhoneNumbers'];\n getWorkspacePhoneNumbersAsAdmin!: AdminBindings['getWorkspacePhoneNumbersAsAdmin'];\n getProviderPhoneNumbers!: AdminBindings['getProviderPhoneNumbers'];\n getProviderPhoneNumber!: AdminBindings['getProviderPhoneNumber'];\n updateProviderPhoneNumber!: AdminBindings['updateProviderPhoneNumber'];\n mapMainAccountPhone!: AdminBindings['mapMainAccountPhone'];\n unmapPhoneNumber!: AdminBindings['unmapPhoneNumber'];\n searchAvailablePhoneNumbersAsAdmin!: AdminBindings['searchAvailablePhoneNumbersAsAdmin'];\n purchasePhoneNumberAsAdmin!: AdminBindings['purchasePhoneNumberAsAdmin'];\n startBulkPhoneClassification!: AdminBindings['startBulkPhoneClassification'];\n getOrgA2PStatusAsAdmin!: AdminBindings['getOrgA2PStatusAsAdmin'];\n resetOrgA2PStatusAsAdmin!: AdminBindings['resetOrgA2PStatusAsAdmin'];\n getSiteMappings!: AdminBindings['getSiteMappings'];\n getSiteMapping!: AdminBindings['getSiteMapping'];\n updateSiteMapping!: AdminBindings['updateSiteMapping'];\n updateSiteMappingWorkspace!: AdminBindings['updateSiteMappingWorkspace'];\n adminDeleteSiteMapping!: AdminBindings['adminDeleteSiteMapping'];\n createSiteMapping!: AdminBindings['createSiteMapping'];\n createOrUpdateSiteMapping!: AdminBindings['createOrUpdateSiteMapping'];\n deleteSiteMapping!: AdminBindings['deleteSiteMapping'];\n getInboxMappings!: AdminBindings['getInboxMappings'];\n getInboxMapping!: AdminBindings['getInboxMapping'];\n updateInboxMapping!: AdminBindings['updateInboxMapping'];\n deleteAdminInboxMapping!: AdminBindings['deleteAdminInboxMapping'];\n generateChatSummaries!: AdminBindings['generateChatSummaries'];\n executeQuery!: AdminBindings['executeQuery'];\n getTraceUrl!: AdminBindings['getTraceUrl'];\n listAllThemes!: AdminBindings['listAllThemes'];\n startBulkTOSAcceptance!: AdminBindings['startBulkTOSAcceptance'];\n startTokenUsageBackfill!: AdminBindings['startTokenUsageBackfill'];\n updateChatMessage!: AdminBindings['updateChatMessage'];\n createCustomerFromAccount!: AdminBindings['createCustomerFromAccount'];\n getCustomers!: AdminBindings['getCustomers'];\n getCustomer!: AdminBindings['getCustomer'];\n createCustomer!: AdminBindings['createCustomer'];\n updateCustomer!: AdminBindings['updateCustomer'];\n getCustomerAccounts!: AdminBindings['getCustomerAccounts'];\n linkCustomerToAccount!: AdminBindings['linkCustomerToAccount'];\n unlinkCustomerFromAccount!: AdminBindings['unlinkCustomerFromAccount'];\n syncCustomerToStripe!: AdminBindings['syncCustomerToStripe'];\n getStripeCustomer!: AdminBindings['getStripeCustomer'];\n createStripeCustomer!: AdminBindings['createStripeCustomer'];\n updateStripeCustomer!: AdminBindings['updateStripeCustomer'];\n getStripeSubscriptions!: AdminBindings['getStripeSubscriptions'];\n createStripeSubscription!: AdminBindings['createStripeSubscription'];\n createDirectSubscription!: AdminBindings['createDirectSubscription'];\n updateStripeSubscription!: AdminBindings['updateStripeSubscription'];\n cancelStripeSubscription!: AdminBindings['cancelStripeSubscription'];\n provisionWorkspaceForSubscription!: AdminBindings['provisionWorkspaceForSubscription'];\n associateWorkspaceWithSubscription!: AdminBindings['associateWorkspaceWithSubscription'];\n createSubscriptionPaymentLink!: AdminBindings['createSubscriptionPaymentLink'];\n createSetupIntent!: AdminBindings['createSetupIntent'];\n getStripePaymentMethods!: AdminBindings['getStripePaymentMethods'];\n attachStripePaymentMethod!: AdminBindings['attachStripePaymentMethod'];\n detachStripePaymentMethod!: AdminBindings['detachStripePaymentMethod'];\n setDefaultStripePaymentMethod!: AdminBindings['setDefaultStripePaymentMethod'];\n createCustomerSetupIntent!: AdminBindings['createCustomerSetupIntent'];\n getCustomerPaymentMethods!: AdminBindings['getCustomerPaymentMethods'];\n attachCustomerPaymentMethod!: AdminBindings['attachCustomerPaymentMethod'];\n detachCustomerPaymentMethod!: AdminBindings['detachCustomerPaymentMethod'];\n setDefaultCustomerPaymentMethod!: AdminBindings['setDefaultCustomerPaymentMethod'];\n convertSubscriptionToStripe!: AdminBindings['convertSubscriptionToStripe'];\n previewWorkspaceOrganizationChange!: AdminBindings['previewWorkspaceOrganizationChange'];\n changeWorkspaceOrganization!: AdminBindings['changeWorkspaceOrganization'];\n createStripeInvoice!: AdminBindings['createStripeInvoice'];\n getStripeInvoices!: AdminBindings['getStripeInvoices'];\n getStripeUpcomingInvoice!: AdminBindings['getStripeUpcomingInvoice'];\n getWorkspaceUsageDashboard!: AdminBindings['getWorkspaceUsageDashboard'];\n compareProductsWithStripe!: AdminBindings['compareProductsWithStripe'];\n syncProductToStripe!: AdminBindings['syncProductToStripe'];\n searchStripeProducts!: AdminBindings['searchStripeProducts'];\n getUsageReport!: AdminBindings['getUsageReport'];\n getSubscriptionsAsAdmin!: AdminBindings['getSubscriptionsAsAdmin'];\n getSubscriptionAsAdmin!: AdminBindings['getSubscriptionAsAdmin'];\n updateSubscriptionStatusAsAdmin!: AdminBindings['updateSubscriptionStatusAsAdmin'];\n updateSubscriptionCreditSettingsAsAdmin!: AdminBindings['updateSubscriptionCreditSettingsAsAdmin'];\n grantCreditsAsAdmin!: AdminBindings['grantCreditsAsAdmin'];\n listCreditGrantsAsAdmin!: AdminBindings['listCreditGrantsAsAdmin'];\n getVoiceMetrics!: AdminBindings['getVoiceMetrics'];\n getHealthMetrics!: AdminBindings['getHealthMetrics'];\n getHealthDetail!: AdminBindings['getHealthDetail'];\n getWorkspaceInboxesAsAdmin!: AdminBindings['getWorkspaceInboxesAsAdmin'];\n listWorkspaceChats!: AdminBindings['listWorkspaceChats'];\n getWorkspaceChat!: AdminBindings['getWorkspaceChat'];\n rateWorkspaceChatMessage!: AdminBindings['rateWorkspaceChatMessage'];\n getTemporalAdminConfig!: AdminBindings['getTemporalAdminConfig'];\n listFailedTemporalWorkflows!: AdminBindings['listFailedTemporalWorkflows'];\n listStuckTemporalWorkflows!: AdminBindings['listStuckTemporalWorkflows'];\n getTemporalSummary!: AdminBindings['getTemporalSummary'];\n getTemporalWorkflowDetail!: AdminBindings['getTemporalWorkflowDetail'];\n getResellers!: AdminBindings['getResellers'];\n getReseller!: AdminBindings['getReseller'];\n createReseller!: AdminBindings['createReseller'];\n updateReseller!: AdminBindings['updateReseller'];\n getResellerAccounts!: AdminBindings['getResellerAccounts'];\n linkResellerToAccount!: AdminBindings['linkResellerToAccount'];\n unlinkResellerFromAccount!: AdminBindings['unlinkResellerFromAccount'];\n getBillingPeriods!: AdminBindings['getBillingPeriods'];\n generateInvoice!: AdminBindings['generateInvoice'];\n getInvoices!: AdminBindings['getInvoices'];\n getInvoiceDownloadUrl!: AdminBindings['getInvoiceDownloadUrl'];\n getReceiptDownloadUrl!: AdminBindings['getReceiptDownloadUrl'];\n recordInvoicePayment!: AdminBindings['recordInvoicePayment'];\n\n protected adminApi: AdminApi;\n\n constructor(apiKey: string | undefined, baseUrl: string, customFetch?: typeof fetch) {\n super(apiKey, baseUrl, customFetch);\n this.adminApi = new AdminApi(apiKey, baseUrl, customFetch);\n bindAdminMethods(this, this.adminApi);\n }\n\n /**\n * Propagates acting member switches to the admin API module as well.\n */\n override setActingMember(memberUuid: string | undefined) {\n super.setActingMember(memberUuid);\n if (typeof this.adminApi.setActingMember === 'function') {\n this.adminApi.setActingMember(memberUuid);\n }\n }\n\n // setOrgToken is intentionally NOT overridden here. Admin routes\n // (/api/v2/admin/*) are protected by the bearer token's superuser claim and\n // ignore X-Org-Token entirely, so propagating an org token to adminApi is\n // dead code that would only obscure auth flow if admin route logic changes.\n}\n","import { AdminApi } from '../../api';\n\nexport interface AdminBindings {\n // Support Requests\n listSupportRequestsAsAdmin: AdminApi['listSupportRequestsAsAdmin'];\n getSupportRequestAsAdmin: AdminApi['getSupportRequestAsAdmin'];\n commentOnSupportRequestAsAdmin: AdminApi['commentOnSupportRequestAsAdmin'];\n noteOnSupportRequestAsAdmin: AdminApi['noteOnSupportRequestAsAdmin'];\n updateSupportRequestStatusAsAdmin: AdminApi['updateSupportRequestStatusAsAdmin'];\n updateSupportRequestAttributesAsAdmin: AdminApi['updateSupportRequestAttributesAsAdmin'];\n createSupportRequestLinearIssueAsAdmin: AdminApi['createSupportRequestLinearIssueAsAdmin'];\n\n // Accounts\n getAccounts: AdminApi['getAccounts'];\n getAccountDetails: AdminApi['getAccountDetails'];\n getAccountByUuid: AdminApi['getAccountByUuid'];\n getAccountMemberships: AdminApi['getAccountMemberships'];\n getAccountOrgMemberships: AdminApi['getAccountOrgMemberships'];\n createAccountOrgMembership: AdminApi['createAccountOrgMembership'];\n deleteAccountOrgMembership: AdminApi['deleteAccountOrgMembership'];\n getAccountMembership: AdminApi['getAccountMembership'];\n updateAccountMembership: AdminApi['updateAccountMembership'];\n createAccountMembership: AdminApi['createAccountMembership'];\n deleteAccountMembership: AdminApi['deleteAccountMembership'];\n updateAccountAsAdmin: AdminApi['updateAccountAsAdmin'];\n createAccountAsAdmin: AdminApi['createAccountAsAdmin'];\n deleteAccountAsAdmin: AdminApi['deleteAccountAsAdmin'];\n lookupAccount: AdminApi['lookupAccount'];\n exportAccountData: AdminApi['exportAccountData'];\n requestAccountDeletion: AdminApi['requestAccountDeletion'];\n cancelAccountDeletion: AdminApi['cancelAccountDeletion'];\n\n // Organizations\n getOrganizations: AdminApi['getOrganizations'];\n getOrganization: AdminApi['getOrganization'];\n getOrganizationAsAdmin: AdminApi['getOrganizationAsAdmin'];\n getOrganizationMembersAsAdmin: AdminApi['getOrganizationMembersAsAdmin'];\n createOrganization: AdminApi['createOrganization'];\n updateOrganization: AdminApi['updateOrganization'];\n deleteOrganization: AdminApi['deleteOrganization'];\n joinOrganization: AdminApi['joinOrganization'];\n leaveOrganization: AdminApi['leaveOrganization'];\n generateLogoUploadUrl: AdminApi['generateLogoUploadUrl'];\n\n // Products\n importProducts: AdminApi['importProducts'];\n createProductAsAdmin: AdminApi['createProductAsAdmin'];\n getProductsAsAdmin: AdminApi['getProductsAsAdmin'];\n getProductAsAdmin: AdminApi['getProductAsAdmin'];\n updateProductAsAdmin: AdminApi['updateProductAsAdmin'];\n deleteProductAsAdmin: AdminApi['deleteProductAsAdmin'];\n\n // Workspaces\n getWorkspacesAsAdmin: AdminApi['getWorkspacesAsAdmin'];\n getWorkspaceAsAdmin: AdminApi['getWorkspaceAsAdmin'];\n getWorkspaceByNumericIdAsAdmin: AdminApi['getWorkspaceByNumericIdAsAdmin'];\n createWorkspaceAsAdmin: AdminApi['createWorkspaceAsAdmin'];\n updateWorkspaceAsAdmin: AdminApi['updateWorkspaceAsAdmin'];\n deleteWorkspaceAsAdmin: AdminApi['deleteWorkspaceAsAdmin'];\n createSchemaAsAdmin: AdminApi['createSchemaAsAdmin'];\n migrateSchemaAsAdmin: AdminApi['migrateSchemaAsAdmin'];\n provisionWorkspaceAsAdmin: AdminApi['provisionWorkspaceAsAdmin'];\n refreshProvisionStatusAsAdmin: AdminApi['refreshProvisionStatusAsAdmin'];\n enableMaintenanceMode: AdminApi['enableMaintenanceMode'];\n disableMaintenanceMode: AdminApi['disableMaintenanceMode'];\n getWorkspaceHealth: AdminApi['getWorkspaceHealth'];\n provisionPlanFeatures: AdminApi['provisionPlanFeatures'];\n changeWorkspaceProduct: AdminApi['changeWorkspaceProduct'];\n validateWorkflowAccessAsAdmin: AdminApi['validateWorkflowAccessAsAdmin'];\n\n // Members\n mergeMembers: AdminApi['mergeMembers'];\n getAdminWorkspaceMember: AdminApi['getAdminWorkspaceMember'];\n createAdminWorkspaceMember: AdminApi['createAdminWorkspaceMember'];\n updateAdminWorkspaceMember: AdminApi['updateAdminWorkspaceMember'];\n unarchiveAdminWorkspaceMember: AdminApi['unarchiveAdminWorkspaceMember'];\n getAdminWorkspaceMemberRoles: AdminApi['getAdminWorkspaceMemberRoles'];\n getMissingMemberships: AdminApi['getMissingMemberships'];\n linkMissingMembership: AdminApi['linkMissingMembership'];\n\n // Phone Numbers\n getUnmappedPhoneNumbers: AdminApi['getUnmappedPhoneNumbers'];\n getWorkspaceUnmappedPhoneNumbers: AdminApi['getWorkspaceUnmappedPhoneNumbers'];\n getWorkspacePhoneNumbersAsAdmin: AdminApi['getWorkspacePhoneNumbersAsAdmin'];\n getProviderPhoneNumbers: AdminApi['getProviderPhoneNumbers'];\n getProviderPhoneNumber: AdminApi['getProviderPhoneNumber'];\n updateProviderPhoneNumber: AdminApi['updateProviderPhoneNumber'];\n mapMainAccountPhone: AdminApi['mapMainAccountPhone'];\n unmapPhoneNumber: AdminApi['unmapPhoneNumber'];\n searchAvailablePhoneNumbersAsAdmin: AdminApi['searchAvailablePhoneNumbersAsAdmin'];\n purchasePhoneNumberAsAdmin: AdminApi['purchasePhoneNumberAsAdmin'];\n startBulkPhoneClassification: AdminApi['startBulkPhoneClassification'];\n getOrgA2PStatusAsAdmin: AdminApi['getOrgA2PStatusAsAdmin'];\n resetOrgA2PStatusAsAdmin: AdminApi['resetOrgA2PStatusAsAdmin'];\n\n // Site Mappings\n getSiteMappings: AdminApi['getSiteMappings'];\n getSiteMapping: AdminApi['getSiteMapping'];\n updateSiteMapping: AdminApi['updateSiteMapping'];\n updateSiteMappingWorkspace: AdminApi['updateSiteMappingWorkspace'];\n adminDeleteSiteMapping: AdminApi['adminDeleteSiteMapping'];\n createSiteMapping: AdminApi['createSiteMapping'];\n createOrUpdateSiteMapping: AdminApi['createOrUpdateSiteMapping'];\n deleteSiteMapping: AdminApi['deleteSiteMapping'];\n\n // Admin Workspace Inboxes\n getWorkspaceInboxesAsAdmin: AdminApi['getWorkspaceInboxesAsAdmin'];\n\n // Inbox Mappings\n getInboxMappings: AdminApi['getInboxMappings'];\n getInboxMapping: AdminApi['getInboxMapping'];\n updateInboxMapping: AdminApi['updateInboxMapping'];\n deleteAdminInboxMapping: AdminApi['deleteAdminInboxMapping'];\n\n // Utilities\n generateChatSummaries: AdminApi['generateChatSummaries'];\n executeQuery: AdminApi['executeQuery'];\n getTraceUrl: AdminApi['getTraceUrl'];\n listAllThemes: AdminApi['listAllThemes'];\n startBulkTOSAcceptance: AdminApi['startBulkTOSAcceptance'];\n startTokenUsageBackfill: AdminApi['startTokenUsageBackfill'];\n updateChatMessage: AdminApi['updateChatMessage'];\n\n // Customer Management\n createCustomerFromAccount: AdminApi['createCustomerFromAccount'];\n getCustomers: AdminApi['getCustomers'];\n getCustomer: AdminApi['getCustomer'];\n createCustomer: AdminApi['createCustomer'];\n updateCustomer: AdminApi['updateCustomer'];\n getCustomerAccounts: AdminApi['getCustomerAccounts'];\n linkCustomerToAccount: AdminApi['linkCustomerToAccount'];\n unlinkCustomerFromAccount: AdminApi['unlinkCustomerFromAccount'];\n syncCustomerToStripe: AdminApi['syncCustomerToStripe'];\n\n // Stripe Customer Management\n getStripeCustomer: AdminApi['getStripeCustomer'];\n createStripeCustomer: AdminApi['createStripeCustomer'];\n updateStripeCustomer: AdminApi['updateStripeCustomer'];\n\n // Stripe Subscription Management\n getStripeSubscriptions: AdminApi['getStripeSubscriptions'];\n createStripeSubscription: AdminApi['createStripeSubscription'];\n createDirectSubscription: AdminApi['createDirectSubscription'];\n updateStripeSubscription: AdminApi['updateStripeSubscription'];\n cancelStripeSubscription: AdminApi['cancelStripeSubscription'];\n provisionWorkspaceForSubscription: AdminApi['provisionWorkspaceForSubscription'];\n associateWorkspaceWithSubscription: AdminApi['associateWorkspaceWithSubscription'];\n createSubscriptionPaymentLink: AdminApi['createSubscriptionPaymentLink'];\n\n // Stripe Payment Methods (account-level — deprecated, use customer-level)\n createSetupIntent: AdminApi['createSetupIntent'];\n getStripePaymentMethods: AdminApi['getStripePaymentMethods'];\n attachStripePaymentMethod: AdminApi['attachStripePaymentMethod'];\n detachStripePaymentMethod: AdminApi['detachStripePaymentMethod'];\n setDefaultStripePaymentMethod: AdminApi['setDefaultStripePaymentMethod'];\n\n // Convert direct subscription to Stripe\n convertSubscriptionToStripe: AdminApi['convertSubscriptionToStripe'];\n\n // Stripe Payment Methods (customer-level)\n createCustomerSetupIntent: AdminApi['createCustomerSetupIntent'];\n getCustomerPaymentMethods: AdminApi['getCustomerPaymentMethods'];\n attachCustomerPaymentMethod: AdminApi['attachCustomerPaymentMethod'];\n detachCustomerPaymentMethod: AdminApi['detachCustomerPaymentMethod'];\n setDefaultCustomerPaymentMethod: AdminApi['setDefaultCustomerPaymentMethod'];\n\n previewWorkspaceOrganizationChange: AdminApi['previewWorkspaceOrganizationChange'];\n changeWorkspaceOrganization: AdminApi['changeWorkspaceOrganization'];\n\n // Stripe Invoices\n createStripeInvoice: AdminApi['createStripeInvoice'];\n getStripeInvoices: AdminApi['getStripeInvoices'];\n getStripeUpcomingInvoice: AdminApi['getStripeUpcomingInvoice'];\n\n // Invoices\n getBillingPeriods: AdminApi['getBillingPeriods'];\n generateInvoice: AdminApi['generateInvoice'];\n getInvoices: AdminApi['getInvoices'];\n getInvoiceDownloadUrl: AdminApi['getInvoiceDownloadUrl'];\n getReceiptDownloadUrl: AdminApi['getReceiptDownloadUrl'];\n recordInvoicePayment: AdminApi['recordInvoicePayment'];\n\n // Billing Dashboard\n getWorkspaceUsageDashboard: AdminApi['getWorkspaceUsageDashboard'];\n\n // Product Stripe Sync\n compareProductsWithStripe: AdminApi['compareProductsWithStripe'];\n syncProductToStripe: AdminApi['syncProductToStripe'];\n searchStripeProducts: AdminApi['searchStripeProducts'];\n\n // Usage API\n getUsageReport: AdminApi['getUsageReport'];\n\n // Subscriptions Admin API\n getSubscriptionsAsAdmin: AdminApi['getSubscriptionsAsAdmin'];\n getSubscriptionAsAdmin: AdminApi['getSubscriptionAsAdmin'];\n updateSubscriptionStatusAsAdmin: AdminApi['updateSubscriptionStatusAsAdmin'];\n updateSubscriptionCreditSettingsAsAdmin: AdminApi['updateSubscriptionCreditSettingsAsAdmin'];\n grantCreditsAsAdmin: AdminApi['grantCreditsAsAdmin'];\n listCreditGrantsAsAdmin: AdminApi['listCreditGrantsAsAdmin'];\n\n // Voice Metrics API\n getVoiceMetrics: AdminApi['getVoiceMetrics'];\n\n // Health Dashboard API\n getHealthMetrics: AdminApi['getHealthMetrics'];\n getHealthDetail: AdminApi['getHealthDetail'];\n\n // Admin Chat Endpoints\n listWorkspaceChats: AdminApi['listWorkspaceChats'];\n getWorkspaceChat: AdminApi['getWorkspaceChat'];\n rateWorkspaceChatMessage: AdminApi['rateWorkspaceChatMessage'];\n\n // Admin Temporal Inspection\n getTemporalAdminConfig: AdminApi['getTemporalAdminConfig'];\n listFailedTemporalWorkflows: AdminApi['listFailedTemporalWorkflows'];\n listStuckTemporalWorkflows: AdminApi['listStuckTemporalWorkflows'];\n getTemporalSummary: AdminApi['getTemporalSummary'];\n getTemporalWorkflowDetail: AdminApi['getTemporalWorkflowDetail'];\n\n // Reseller Management\n getResellers: AdminApi['getResellers'];\n getReseller: AdminApi['getReseller'];\n createReseller: AdminApi['createReseller'];\n updateReseller: AdminApi['updateReseller'];\n getResellerAccounts: AdminApi['getResellerAccounts'];\n linkResellerToAccount: AdminApi['linkResellerToAccount'];\n unlinkResellerFromAccount: AdminApi['unlinkResellerFromAccount'];\n}\n\nexport function bindAdminMethods(target: AdminBindings, admin: AdminApi): void {\n // Support Requests\n target.listSupportRequestsAsAdmin = admin.listSupportRequestsAsAdmin.bind(admin);\n target.getSupportRequestAsAdmin = admin.getSupportRequestAsAdmin.bind(admin);\n target.commentOnSupportRequestAsAdmin = admin.commentOnSupportRequestAsAdmin.bind(admin);\n target.noteOnSupportRequestAsAdmin = admin.noteOnSupportRequestAsAdmin.bind(admin);\n target.updateSupportRequestStatusAsAdmin = admin.updateSupportRequestStatusAsAdmin.bind(admin);\n target.updateSupportRequestAttributesAsAdmin =\n admin.updateSupportRequestAttributesAsAdmin.bind(admin);\n target.createSupportRequestLinearIssueAsAdmin =\n admin.createSupportRequestLinearIssueAsAdmin.bind(admin);\n\n // Accounts\n target.getAccounts = admin.getAccounts.bind(admin);\n target.getAccountDetails = admin.getAccountDetails.bind(admin);\n target.getAccountByUuid = admin.getAccountByUuid.bind(admin);\n target.getAccountMemberships = admin.getAccountMemberships.bind(admin);\n target.getAccountOrgMemberships = admin.getAccountOrgMemberships.bind(admin);\n target.createAccountOrgMembership = admin.createAccountOrgMembership.bind(admin);\n target.deleteAccountOrgMembership = admin.deleteAccountOrgMembership.bind(admin);\n target.getAccountMembership = admin.getAccountMembership.bind(admin);\n target.updateAccountMembership = admin.updateAccountMembership.bind(admin);\n target.createAccountMembership = admin.createAccountMembership.bind(admin);\n target.deleteAccountMembership = admin.deleteAccountMembership.bind(admin);\n target.updateAccountAsAdmin = admin.updateAccountAsAdmin.bind(admin);\n target.createAccountAsAdmin = admin.createAccountAsAdmin.bind(admin);\n target.deleteAccountAsAdmin = admin.deleteAccountAsAdmin.bind(admin);\n target.lookupAccount = admin.lookupAccount.bind(admin);\n target.exportAccountData = admin.exportAccountData.bind(admin);\n target.requestAccountDeletion = admin.requestAccountDeletion.bind(admin);\n target.cancelAccountDeletion = admin.cancelAccountDeletion.bind(admin);\n\n // Organizations\n target.getOrganizations = admin.getOrganizations.bind(admin);\n target.getOrganization = admin.getOrganization.bind(admin);\n target.getOrganizationAsAdmin = admin.getOrganizationAsAdmin.bind(admin);\n target.getOrganizationMembersAsAdmin = admin.getOrganizationMembersAsAdmin.bind(admin);\n target.createOrganization = admin.createOrganization.bind(admin);\n target.updateOrganization = admin.updateOrganization.bind(admin);\n target.deleteOrganization = admin.deleteOrganization.bind(admin);\n target.joinOrganization = admin.joinOrganization.bind(admin);\n target.leaveOrganization = admin.leaveOrganization.bind(admin);\n target.generateLogoUploadUrl = admin.generateLogoUploadUrl.bind(admin);\n\n // Products\n target.importProducts = admin.importProducts.bind(admin);\n target.createProductAsAdmin = admin.createProductAsAdmin.bind(admin);\n target.getProductsAsAdmin = admin.getProductsAsAdmin.bind(admin);\n target.getProductAsAdmin = admin.getProductAsAdmin.bind(admin);\n target.updateProductAsAdmin = admin.updateProductAsAdmin.bind(admin);\n target.deleteProductAsAdmin = admin.deleteProductAsAdmin.bind(admin);\n\n // Workspaces\n target.getWorkspacesAsAdmin = admin.getWorkspacesAsAdmin.bind(admin);\n target.getWorkspaceAsAdmin = admin.getWorkspaceAsAdmin.bind(admin);\n target.getWorkspaceByNumericIdAsAdmin = admin.getWorkspaceByNumericIdAsAdmin.bind(admin);\n target.createWorkspaceAsAdmin = admin.createWorkspaceAsAdmin.bind(admin);\n target.updateWorkspaceAsAdmin = admin.updateWorkspaceAsAdmin.bind(admin);\n target.deleteWorkspaceAsAdmin = admin.deleteWorkspaceAsAdmin.bind(admin);\n target.createSchemaAsAdmin = admin.createSchemaAsAdmin.bind(admin);\n target.migrateSchemaAsAdmin = admin.migrateSchemaAsAdmin.bind(admin);\n target.provisionWorkspaceAsAdmin = admin.provisionWorkspaceAsAdmin.bind(admin);\n target.refreshProvisionStatusAsAdmin = admin.refreshProvisionStatusAsAdmin.bind(admin);\n target.enableMaintenanceMode = admin.enableMaintenanceMode.bind(admin);\n target.disableMaintenanceMode = admin.disableMaintenanceMode.bind(admin);\n target.getWorkspaceHealth = admin.getWorkspaceHealth.bind(admin);\n target.provisionPlanFeatures = admin.provisionPlanFeatures.bind(admin);\n target.changeWorkspaceProduct = admin.changeWorkspaceProduct.bind(admin);\n target.validateWorkflowAccessAsAdmin = admin.validateWorkflowAccessAsAdmin.bind(admin);\n\n // Members\n target.mergeMembers = admin.mergeMembers.bind(admin);\n target.getAdminWorkspaceMember = admin.getAdminWorkspaceMember.bind(admin);\n target.createAdminWorkspaceMember = admin.createAdminWorkspaceMember.bind(admin);\n target.updateAdminWorkspaceMember = admin.updateAdminWorkspaceMember.bind(admin);\n target.unarchiveAdminWorkspaceMember = admin.unarchiveAdminWorkspaceMember.bind(admin);\n target.getAdminWorkspaceMemberRoles = admin.getAdminWorkspaceMemberRoles.bind(admin);\n target.getMissingMemberships = admin.getMissingMemberships.bind(admin);\n target.linkMissingMembership = admin.linkMissingMembership.bind(admin);\n\n // Phone Numbers\n target.getUnmappedPhoneNumbers = admin.getUnmappedPhoneNumbers.bind(admin);\n target.getWorkspaceUnmappedPhoneNumbers = admin.getWorkspaceUnmappedPhoneNumbers.bind(admin);\n target.getWorkspacePhoneNumbersAsAdmin = admin.getWorkspacePhoneNumbersAsAdmin.bind(admin);\n target.getProviderPhoneNumbers = admin.getProviderPhoneNumbers.bind(admin);\n target.getProviderPhoneNumber = admin.getProviderPhoneNumber.bind(admin);\n target.updateProviderPhoneNumber = admin.updateProviderPhoneNumber.bind(admin);\n target.mapMainAccountPhone = admin.mapMainAccountPhone.bind(admin);\n target.unmapPhoneNumber = admin.unmapPhoneNumber.bind(admin);\n target.searchAvailablePhoneNumbersAsAdmin = admin.searchAvailablePhoneNumbersAsAdmin.bind(admin);\n target.purchasePhoneNumberAsAdmin = admin.purchasePhoneNumberAsAdmin.bind(admin);\n target.startBulkPhoneClassification = admin.startBulkPhoneClassification.bind(admin);\n target.getOrgA2PStatusAsAdmin = admin.getOrgA2PStatusAsAdmin.bind(admin);\n target.resetOrgA2PStatusAsAdmin = admin.resetOrgA2PStatusAsAdmin.bind(admin);\n\n // Site Mappings\n target.getSiteMappings = admin.getSiteMappings.bind(admin);\n target.getSiteMapping = admin.getSiteMapping.bind(admin);\n target.updateSiteMapping = admin.updateSiteMapping.bind(admin);\n target.updateSiteMappingWorkspace = admin.updateSiteMappingWorkspace.bind(admin);\n target.adminDeleteSiteMapping = admin.adminDeleteSiteMapping.bind(admin);\n target.createSiteMapping = admin.createSiteMapping.bind(admin);\n target.createOrUpdateSiteMapping = admin.createOrUpdateSiteMapping.bind(admin);\n target.deleteSiteMapping = admin.deleteSiteMapping.bind(admin);\n\n // Inbox Mappings\n target.getInboxMappings = admin.getInboxMappings.bind(admin);\n target.getInboxMapping = admin.getInboxMapping.bind(admin);\n target.updateInboxMapping = admin.updateInboxMapping.bind(admin);\n target.deleteAdminInboxMapping = admin.deleteAdminInboxMapping.bind(admin);\n\n // Utilities\n target.generateChatSummaries = admin.generateChatSummaries.bind(admin);\n target.executeQuery = admin.executeQuery.bind(admin);\n target.getTraceUrl = admin.getTraceUrl.bind(admin);\n target.listAllThemes = admin.listAllThemes.bind(admin);\n target.startBulkTOSAcceptance = admin.startBulkTOSAcceptance.bind(admin);\n target.startTokenUsageBackfill = admin.startTokenUsageBackfill.bind(admin);\n target.updateChatMessage = admin.updateChatMessage.bind(admin);\n\n // Customer Management\n target.createCustomerFromAccount = admin.createCustomerFromAccount.bind(admin);\n target.getCustomers = admin.getCustomers.bind(admin);\n target.getCustomer = admin.getCustomer.bind(admin);\n target.createCustomer = admin.createCustomer.bind(admin);\n target.updateCustomer = admin.updateCustomer.bind(admin);\n target.getCustomerAccounts = admin.getCustomerAccounts.bind(admin);\n target.linkCustomerToAccount = admin.linkCustomerToAccount.bind(admin);\n target.unlinkCustomerFromAccount = admin.unlinkCustomerFromAccount.bind(admin);\n target.syncCustomerToStripe = admin.syncCustomerToStripe.bind(admin);\n\n // Stripe Customer Management\n target.getStripeCustomer = admin.getStripeCustomer.bind(admin);\n target.createStripeCustomer = admin.createStripeCustomer.bind(admin);\n target.updateStripeCustomer = admin.updateStripeCustomer.bind(admin);\n\n // Stripe Subscription Management\n target.getStripeSubscriptions = admin.getStripeSubscriptions.bind(admin);\n target.createStripeSubscription = admin.createStripeSubscription.bind(admin);\n target.createDirectSubscription = admin.createDirectSubscription.bind(admin);\n target.updateStripeSubscription = admin.updateStripeSubscription.bind(admin);\n target.cancelStripeSubscription = admin.cancelStripeSubscription.bind(admin);\n target.provisionWorkspaceForSubscription = admin.provisionWorkspaceForSubscription.bind(admin);\n target.associateWorkspaceWithSubscription = admin.associateWorkspaceWithSubscription.bind(admin);\n target.createSubscriptionPaymentLink = admin.createSubscriptionPaymentLink.bind(admin);\n\n // Stripe Payment Methods (account-level — deprecated)\n target.createSetupIntent = admin.createSetupIntent.bind(admin);\n target.getStripePaymentMethods = admin.getStripePaymentMethods.bind(admin);\n target.attachStripePaymentMethod = admin.attachStripePaymentMethod.bind(admin);\n target.detachStripePaymentMethod = admin.detachStripePaymentMethod.bind(admin);\n target.setDefaultStripePaymentMethod = admin.setDefaultStripePaymentMethod.bind(admin);\n\n // Convert direct subscription to Stripe\n target.convertSubscriptionToStripe = admin.convertSubscriptionToStripe.bind(admin);\n\n // Stripe Payment Methods (customer-level)\n target.createCustomerSetupIntent = admin.createCustomerSetupIntent.bind(admin);\n target.getCustomerPaymentMethods = admin.getCustomerPaymentMethods.bind(admin);\n target.attachCustomerPaymentMethod = admin.attachCustomerPaymentMethod.bind(admin);\n target.detachCustomerPaymentMethod = admin.detachCustomerPaymentMethod.bind(admin);\n target.setDefaultCustomerPaymentMethod = admin.setDefaultCustomerPaymentMethod.bind(admin);\n\n target.previewWorkspaceOrganizationChange = admin.previewWorkspaceOrganizationChange.bind(admin);\n target.changeWorkspaceOrganization = admin.changeWorkspaceOrganization.bind(admin);\n\n // Stripe Invoices\n target.createStripeInvoice = admin.createStripeInvoice.bind(admin);\n target.getStripeInvoices = admin.getStripeInvoices.bind(admin);\n target.getStripeUpcomingInvoice = admin.getStripeUpcomingInvoice.bind(admin);\n\n // Invoices\n target.getBillingPeriods = admin.getBillingPeriods.bind(admin);\n target.generateInvoice = admin.generateInvoice.bind(admin);\n target.getInvoices = admin.getInvoices.bind(admin);\n target.getInvoiceDownloadUrl = admin.getInvoiceDownloadUrl.bind(admin);\n target.getReceiptDownloadUrl = admin.getReceiptDownloadUrl.bind(admin);\n target.recordInvoicePayment = admin.recordInvoicePayment.bind(admin);\n\n // Billing Dashboard\n target.getWorkspaceUsageDashboard = admin.getWorkspaceUsageDashboard.bind(admin);\n\n // Product Stripe Sync\n target.compareProductsWithStripe = admin.compareProductsWithStripe.bind(admin);\n target.syncProductToStripe = admin.syncProductToStripe.bind(admin);\n target.searchStripeProducts = admin.searchStripeProducts.bind(admin);\n\n // Usage API\n target.getUsageReport = admin.getUsageReport.bind(admin);\n\n // Subscriptions Admin API\n target.getSubscriptionsAsAdmin = admin.getSubscriptionsAsAdmin.bind(admin);\n target.getSubscriptionAsAdmin = admin.getSubscriptionAsAdmin.bind(admin);\n target.updateSubscriptionStatusAsAdmin = admin.updateSubscriptionStatusAsAdmin.bind(admin);\n target.updateSubscriptionCreditSettingsAsAdmin =\n admin.updateSubscriptionCreditSettingsAsAdmin.bind(admin);\n target.grantCreditsAsAdmin = admin.grantCreditsAsAdmin.bind(admin);\n target.listCreditGrantsAsAdmin = admin.listCreditGrantsAsAdmin.bind(admin);\n\n // Voice Metrics API\n target.getVoiceMetrics = admin.getVoiceMetrics.bind(admin);\n\n // Health Dashboard API\n target.getHealthMetrics = admin.getHealthMetrics.bind(admin);\n target.getHealthDetail = admin.getHealthDetail.bind(admin);\n\n // Admin Workspace Inboxes\n target.getWorkspaceInboxesAsAdmin = admin.getWorkspaceInboxesAsAdmin.bind(admin);\n\n // Admin Chat Endpoints\n target.listWorkspaceChats = admin.listWorkspaceChats.bind(admin);\n target.getWorkspaceChat = admin.getWorkspaceChat.bind(admin);\n target.rateWorkspaceChatMessage = admin.rateWorkspaceChatMessage.bind(admin);\n\n // Admin Temporal Inspection\n target.getTemporalAdminConfig = admin.getTemporalAdminConfig.bind(admin);\n target.listFailedTemporalWorkflows = admin.listFailedTemporalWorkflows.bind(admin);\n target.listStuckTemporalWorkflows = admin.listStuckTemporalWorkflows.bind(admin);\n target.getTemporalSummary = admin.getTemporalSummary.bind(admin);\n target.getTemporalWorkflowDetail = admin.getTemporalWorkflowDetail.bind(admin);\n\n // Reseller Management\n target.getResellers = admin.getResellers.bind(admin);\n target.getReseller = admin.getReseller.bind(admin);\n target.createReseller = admin.createReseller.bind(admin);\n target.updateReseller = admin.updateReseller.bind(admin);\n target.getResellerAccounts = admin.getResellerAccounts.bind(admin);\n target.linkResellerToAccount = admin.linkResellerToAccount.bind(admin);\n target.unlinkResellerFromAccount = admin.unlinkResellerFromAccount.bind(admin);\n}\n","import { ApiClient as GravityRailClient } from '@gravity-rail/client';\nimport {\n CredentialsManager,\n getEnvironmentConfig,\n refreshAccessToken,\n type CLICredentials,\n type EnvironmentConfig,\n} from '../cli-utils';\nimport { homedir } from 'os';\nimport { detectOutputFormat, type OutputFormat } from './output';\nimport { loadDevCloudRealmFile, loadRealmCredentials } from './realm';\nimport { AuthRequiredError } from './errors';\nimport { registerOrgAuthHandler } from './org-auth';\n\n/** Build an authenticated API client with the CLI org-auth handler registered. */\nfunction makeApiClient(accessToken: string, apiUrl: string): GravityRailClient {\n const apiClient = new GravityRailClient(accessToken, apiUrl);\n registerOrgAuthHandler(apiClient, apiUrl, accessToken);\n return apiClient;\n}\n\n/** Try to silently refresh an expired access token. Returns an AuthenticatedContext or null. */\nasync function tryTokenRefresh(\n ctx: CommandContext,\n creds: CLICredentials\n): Promise<AuthenticatedContext | null> {\n if (!creds.refreshToken) return null;\n const refreshed = await refreshAccessToken(\n ctx.envConfig,\n creds,\n ctx.credentialsManager,\n ctx.env\n );\n if (!refreshed?.accessToken) return null;\n const apiClient = makeApiClient(refreshed.accessToken, ctx.envConfig.apiUrl);\n return { ...ctx, accessToken: refreshed.accessToken, apiClient };\n}\n\nexport interface GlobalOptions {\n env: string;\n realm?: string;\n outputFormat?: string;\n verbose?: boolean;\n allowWrite?: boolean;\n}\n\nexport interface PublicGlobalOptions {\n apiUrl?: string;\n frontendUrl?: string;\n outputFormat?: string;\n verbose?: boolean;\n allowWrite?: boolean;\n}\n\nexport interface CommandContext {\n env: string;\n envConfig: EnvironmentConfig;\n outputFormat: OutputFormat;\n verbose: boolean;\n allowWrite: boolean;\n credentialsManager: CredentialsManager;\n}\n\nexport interface AuthenticatedContext extends CommandContext {\n accessToken: string;\n apiClient: GravityRailClient;\n realmWorkspace?: string;\n}\n\n/** Create a base command context (no auth required) */\nexport function createContext(opts: GlobalOptions): CommandContext {\n const envConfig = getEnvironmentConfig(opts.env);\n const credentialsManager = new CredentialsManager(homedir(), envConfig.apiUrl);\n return {\n env: opts.env,\n envConfig,\n outputFormat: detectOutputFormat(opts.outputFormat),\n verbose: opts.verbose ?? false,\n allowWrite: opts.allowWrite ?? false,\n credentialsManager,\n };\n}\n\n/** Create an authenticated command context. Tries realm, env var, then cached token. Never auto-triggers OAuth. */\nexport async function createAuthenticatedContext(\n opts: GlobalOptions\n): Promise<AuthenticatedContext> {\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- CLI handler context, not React\n const ctx = createContext(opts);\n\n // Try --realm first (dev-only shortcut using dev-realms.json)\n if (opts.realm) {\n let devRealmsPath: string | undefined;\n if (opts.env.startsWith('dev-cloud:')) {\n const namespace = opts.env.slice('dev-cloud:'.length);\n devRealmsPath = loadDevCloudRealmFile(namespace);\n }\n const { token, workspaceUuid } = loadRealmCredentials(opts.realm, devRealmsPath);\n const apiClient = makeApiClient(token, ctx.envConfig.apiUrl);\n return { ...ctx, accessToken: token, apiClient, realmWorkspace: workspaceUuid };\n }\n\n // Try GRAVITY_RAIL_API_KEY first\n const apiKey = process.env.GRAVITY_RAIL_API_KEY;\n if (apiKey) {\n const apiClient = makeApiClient(apiKey, ctx.envConfig.apiUrl);\n return { ...ctx, accessToken: apiKey, apiClient };\n }\n\n // Try cached credentials (from `gr login`)\n const creds = ctx.credentialsManager.load(ctx.env);\n if (creds?.accessToken) {\n const buffer = 5 * 60 * 1000;\n const notExpired =\n !creds.expiresAt || new Date(creds.expiresAt) > new Date(Date.now() + buffer);\n if (notExpired) {\n const apiClient = makeApiClient(creds.accessToken, ctx.envConfig.apiUrl);\n return { ...ctx, accessToken: creds.accessToken, apiClient };\n }\n\n // Token expired — try refresh\n const refreshed = await tryTokenRefresh(ctx, creds);\n if (refreshed) return refreshed;\n }\n\n throw new AuthRequiredError();\n}\n\n/**\n * Narrow a handler context to `AuthenticatedContext`.\n *\n * Handler `ctx` is typed as `AuthenticatedContext | CommandContext` so that\n * `requiresAuth: false` handlers can also share the type. At runtime, every\n * handler that did not opt out of auth will receive an `AuthenticatedContext`,\n * but TypeScript cannot verify this — call this helper before accessing\n * `apiClient` / `accessToken`.\n *\n * Throws if called from a handler that did not declare `requiresAuth`.\n */\nexport function requireAuth(ctx: AuthenticatedContext | CommandContext): AuthenticatedContext {\n if (!('apiClient' in ctx)) {\n throw new Error('Command handler accessed apiClient without declaring requiresAuth');\n }\n return ctx;\n}\n\n/** Create a base command context for the public CLI (no --env flag, defaults to prod) */\nexport function createPublicContext(opts: PublicGlobalOptions): CommandContext {\n const apiUrl = opts.apiUrl || process.env.GRAVITY_RAIL_API_URL || 'https://api.gravityrail.com';\n const frontendUrl =\n opts.frontendUrl || process.env.GRAVITY_RAIL_FRONTEND_URL || 'https://app.gravityrail.com';\n const envConfig: EnvironmentConfig = { apiUrl, frontendUrl };\n const credentialsManager = new CredentialsManager(homedir(), apiUrl);\n return {\n env: 'prod',\n envConfig,\n outputFormat: detectOutputFormat(opts.outputFormat),\n verbose: opts.verbose ?? false,\n allowWrite: opts.allowWrite ?? false,\n credentialsManager,\n };\n}\n\n/** Create an authenticated context for the public CLI. Tries env var, then cached token. */\nexport async function createPublicAuthenticatedContext(\n opts: PublicGlobalOptions\n): Promise<AuthenticatedContext> {\n const ctx = createPublicContext(opts);\n\n const apiKey = process.env.GRAVITY_RAIL_API_KEY;\n if (apiKey) {\n const apiClient = makeApiClient(apiKey, ctx.envConfig.apiUrl);\n return { ...ctx, accessToken: apiKey, apiClient };\n }\n\n const creds = ctx.credentialsManager.load(ctx.env);\n if (creds?.accessToken) {\n const buffer = 5 * 60 * 1000;\n const notExpired =\n !creds.expiresAt || new Date(creds.expiresAt) > new Date(Date.now() + buffer);\n if (notExpired) {\n const apiClient = makeApiClient(creds.accessToken, ctx.envConfig.apiUrl);\n return { ...ctx, accessToken: creds.accessToken, apiClient };\n }\n\n // Token expired — try refresh\n const refreshed = await tryTokenRefresh(ctx, creds);\n if (refreshed) return refreshed;\n }\n\n throw new AuthRequiredError();\n}\n","import { printTable } from '../cli-utils';\nimport {\n type PaginationMeta,\n isListResult,\n extractPaginationMeta,\n formatPaginationWarning,\n unwrapItems,\n} from './pagination';\n\nexport type OutputFormat = 'json' | 'jsonl' | 'table';\n\nexport interface OutputOptions {\n outputFormat: OutputFormat;\n}\n\nexport interface TableColumn<T> {\n header: string;\n getValue: (item: T) => string;\n maxWidth?: number;\n}\n\n/** Detect default output format based on whether stdout is a TTY */\nexport function detectOutputFormat(explicit?: string): OutputFormat {\n if (explicit) return explicit as OutputFormat;\n return process.stdout.isTTY ? 'table' : 'json';\n}\n\n/**\n * Write a list of items to stdout in the requested format.\n *\n * Accepts:\n * - A `ListResult` (explicit contract with items, meta, supportsAll) — preferred.\n * - Raw arrays, paginated responses ({ items: [...] }), or any object — legacy.\n *\n * When a `ListResult` is passed, its explicit `meta` and `supportsAll` are used.\n * When raw data is passed, pagination metadata is auto-detected with\n * `supportsAll: false` as the safe default.\n *\n * The optional `paginationMeta` and `supportsAll` parameters are kept for\n * backward compatibility but are ignored when a `ListResult` is passed.\n */\nexport function outputData(\n data: unknown,\n opts: OutputOptions,\n columns?: TableColumn<any>[],\n paginationMeta?: PaginationMeta,\n supportsAll?: boolean\n): void {\n let items: unknown[];\n let meta: PaginationMeta | undefined;\n let allSupported: boolean;\n\n if (isListResult(data)) {\n // Explicit contract: use ListResult fields directly\n items = data.items;\n meta = data.meta;\n allSupported = data.supportsAll ?? false;\n } else {\n // Legacy path: auto-detect from raw data\n items = unwrapItems(data);\n meta = paginationMeta ?? extractPaginationMeta(data);\n allSupported = supportsAll ?? false;\n }\n\n const warning = formatPaginationWarning(meta, allSupported);\n if (warning) {\n process.stderr.write(warning + '\\n');\n }\n\n switch (opts.outputFormat) {\n case 'json':\n process.stdout.write(JSON.stringify(items, null, 2) + '\\n');\n break;\n case 'jsonl':\n for (const item of items) {\n process.stdout.write(JSON.stringify(item) + '\\n');\n }\n break;\n case 'table':\n if (columns) {\n printTable(items, columns);\n } else {\n process.stdout.write(JSON.stringify(items, null, 2) + '\\n');\n }\n break;\n }\n}\n\n/** Write a single object to stdout in the requested format */\nexport function outputSingle<T>(data: T, opts: OutputOptions, columns?: TableColumn<T>[]): void {\n switch (opts.outputFormat) {\n case 'json':\n process.stdout.write(JSON.stringify(data, null, 2) + '\\n');\n break;\n case 'jsonl':\n process.stdout.write(JSON.stringify(data) + '\\n');\n break;\n case 'table':\n if (columns) {\n printTable([data], columns);\n } else {\n process.stdout.write(JSON.stringify(data, null, 2) + '\\n');\n }\n break;\n }\n}\n\n/** Common column factory helpers for domain files */\nexport const COL = {\n id: (): TableColumn<any> => ({ header: 'ID', getValue: (item) => String(item.id ?? '') }),\n uuid: (): TableColumn<any> => ({ header: 'UUID', getValue: (item) => item.uuid ?? '' }),\n name: (): TableColumn<any> => ({ header: 'NAME', getValue: (item) => item.name ?? '' }),\n status: (): TableColumn<any> => ({ header: 'STATUS', getValue: (item) => item.status ?? '' }),\n created: (): TableColumn<any> => ({\n header: 'CREATED',\n getValue: (item) => item.created_at ?? '',\n }),\n updated: (): TableColumn<any> => ({\n header: 'UPDATED',\n getValue: (item) => item.updated_at ?? '',\n }),\n description: (): TableColumn<any> => ({\n header: 'DESCRIPTION',\n getValue: (item) => item.description ?? '',\n }),\n enabled: (): TableColumn<any> => ({\n header: 'ENABLED',\n getValue: (item) => String(item.enabled ?? ''),\n }),\n};\n\n/** Write a status/progress message to stderr (never pollutes stdout) */\nexport function stderr(msg: string): void {\n process.stderr.write(msg + '\\n');\n}\n","import { execSync } from 'child_process';\nimport { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'fs';\nimport { dirname, join } from 'path';\n\nexport interface RealmCredentials {\n token: string;\n workspaceUuid?: string;\n}\n\n/** Walk up from cwd looking for dev-realms.json (like finding package.json) */\nfunction findDevRealmsFile(): string {\n let dir = process.cwd();\n while (dir !== dirname(dir)) {\n const candidate = join(dir, 'dev-realms.json');\n if (existsSync(candidate)) return candidate;\n dir = dirname(dir);\n }\n throw new Error('Cannot find dev-realms.json in any parent directory');\n}\n\nconst DEV_CLOUD_CACHE_DIR = '.dev-cloud';\nconst CACHE_MAX_AGE_MS = 60 * 60 * 1000; // 1 hour\n\nfunction findRepoRoot(): string | undefined {\n let dir = process.cwd();\n while (dir !== dirname(dir)) {\n if (existsSync(join(dir, '.git'))) {\n return dir;\n }\n dir = dirname(dir);\n }\n return undefined;\n}\n\nfunction getDevCloudCacheDir(namespace: string): string {\n const repoRoot = findRepoRoot();\n const base = repoRoot ?? process.cwd();\n return join(base, DEV_CLOUD_CACHE_DIR, namespace);\n}\n\nfunction fetchDevCloudRealms(namespace: string): string {\n const k8sNamespace = `dev-cloud-${namespace}`;\n const cmd = `kubectl exec -n ${k8sNamespace} deploy/env -c devbox -- cat /workspace/dev-realms.json`;\n try {\n return execSync(cmd, { encoding: 'utf-8', timeout: 30000 });\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n throw new Error(\n `Failed to fetch dev-realms.json from dev-cloud pod \"${namespace}\": ${message}`\n );\n }\n}\n\n/**\n * Load (and cache) the dev-realms.json file from a dev-cloud pod.\n * Returns the path to the cached file.\n */\nexport function loadDevCloudRealmFile(namespace: string): string {\n const cacheDir = getDevCloudCacheDir(namespace);\n const cachePath = join(cacheDir, 'dev-realms.json');\n\n // Check cache freshness\n if (existsSync(cachePath)) {\n const stat = statSync(cachePath);\n const age = Date.now() - stat.mtimeMs;\n if (age < CACHE_MAX_AGE_MS) {\n return cachePath;\n }\n }\n\n // Fetch from pod\n const content = fetchDevCloudRealms(namespace);\n mkdirSync(cacheDir, { recursive: true });\n writeFileSync(cachePath, content, 'utf-8');\n return cachePath;\n}\n\nexport function loadRealmCredentials(realm: string, devRealmsPath?: string): RealmCredentials {\n const filePath = devRealmsPath ?? findDevRealmsFile();\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(readFileSync(filePath, 'utf-8'));\n } catch {\n throw new Error(`Cannot read dev-realms.json at ${filePath}`);\n }\n\n const parts = realm.split('/');\n if (parts.length === 1) {\n // Account-level: --realm dr-chen\n const accounts = data._accounts as Record<string, { token?: string }> | undefined;\n const account = accounts?.[parts[0]!];\n if (!account?.token) {\n throw new Error(`Realm account \"${parts[0]}\" not found in dev-realms.json`);\n }\n return { token: account.token };\n } else {\n // Workspace/member: --realm boston-nephrology-clinic/dr-chen\n const [wsName, memberName] = parts;\n const ws = data[wsName!] as\n | { workspaceUuid?: string; members?: Record<string, { token?: string }> }\n | undefined;\n if (!ws) {\n throw new Error(`Realm workspace \"${wsName}\" not found in dev-realms.json`);\n }\n const member = ws.members?.[memberName!];\n if (!member?.token) {\n throw new Error(`Realm member \"${memberName}\" not found in workspace \"${wsName}\"`);\n }\n return { token: member.token, workspaceUuid: ws.workspaceUuid };\n }\n}\n","/**\n * CLI handler for organization-level authentication challenges.\n *\n * When a workspace API call returns a 401 with WWW-Authenticate: Bearer realm=\"org\",\n * the SDK calls this handler. The CLI attempts to satisfy the challenge by:\n *\n * 1. POSTing to /api/v2/o/{org_uuid}/join with the existing bearer token.\n * This works for organizations that allow internal (non-SSO) authentication.\n * The response Set-Cookie header contains the org JWE token.\n *\n * 2. If the org requires SSO, falls back to opening the auth URL in the browser\n * and prompting the user to complete authentication manually, then errors.\n */\n\nimport { execFile } from 'child_process';\nimport type { OrgAuthInfo, GravityRailClient } from '@gravity-rail/sdk';\nimport { stderr } from './output';\n\nconst ORG_AUTH_TIMEOUT_MS = 5 * 60 * 1000;\n\n/** Parse an org token value from Set-Cookie header strings. */\nfunction extractOrgTokenFromSetCookies(\n setCookieValues: string[],\n preferredCookieName: string\n): string | undefined {\n let fallback: string | undefined;\n\n for (const value of setCookieValues) {\n const nameValue = value.split(';')[0]?.trim() ?? '';\n const eqIdx = nameValue.indexOf('=');\n if (eqIdx === -1) continue;\n\n const name = nameValue.slice(0, eqIdx).trim();\n const tokenValue = nameValue.slice(eqIdx + 1).trim() || undefined;\n if (!tokenValue) continue;\n\n if (name === preferredCookieName) return tokenValue;\n // Accept any orgToken... or orgSession... cookie as a fallback\n if (!fallback && (name.startsWith('orgToken') || name.startsWith('orgSession'))) {\n fallback = tokenValue;\n }\n }\n\n return fallback;\n}\n\n/**\n * Attempt to satisfy an org auth challenge via the direct join endpoint.\n * Returns the org token string on success, null when SSO is required.\n * Throws on unexpected network / server errors.\n */\nasync function tryDirectJoin(\n apiUrl: string,\n accessToken: string,\n orgAuthInfo: OrgAuthInfo\n): Promise<string | null> {\n const response = await fetch(`${apiUrl}/api/v2/o/${orgAuthInfo.orgUuid}/join`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: '{}',\n });\n\n if (response.status === 400) {\n // Org requires SSO — direct join is not permitted for this account\n return null;\n }\n\n if (!response.ok) {\n // Don't include the response body — the backend currently returns safe\n // JSON, but a future change could put PHI or other sensitive data there.\n // Status code is sufficient to disambiguate the failure mode.\n throw new Error(`Org join failed (HTTP ${response.status})`);\n }\n\n // Read Set-Cookie headers to extract the org token value.\n // Node ≥18 exposes getSetCookie() on Headers; fall back to get() for older runtimes.\n const rawHeaders = response.headers as Headers & {\n getSetCookie?: () => string[];\n };\n const setCookies: string[] =\n rawHeaders.getSetCookie?.() ??\n (rawHeaders.get('set-cookie') ? [rawHeaders.get('set-cookie')!] : []);\n\n if (setCookies.length === 0) {\n throw new Error('Org join succeeded but no Set-Cookie header returned');\n }\n\n const orgToken = extractOrgTokenFromSetCookies(setCookies, orgAuthInfo.cookieName);\n if (!orgToken) {\n throw new Error('Org join succeeded but org token cookie not found in Set-Cookie');\n }\n\n return orgToken;\n}\n\n/**\n * Validate that an auth URL is safe to hand to the OS URL opener.\n *\n * `open` / `xdg-open` / `cmd.exe start` will follow any URI scheme the OS\n * registers — including `file://`, `javascript:`, and custom app handlers —\n * so a compromised/MITMed server returning an attacker-controlled `authUrl`\n * could trigger arbitrary URI execution. Restrict to http(s) and require\n * the same parent domain as the configured API host (e.g. SSO login on\n * `app.gravityrail.com` is allowed when the API is `api.gravityrail.com`,\n * but `attacker.example` against `api.gravityrail.com` is rejected).\n *\n * \"Same parent domain\" is a last-2-labels match. This is a heuristic — it\n * does not consult the Public Suffix List, so `foo.co.uk` and `bar.co.uk`\n * would falsely match — but Gravity Rail's auth hosts do not live under\n * those ccTLDs, and the alternative (vendoring `psl`) is overkill for a CLI\n * gating check. The configured `apiUrl` is itself a trust anchor controlled\n * by the user; the threat is a hostile *response* from that API (or a MITM)\n * pivoting the URL opener.\n */\nfunction isAllowedAuthUrl(url: string, apiUrl: string): boolean {\n try {\n const parsed = new URL(url);\n const api = new URL(apiUrl);\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return false;\n if (parsed.hostname === api.hostname) return true;\n\n const lastTwo = (host: string): string => {\n const parts = host.split('.').filter(Boolean);\n return parts.length >= 2 ? parts.slice(-2).join('.') : host;\n };\n // Reject IP-literal hosts from the parent-domain heuristic — last-2\n // labels of \"1.2.3.4\" would naively match \"3.4\" and admit anything.\n const isIp = /^[0-9.]+$|^\\[.*\\]$/.test(parsed.hostname);\n if (isIp) return false;\n\n return lastTwo(parsed.hostname) === lastTwo(api.hostname);\n } catch {\n return false;\n }\n}\n\n/** Open a URL in the system browser (cross-platform). */\nfunction openBrowser(url: string): void {\n let command: string;\n let args: string[];\n\n if (process.platform === 'darwin') {\n command = 'open';\n args = [url];\n } else if (process.platform === 'win32') {\n command = 'cmd.exe';\n args = ['/c', 'start', '', url];\n } else {\n command = 'xdg-open';\n args = [url];\n }\n\n execFile(command, args, (_err) => {\n // Failure is non-fatal — the URL is printed to stderr so the user can open it manually.\n });\n}\n\n/**\n * Register a CLI org-auth handler on the given client.\n *\n * The handler satisfies org-auth 401 challenges without relying on browser\n * cookies (which are not available in Node.js):\n *\n * - Non-SSO orgs: calls the join endpoint directly and reads the org token\n * from the Set-Cookie response header, then sets it via client.setOrgToken().\n * The SDK retries the original request with X-Org-Token on the next call.\n *\n * - SSO orgs: opens the browser at the authUrl and returns a timeout error\n * after ORG_AUTH_TIMEOUT_MS, because the SSO token is only ever set as a\n * browser cookie that the CLI cannot intercept.\n */\nexport function registerOrgAuthHandler(\n apiClient: GravityRailClient,\n apiUrl: string,\n accessToken: string\n): void {\n apiClient.setOrgAuthHandler(async (orgAuthInfo: OrgAuthInfo): Promise<void> => {\n // Fast path: non-SSO org — join directly and extract the token.\n try {\n const orgToken = await tryDirectJoin(apiUrl, accessToken, orgAuthInfo);\n if (orgToken !== null) {\n // Set the token on the client so the SDK's fallback check (this.orgToken)\n // picks it up after the handler resolves (Node.js has no document.cookie).\n // Pass the org_uuid so the SDK can detect a stale token if the next\n // request targets a different org.\n apiClient.setOrgToken(orgToken, orgAuthInfo.orgUuid);\n return;\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n stderr(`Warning: org direct-join failed (${msg}); trying browser auth`);\n }\n\n // Slow path: SSO org — the browser must complete the flow. Reject the\n // auth URL up-front if it doesn't match the configured API origin so a\n // hostile server can't pivot the OS URL opener to a `javascript:` /\n // `file://` / custom-scheme handler.\n if (!isAllowedAuthUrl(orgAuthInfo.authUrl, apiUrl)) {\n throw new Error(\n `Refusing to open organization auth URL: scheme/host does not match the configured API host. ` +\n `Re-run with the expected --api-url, or contact support.`\n );\n }\n\n stderr(`\\nThis workspace requires organization SSO authentication.`);\n stderr(`Opening browser to complete authentication...`);\n stderr(` ${orgAuthInfo.authUrl}\\n`);\n stderr(`If the browser does not open, visit the URL above manually.`);\n stderr(\n `After signing in, re-run the command — the CLI cannot receive the SSO token directly.`\n );\n openBrowser(orgAuthInfo.authUrl);\n\n // Reject after timeout so the CLI doesn't hang indefinitely.\n await new Promise<void>((_, reject) => {\n const t = setTimeout(\n () =>\n reject(\n new Error(\n 'Organization authentication timed out.\\n' +\n 'Please complete authentication in the browser, then re-run the command.'\n )\n ),\n ORG_AUTH_TIMEOUT_MS\n );\n // Unref so the timeout doesn't keep the Node.js event loop alive\n // if the parent process is otherwise done.\n t.unref?.();\n });\n });\n}\n","import { readFileSync } from 'fs';\nimport type { ParsedArgs } from './types';\nimport { CLIError } from './errors';\n\n/** Read JSON input from --data string, --file path, or stdin (if piped) */\nexport async function readJsonInput(args: ParsedArgs): Promise<unknown | undefined> {\n const dataStr = args.data as string | undefined;\n const filePath = args.file as string | undefined;\n\n if (dataStr) {\n try {\n return JSON.parse(dataStr);\n } catch {\n throw new CLIError('Invalid JSON in --data argument');\n }\n }\n\n if (filePath) {\n try {\n const content = readFileSync(filePath, 'utf-8');\n return JSON.parse(content);\n } catch (err) {\n if (err instanceof SyntaxError) {\n throw new CLIError(`Invalid JSON in file: ${filePath}`);\n }\n throw new CLIError(`Cannot read file: ${filePath}`);\n }\n }\n\n // Read from stdin if piped\n if (!process.stdin.isTTY) {\n return readStdin();\n }\n\n return undefined;\n}\n\nfunction readStdin(): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let data = '';\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (chunk: string) => {\n data += chunk;\n });\n process.stdin.on('end', () => {\n if (!data.trim()) {\n resolve(undefined);\n return;\n }\n try {\n resolve(JSON.parse(data));\n } catch {\n reject(new CLIError('Invalid JSON from stdin'));\n }\n });\n process.stdin.on('error', (err: Error) => {\n reject(new CLIError(`Error reading stdin: ${err.message}`));\n });\n });\n}\n","import type { GravityRailClient } from '@gravity-rail/sdk';\nimport { requireAuth } from './context';\nimport type { ArgDef, CommandDef, CommandHandlerContext } from './types';\nimport type { TableColumn } from './output';\nimport { outputData, outputSingle } from './output';\nimport { CLIError } from './errors';\nimport { LIST_PAGINATION_ARGS, fetchAllPages, listResult, unwrapItems } from './pagination';\n\n/**\n * @deprecated Use `SimpleCrudConfig` with `simpleCrudCommands()` for new code.\n *\n * This interface uses string method names that are resolved at runtime via\n * dynamic dispatch, which prevents TypeScript from validating call signatures.\n * It is safe for simple top-level CRUD resources but must NOT be used for\n * nested resources that require parent IDs.\n */\nexport interface CrudConfig<T = unknown> {\n prefix: string[];\n entityName: string;\n listMethod?: string;\n getMethod?: string;\n createMethod?: string;\n updateMethod?: string;\n deleteMethod?: string;\n archiveMethod?: string;\n unarchiveMethod?: string;\n /** When true, adds a --cascade flag to the delete command. Only enable for entities whose backend endpoint accepts a cascade parameter. */\n supportsCascade?: boolean;\n columns?: TableColumn<T>[];\n requiresWorkspace?: boolean;\n listArgs?: ArgDef[];\n extra?: CommandDef[];\n /** Example lines shown in help for the create command */\n createExamples?: string[];\n /**\n * Controls how the CRUD list handler interacts with pagination.\n *\n * - `'full'` — The client method accepts an options object with page/pageSize.\n * Pagination args (--page, --page-size, --all) are injected and\n * forwarded to the API method via `callApiWithOptions`.\n * - `'client-only'` — Pagination args are injected for --all support (client-side\n * page-walking), but options are NOT forwarded to the API method.\n * Use for raw-array endpoints that don't accept page/pageSize.\n * - `false` — No pagination args are injected. The list method is called with\n * `callApi` (workspace-only) or `callApiWithOptions` for domain\n * listArgs only. Use for legacy/positional signatures where passing\n * an options object would be misinterpreted.\n *\n * Default: `false` (safe — never forwards pagination options unless opted in).\n */\n paginationSupport?: 'full' | 'client-only' | false;\n}\n\n/**\n * @deprecated Use `simpleCrudCommands()` for new code — it provides compile-time\n * safety via typed callables instead of string method names.\n *\n * Existing usages are safe for simple top-level CRUD resources. Do NOT use this\n * for nested resources that require parent IDs (workflowId, memberId, toolkitId, etc.).\n */\nexport function crudCommands<T>(config: CrudConfig<T>): CommandDef[] {\n const {\n prefix,\n entityName,\n columns,\n requiresWorkspace = true,\n listArgs = [],\n extra = [],\n } = config;\n\n // Default: false (safe — never forwards pagination options unless explicitly opted in)\n const paginationSupport = config.paginationSupport ?? false;\n\n const cmds: CommandDef[] = [];\n\n if (config.listMethod) {\n // Determine which args to expose on this list command.\n // 'full' and 'client-only' inject pagination args; false does not.\n const injectPaginationArgs = paginationSupport !== false;\n const seenArgNames = new Set(listArgs.map((a) => a.name));\n const mergedArgs = injectPaginationArgs\n ? [...listArgs, ...LIST_PAGINATION_ARGS.filter((a) => !seenArgNames.has(a.name))]\n : [...listArgs];\n\n cmds.push({\n path: [...prefix, 'list'],\n description: `List ${entityName}s`,\n args: mergedArgs,\n requiresWorkspace,\n columns: columns as TableColumn<unknown>[] | undefined,\n handler: async (hctx: CommandHandlerContext) => {\n // Track whether the domain defines custom list args (domain filters or pagination).\n // When true, always pass an options object to the API method for compatibility.\n const domainHasListArgs = listArgs.length > 0;\n\n if (injectPaginationArgs && hctx.args['all']) {\n let allItems: unknown[];\n if (paginationSupport === 'full') {\n // Fetch all pages using server-side pagination\n allItems = await fetchAllPages(async ({ page, pageSize }) => {\n const opts = buildListOptions(hctx, listArgs);\n opts['page'] = page;\n opts['pageSize'] = pageSize;\n return callApiWithOptions(hctx, config.listMethod!, requiresWorkspace, opts);\n });\n } else {\n // client-only: single fetch, return whatever the API gives us\n const result = await callApi(hctx, config.listMethod!, requiresWorkspace);\n allItems = unwrapItems(result);\n }\n outputData(allItems, hctx.ctx, columns as TableColumn<T>[] | undefined);\n } else if (paginationSupport === 'full') {\n // Build options from domain-specific + pagination args\n const opts = buildListOptions(hctx, mergedArgs);\n const result =\n domainHasListArgs || Object.keys(opts).length > 0\n ? await callApiWithOptions(hctx, config.listMethod!, requiresWorkspace, opts)\n : await callApi(hctx, config.listMethod!, requiresWorkspace);\n // Explicit contract: supportsAll=true because this path exposes --all\n outputData(\n listResult(result, true),\n hctx.ctx,\n columns as TableColumn<T>[] | undefined\n );\n } else {\n // paginationSupport is false or 'client-only': never forward options to the API.\n // Only pass domain listArgs if the domain defines custom args and the method\n // is options-compatible (domainHasListArgs implies the method accepts an object).\n if (domainHasListArgs) {\n const opts = buildListOptions(hctx, listArgs);\n const result =\n Object.keys(opts).length > 0\n ? await callApiWithOptions(\n hctx,\n config.listMethod!,\n requiresWorkspace,\n opts\n )\n : await callApi(hctx, config.listMethod!, requiresWorkspace);\n outputData(\n listResult(result, false),\n hctx.ctx,\n columns as TableColumn<T>[] | undefined\n );\n } else {\n const result = await callApi(hctx, config.listMethod!, requiresWorkspace);\n outputData(\n listResult(result, false),\n hctx.ctx,\n columns as TableColumn<T>[] | undefined\n );\n }\n }\n },\n });\n }\n\n if (config.getMethod) {\n cmds.push({\n path: [...prefix, 'get'],\n description: `Get a ${entityName} by ID`,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n columns: columns as TableColumn<unknown>[] | undefined,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const result = await callApiWithId(hctx, config.getMethod!, id, requiresWorkspace);\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.createMethod) {\n cmds.push({\n path: [...prefix, 'create'],\n description: `Create a ${entityName}`,\n mutates: true,\n requiresWorkspace,\n ...(config.createExamples ? { examples: config.createExamples } : {}),\n handler: async (hctx: CommandHandlerContext) => {\n if (!hctx.data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await callApiWithData(hctx, config.createMethod!, requiresWorkspace);\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.updateMethod) {\n cmds.push({\n path: [...prefix, 'update'],\n description: `Update a ${entityName}`,\n mutates: true,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n if (!hctx.data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = resolveId(hctx);\n const result = await callApiWithIdAndData(\n hctx,\n config.updateMethod!,\n id,\n requiresWorkspace\n );\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.deleteMethod) {\n const deleteArgs: ArgDef[] = [\n { name: 'id', description: `${entityName} ID`, required: true },\n ];\n if (config.supportsCascade) {\n deleteArgs.push({\n name: 'cascade',\n description: 'Also delete dependent child entities',\n required: false,\n isFlag: true,\n });\n }\n cmds.push({\n path: [...prefix, 'delete'],\n description: `Delete a ${entityName}`,\n mutates: true,\n args: deleteArgs,\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n if (config.supportsCascade) {\n const cascade = hctx.args.cascade === true;\n const result = await callMethod(\n hctx,\n config.deleteMethod!,\n requiresWorkspace ? [hctx.workspace, id, cascade] : [id, cascade]\n );\n const suffix =\n result &&\n typeof result === 'object' &&\n 'deletedTaskCount' in result &&\n result.deletedTaskCount\n ? ` and ${result.deletedTaskCount} child entities`\n : '';\n process.stdout.write(`Deleted ${entityName} ${id}${suffix}\\n`);\n } else {\n await callApiWithId(hctx, config.deleteMethod!, id, requiresWorkspace);\n process.stdout.write(`Deleted ${entityName} ${id}\\n`);\n }\n },\n });\n }\n\n if (config.archiveMethod) {\n cmds.push({\n path: [...prefix, 'archive'],\n description: `Archive a ${entityName}`,\n mutates: true,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const result = await callApiWithId(hctx, config.archiveMethod!, id, requiresWorkspace);\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.unarchiveMethod) {\n cmds.push({\n path: [...prefix, 'unarchive'],\n description: `Unarchive a ${entityName}`,\n mutates: true,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const result = await callApiWithId(\n hctx,\n config.unarchiveMethod!,\n id,\n requiresWorkspace\n );\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n return [...cmds, ...extra];\n}\n\nfunction resolveId(hctx: CommandHandlerContext): string {\n const id = (hctx.args.id ?? hctx.args.uuid) as string | undefined;\n if (!id) throw new CLIError('--id is required');\n return id;\n}\n\n/**\n * Encapsulates the dynamic dispatch used by the legacy stringly-typed\n * `crudCommands()` factory. The `GravityRailClient` is structurally typed —\n * we deliberately erase that type here to allow string-key lookup, but the\n * scope of the unsafe access is contained in this single helper instead of\n * leaking into every call site.\n */\nfunction callMethod(\n hctx: CommandHandlerContext,\n method: string,\n args: unknown[]\n): Promise<unknown> {\n const client = requireAuth(hctx.ctx).apiClient as unknown as Record<\n string,\n (...a: unknown[]) => Promise<unknown>\n >;\n const fn = client[method];\n if (typeof fn !== 'function') {\n throw new CLIError(`API method not found: ${method}`);\n }\n return fn.apply(client, args);\n}\n\nasync function callApi(\n hctx: CommandHandlerContext,\n method: string,\n requiresWorkspace: boolean\n): Promise<unknown> {\n return callMethod(hctx, method, requiresWorkspace ? [hctx.workspace] : []);\n}\n\nasync function callApiWithId(\n hctx: CommandHandlerContext,\n method: string,\n id: string,\n requiresWorkspace: boolean\n): Promise<unknown> {\n return callMethod(hctx, method, requiresWorkspace ? [hctx.workspace, id] : [id]);\n}\n\nasync function callApiWithData(\n hctx: CommandHandlerContext,\n method: string,\n requiresWorkspace: boolean\n): Promise<unknown> {\n return callMethod(hctx, method, requiresWorkspace ? [hctx.workspace, hctx.data] : [hctx.data]);\n}\n\nasync function callApiWithIdAndData(\n hctx: CommandHandlerContext,\n method: string,\n id: string,\n requiresWorkspace: boolean\n): Promise<unknown> {\n return callMethod(\n hctx,\n method,\n requiresWorkspace ? [hctx.workspace, id, hctx.data] : [id, hctx.data]\n );\n}\n\nfunction buildListOptions(\n hctx: CommandHandlerContext,\n listArgs: ArgDef[]\n): Record<string, unknown> {\n const opts: Record<string, unknown> = {};\n for (const arg of listArgs) {\n if (arg.name === 'all') continue; // handled by caller, not sent to API\n const key = arg.name.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());\n const val = hctx.args[arg.name];\n if (val !== undefined) {\n if (key === 'page' || key === 'pageSize') {\n const num = Number(val);\n if (isNaN(num) || num < 1)\n throw new CLIError(`--${arg.name} must be a positive integer`);\n if (key === 'pageSize' && num > 100)\n throw new CLIError(`--${arg.name} must be at most 100 (API limit)`);\n opts[key] = num;\n } else {\n opts[key] = val;\n }\n }\n }\n return opts;\n}\n\nasync function callApiWithOptions(\n hctx: CommandHandlerContext,\n method: string,\n requiresWorkspace: boolean,\n opts: Record<string, unknown>\n): Promise<unknown> {\n return callMethod(hctx, method, requiresWorkspace ? [hctx.workspace, opts] : [opts]);\n}\n\n// ---------------------------------------------------------------------------\n// SimpleCrudConfig — typed-callable variant of CrudConfig\n// ---------------------------------------------------------------------------\n\n/**\n * Typed CRUD config for simple, top-level resources.\n *\n * Unlike the stringly-typed `CrudConfig`, operations are typed functions that\n * receive the real `GravityRailClient`. TypeScript validates the call at the definition\n * site, eliminating the string-dispatch + positional-argument blind spot.\n *\n * Use this for resources that fit the simple CRUD contract:\n * - optional workspace scope\n * - single resource ID (no parent IDs)\n * - optional list-options object\n *\n * For nested resources that need parent IDs, use explicit handlers.\n *\n * @example\n * ```ts\n * simpleCrudCommands({\n * prefix: ['tasks'],\n * entityName: 'task',\n * list: (client, wid) => client.getTasks(wid),\n * get: (client, wid, id) => client.getTask(wid, id),\n * create: (client, wid, data) => client.createTask(wid, data),\n * update: (client, wid, id, data) => client.updateTask(wid, id, data),\n * delete: (client, wid, id) => client.deleteTask(wid, id),\n * })\n * ```\n */\nexport interface SimpleCrudConfig<T = unknown> {\n prefix: string[];\n entityName: string;\n columns?: TableColumn<T>[];\n requiresWorkspace?: boolean;\n listArgs?: ArgDef[];\n extra?: CommandDef[];\n createExamples?: string[];\n paginationSupport?: 'full' | 'client-only' | false;\n\n // Typed operations — each receives the real GravityRailClient and typed positional args\n list?: (\n client: GravityRailClient,\n workspace: string,\n opts?: Record<string, unknown>\n ) => Promise<unknown>;\n get?: (client: GravityRailClient, workspace: string, id: string) => Promise<unknown>;\n create?: (client: GravityRailClient, workspace: string, data: unknown) => Promise<unknown>;\n update?: (\n client: GravityRailClient,\n workspace: string,\n id: string,\n data: unknown\n ) => Promise<unknown>;\n delete?: (client: GravityRailClient, workspace: string, id: string) => Promise<unknown>;\n archive?: (client: GravityRailClient, workspace: string, id: string) => Promise<unknown>;\n unarchive?: (client: GravityRailClient, workspace: string, id: string) => Promise<unknown>;\n\n /** When true, adds a --cascade flag to the delete command. */\n supportsCascade?: boolean;\n deleteFn?: (\n client: GravityRailClient,\n workspace: string,\n id: string,\n cascade: boolean\n ) => Promise<unknown>;\n}\n\n/**\n * Generate CRUD commands from typed callable functions.\n *\n * This is the recommended path for new simple CRUD domains. It provides\n * compile-time safety by accepting typed callables instead of string method names.\n */\nexport function simpleCrudCommands<T>(config: SimpleCrudConfig<T>): CommandDef[] {\n const {\n prefix,\n entityName,\n columns,\n requiresWorkspace = true,\n listArgs = [],\n extra = [],\n } = config;\n\n const paginationSupport = config.paginationSupport ?? false;\n const cmds: CommandDef[] = [];\n\n if (config.list) {\n const listFn = config.list;\n const injectPaginationArgs = paginationSupport !== false;\n const seenArgNames = new Set(listArgs.map((a) => a.name));\n const mergedArgs = injectPaginationArgs\n ? [...listArgs, ...LIST_PAGINATION_ARGS.filter((a) => !seenArgNames.has(a.name))]\n : [...listArgs];\n\n cmds.push({\n path: [...prefix, 'list'],\n description: `List ${entityName}s`,\n args: mergedArgs,\n requiresWorkspace,\n columns: columns as TableColumn<unknown>[] | undefined,\n handler: async (hctx: CommandHandlerContext) => {\n const client = requireAuth(hctx.ctx).apiClient;\n const domainHasListArgs = listArgs.length > 0;\n\n if (injectPaginationArgs && hctx.args['all']) {\n let allItems: unknown[];\n if (paginationSupport === 'full') {\n allItems = await fetchAllPages(async ({ page, pageSize }) => {\n const opts = buildListOptions(hctx, listArgs);\n opts['page'] = page;\n opts['pageSize'] = pageSize;\n return listFn(client, hctx.workspace, opts);\n });\n } else {\n const result = await listFn(client, hctx.workspace);\n allItems = unwrapItems(result);\n }\n outputData(allItems, hctx.ctx, columns as TableColumn<T>[] | undefined);\n } else if (paginationSupport === 'full') {\n const opts = buildListOptions(hctx, mergedArgs);\n const result =\n domainHasListArgs || Object.keys(opts).length > 0\n ? await listFn(client, hctx.workspace, opts)\n : await listFn(client, hctx.workspace);\n outputData(\n listResult(result, true),\n hctx.ctx,\n columns as TableColumn<T>[] | undefined\n );\n } else {\n if (domainHasListArgs) {\n const opts = buildListOptions(hctx, listArgs);\n const result =\n Object.keys(opts).length > 0\n ? await listFn(client, hctx.workspace, opts)\n : await listFn(client, hctx.workspace);\n outputData(\n listResult(result, false),\n hctx.ctx,\n columns as TableColumn<T>[] | undefined\n );\n } else {\n const result = await listFn(client, hctx.workspace);\n outputData(\n listResult(result, false),\n hctx.ctx,\n columns as TableColumn<T>[] | undefined\n );\n }\n }\n },\n });\n }\n\n if (config.get) {\n const getFn = config.get;\n cmds.push({\n path: [...prefix, 'get'],\n description: `Get a ${entityName} by ID`,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n columns: columns as TableColumn<unknown>[] | undefined,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const result = await getFn(requireAuth(hctx.ctx).apiClient, hctx.workspace, id);\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.create) {\n const createFn = config.create;\n cmds.push({\n path: [...prefix, 'create'],\n description: `Create a ${entityName}`,\n mutates: true,\n requiresWorkspace,\n ...(config.createExamples ? { examples: config.createExamples } : {}),\n handler: async (hctx: CommandHandlerContext) => {\n if (!hctx.data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await createFn(\n requireAuth(hctx.ctx).apiClient,\n hctx.workspace,\n hctx.data\n );\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.update) {\n const updateFn = config.update;\n cmds.push({\n path: [...prefix, 'update'],\n description: `Update a ${entityName}`,\n mutates: true,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n if (!hctx.data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = resolveId(hctx);\n const result = await updateFn(\n requireAuth(hctx.ctx).apiClient,\n hctx.workspace,\n id,\n hctx.data\n );\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.delete || config.deleteFn) {\n const deleteArgs: ArgDef[] = [\n { name: 'id', description: `${entityName} ID`, required: true },\n ];\n if (config.supportsCascade) {\n deleteArgs.push({\n name: 'cascade',\n description: 'Also delete dependent child entities',\n required: false,\n isFlag: true,\n });\n }\n cmds.push({\n path: [...prefix, 'delete'],\n description: `Delete a ${entityName}`,\n mutates: true,\n args: deleteArgs,\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const client = requireAuth(hctx.ctx).apiClient;\n if (config.deleteFn) {\n const cascade = config.supportsCascade ? hctx.args.cascade === true : false;\n const result = await config.deleteFn(client, hctx.workspace, id, cascade);\n const suffix =\n result &&\n typeof result === 'object' &&\n 'deletedTaskCount' in result &&\n result.deletedTaskCount\n ? ` and ${result.deletedTaskCount} child entities`\n : '';\n process.stdout.write(`Deleted ${entityName} ${id}${suffix}\\n`);\n } else if (config.delete) {\n await config.delete(client, hctx.workspace, id);\n process.stdout.write(`Deleted ${entityName} ${id}\\n`);\n }\n },\n });\n }\n\n if (config.archive) {\n const archiveFn = config.archive;\n cmds.push({\n path: [...prefix, 'archive'],\n description: `Archive a ${entityName}`,\n mutates: true,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const result = await archiveFn(requireAuth(hctx.ctx).apiClient, hctx.workspace, id);\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.unarchive) {\n const unarchiveFn = config.unarchive;\n cmds.push({\n path: [...prefix, 'unarchive'],\n description: `Unarchive a ${entityName}`,\n mutates: true,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const result = await unarchiveFn(requireAuth(hctx.ctx).apiClient, hctx.workspace, id);\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n return [...cmds, ...extra];\n}\n","import type { CommandDef, DomainDef } from './types';\n\nexport class CommandRegistry {\n private commands = new Map<string, CommandDef>();\n private domains: DomainDef[] = [];\n\n register(domain: DomainDef): void {\n this.domains.push(domain);\n for (const cmd of domain.commands) {\n const key = cmd.path.join(' ');\n this.commands.set(key, cmd);\n }\n }\n\n registerCommand(cmd: CommandDef): void {\n const key = cmd.path.join(' ');\n this.commands.set(key, cmd);\n }\n\n /** Resolve command words to a CommandDef using longest-match.\n * Supports {param} path segments that match any word and extract as pathParams. */\n resolve(\n words: string[]\n ): { cmd: CommandDef; rest: string[]; pathParams: Record<string, string> } | undefined {\n // Try exact match first (4-word, 3-word, 2-word, 1-word)\n for (let len = Math.min(words.length, 4); len >= 1; len--) {\n const key = words.slice(0, len).join(' ');\n const cmd = this.commands.get(key);\n if (cmd) {\n return { cmd, rest: words.slice(len), pathParams: {} };\n }\n }\n // Try pattern match ({param} segments)\n for (const [, cmd] of this.commands) {\n if (cmd.path.length > words.length) continue;\n const params: Record<string, string> = {};\n let matched = true;\n for (let i = 0; i < cmd.path.length; i++) {\n const segment = cmd.path[i]!;\n const word = words[i]!;\n if (segment.startsWith('{') && segment.endsWith('}')) {\n params[segment.slice(1, -1)] = word;\n } else if (segment !== word) {\n matched = false;\n break;\n }\n }\n if (matched) {\n return { cmd, rest: words.slice(cmd.path.length), pathParams: params };\n }\n }\n return undefined;\n }\n\n /** Generate help text. If prefix given, show commands under that prefix. */\n getHelp(prefix?: string[]): string {\n if (!prefix || prefix.length === 0) {\n return this.getTopLevelHelp();\n }\n\n const prefixStr = prefix.join(' ');\n const matching: CommandDef[] = [];\n for (const [key, cmd] of this.commands) {\n if (key.startsWith(prefixStr + ' ') || key === prefixStr) {\n matching.push(cmd);\n }\n }\n\n // Also match commands with {param} segments in the prefix position\n for (const [, cmd] of this.commands) {\n if (matching.includes(cmd)) continue;\n if (cmd.path.length <= prefix.length) continue;\n let prefixMatches = true;\n for (let i = 0; i < prefix.length; i++) {\n const seg = cmd.path[i]!;\n if (seg !== prefix[i] && !(seg.startsWith('{') && seg.endsWith('}'))) {\n prefixMatches = false;\n break;\n }\n }\n if (prefixMatches) matching.push(cmd);\n }\n\n if (matching.length === 0) {\n return `No commands found for: ${prefixStr}`;\n }\n\n // If exactly one command matched (leaf command), show detailed help\n if (matching.length === 1 && matching[0]!.path.join(' ') === prefixStr) {\n return this.getCommandHelp(matching[0]!);\n }\n\n // Determine the placeholder: if all next segments are {param}, use that param name\n const nextSegments = new Set(matching.map((cmd) => cmd.path[prefix.length]).filter(Boolean));\n const allParams = [...nextSegments].every((s) => s!.startsWith('{') && s!.endsWith('}'));\n const placeholder =\n allParams && nextSegments.size === 1\n ? `<${[...nextSegments][0]!.slice(1, -1)}>`\n : '<command>';\n\n const lines = [`Usage: gr ${prefixStr} ${placeholder} [options]\\n`, 'Commands:'];\n for (const cmd of matching.sort((a, b) => a.path.join(' ').localeCompare(b.path.join(' ')))) {\n const subPath = cmd.path.slice(prefix.length).join(' ') || cmd.path[cmd.path.length - 1]!;\n lines.push(` ${subPath.padEnd(28)} ${cmd.description}`);\n }\n return lines.join('\\n') + '\\n';\n }\n\n private getCommandHelp(cmd: CommandDef): string {\n const cmdStr = cmd.path.join(' ');\n const lines = [`${cmd.description}\\n`, `Usage: gr ${cmdStr} [options]`];\n\n if (cmd.requiresWorkspace) {\n lines.push(' Requires: -w <workspace-uuid>');\n }\n if (cmd.mutates) {\n lines.push(' Requires: --allow-write');\n }\n\n if (cmd.args && cmd.args.length > 0) {\n lines.push('', 'Arguments:');\n for (const arg of cmd.args) {\n const flag = arg.isFlag ? `--${arg.name}` : `--${arg.name} <value>`;\n const req = arg.required ? ' (required)' : '';\n lines.push(` ${flag.padEnd(28)} ${arg.description}${req}`);\n }\n }\n\n if (cmd.examples && cmd.examples.length > 0) {\n lines.push('', 'Examples:');\n for (const ex of cmd.examples) {\n lines.push(` ${ex}`);\n }\n }\n\n return lines.join('\\n') + '\\n';\n }\n\n private getTopLevelHelp(): string {\n const lines = ['Usage: gr <command> [options]\\n', 'Commands:'];\n\n // Group by domain\n const seen = new Set<string>();\n for (const domain of this.domains) {\n if (!seen.has(domain.name)) {\n seen.add(domain.name);\n lines.push(` ${domain.name.padEnd(28)} ${domain.description}`);\n }\n }\n\n // Add standalone commands (not in any domain)\n for (const [, cmd] of this.commands) {\n const topWord = cmd.path[0]!;\n if (!seen.has(topWord) && cmd.path.length === 1) {\n seen.add(topWord);\n lines.push(` ${topWord.padEnd(28)} ${cmd.description}`);\n }\n }\n\n lines.push(\n '',\n 'Global Options:',\n ' --env <env> Environment: dev, staging, prod (default: dev)',\n ' -o, --output-format <fmt> Output format: json, jsonl, table (default: auto)',\n ' -v, --verbose Verbose output to stderr',\n ' --help Show help',\n ' --version Show version'\n );\n\n return lines.join('\\n') + '\\n';\n }\n}\n","import type { AuthenticatedContext, CommandContext } from './context';\nimport type { TableColumn } from './output';\n\nexport interface ArgDef {\n name: string;\n alias?: string;\n /** Additional long-form aliases (e.g. ['workspace-id', 'id'] for --wid) */\n aliases?: string[];\n description: string;\n required?: boolean;\n isFlag?: boolean;\n default?: string | boolean;\n}\n\nexport type ParsedArgs = Record<string, string | boolean | undefined>;\n\n/**\n * Context passed to a command handler.\n *\n * `ctx` is a discriminated union of `AuthenticatedContext` and `CommandContext`.\n * Handlers registered without `requiresAuth: false` always receive an\n * `AuthenticatedContext` at runtime, but the type does not express this — call\n * `requireAuth(hctx.ctx)` before accessing `apiClient` / `accessToken` so that\n * a handler missing `requiresAuth: false` cannot silently access undefined\n * fields if it is later miswired.\n */\nexport interface CommandHandlerContext {\n ctx: AuthenticatedContext | CommandContext;\n args: ParsedArgs;\n workspace: string;\n data?: unknown;\n}\n\nexport interface CommandDef<T = unknown> {\n path: string[];\n description: string;\n args?: ArgDef[];\n /** Example usage lines shown in command-level help */\n examples?: string[];\n requiresWorkspace?: boolean;\n requiresAuth?: boolean;\n /** Whether this command mutates data. Requires --allow-write to execute. */\n mutates?: boolean;\n columns?: TableColumn<T>[];\n handler: (hctx: CommandHandlerContext) => Promise<void>;\n}\n\nexport interface DomainDef {\n name: string;\n description: string;\n commands: CommandDef[];\n}\n\n/** Extract a required string arg, throwing if missing or not a string */\nexport function requireString(args: ParsedArgs, key: string): string {\n const val = args[key];\n if (typeof val !== 'string') throw new Error(`Missing required argument: --${key}`);\n return val;\n}\n\n/** Extract a required numeric arg, throwing if missing */\nexport function requireNumber(args: ParsedArgs, key: string): number {\n const val = args[key];\n if (typeof val !== 'string') throw new Error(`Missing required argument: --${key}`);\n const num = Number(val);\n if (isNaN(num)) throw new Error(`Argument --${key} must be a number`);\n return num;\n}\n","import type { DomainDef } from '../lib/types';\nimport { requireString } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\n// Operator-facing CLI domain for async sub-agent tasks.\n//\n// Unlike the LLM a2a tools (which are scoped to the requestor for\n// inter-agent isolation), this domain calls workspace-scoped HTTP routes\n// that return any agent task in the workspace. The routes require the\n// caller to hold MEMBERS_READ / MEMBERS_WRITE — they are for operators,\n// not sibling agents.\n\nconst LIST_COLUMNS: TableColumn<unknown>[] = [\n { header: 'UUID', getValue: (item: any) => String(item.uuid ?? '') },\n { header: 'STATUS', getValue: (item: any) => String(item.status ?? '') },\n {\n header: 'AGENT',\n getValue: (item: any) => (item.agentMemberId != null ? String(item.agentMemberId) : ''),\n },\n { header: 'DEPTH', getValue: (item: any) => String(item.depth ?? 0) },\n { header: 'CREATED', getValue: (item: any) => String(item.createdAt ?? '') },\n];\n\nconst MESSAGE_COLUMNS: TableColumn<unknown>[] = [\n { header: 'ROLE', getValue: (item: any) => String(item.role ?? '') },\n {\n header: 'TIMESTAMP',\n getValue: (item: any) => String(item.receivedAt ?? ''),\n },\n {\n header: 'CONTENT',\n getValue: (item: any) => {\n const content = String(item.content ?? '');\n const oneLine = content.replace(/\\s+/g, ' ').trim();\n return oneLine.length > 80 ? `${oneLine.slice(0, 77)}...` : oneLine;\n },\n },\n];\n\nexport const agentTasksDomain: DomainDef = {\n name: 'agent-tasks',\n description:\n 'Inspect and cancel async sub-agent tasks (operator-facing; requires members_read/write)',\n commands: [\n {\n path: ['agent-tasks', 'list'],\n description: 'List agent tasks in the workspace (newest first)',\n requiresWorkspace: true,\n args: [\n {\n name: 'status',\n description:\n 'Filter by A2A state (submitted|working|input-required|completed|failed|canceled|rejected|auth-required)',\n required: false,\n },\n {\n name: 'agent',\n description: 'Filter by executing agent member id',\n required: false,\n },\n {\n name: 'parent-task',\n description:\n 'Filter by parent agent task uuid (not supported server-side yet — filters by id)',\n required: false,\n },\n {\n name: 'limit',\n description: 'Max rows to return (default 50)',\n required: false,\n },\n ],\n columns: LIST_COLUMNS,\n handler: async ({ ctx, workspace, args }) => {\n const params: {\n status?: any;\n agentMemberId?: number;\n parentTaskId?: number;\n limit?: number;\n } = {};\n if (typeof args.status === 'string') params.status = args.status;\n if (typeof args.agent === 'string') {\n const n = Number(args.agent);\n if (!isNaN(n)) params.agentMemberId = n;\n }\n if (typeof args['parent-task'] === 'string') {\n const n = Number(args['parent-task']);\n if (!isNaN(n)) params.parentTaskId = n;\n }\n if (typeof args.limit === 'string') {\n const n = Number(args.limit);\n if (!isNaN(n)) params.limit = n;\n }\n const result = await requireAuth(ctx).apiClient.getAgentTasks(workspace, params);\n outputData(result, ctx, LIST_COLUMNS);\n },\n },\n {\n path: ['agent-tasks', 'get'],\n description: 'Get a single agent task by UUID',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Agent task UUID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getAgentTask(\n workspace,\n requireString(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['agent-tasks', 'cancel'],\n description: 'Cancel a running agent task (idempotent; terminal tasks are returned as-is)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Agent task UUID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.cancelAgentTask(\n workspace,\n requireString(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['agent-tasks', 'messages'],\n description: 'Show recent messages from a sub-agent task context chat',\n requiresWorkspace: true,\n args: [\n { name: 'id', description: 'Agent task UUID', required: true },\n {\n name: 'limit',\n description: 'Max messages to return (default 20)',\n required: false,\n },\n ],\n columns: MESSAGE_COLUMNS,\n handler: async ({ ctx, workspace, args }) => {\n const params: { limit?: number } = {};\n if (typeof args.limit === 'string') {\n const n = Number(args.limit);\n if (!isNaN(n)) params.limit = n;\n }\n const result = await requireAuth(ctx).apiClient.getAgentTaskMessages(\n workspace,\n requireString(args, 'id'),\n params\n );\n outputData(result, ctx, MESSAGE_COLUMNS);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { COL } from '../lib/output';\n\nconst COLUMNS = [COL.id(), COL.uuid(), COL.name(), COL.status(), COL.created()];\n\nexport const agentsDomain: DomainDef = {\n name: 'agents',\n description: 'Manage agents',\n commands: [\n ...crudCommands({\n prefix: ['agents'],\n entityName: 'agent',\n listMethod: 'getAgents',\n getMethod: 'getAgent',\n createMethod: 'createAgent',\n updateMethod: 'updateAgent',\n deleteMethod: 'deleteAgent',\n archiveMethod: 'archiveAgent',\n unarchiveMethod: 'unarchiveAgent',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { AGUIClient, getTextDelta, getErrorMessage } from '../cli-utils';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n { header: 'MEMBER', getValue: (item: any) => item.member_name ?? String(item.member_id ?? '') },\n COL.status(),\n { header: 'CHANNEL', getValue: (item: any) => item.channel ?? '' },\n COL.created(),\n];\n\nconst LABEL_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n COL.name(),\n { header: 'COLOR', getValue: (item: any) => item.color ?? '' },\n];\n\nconst FILTER_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.uuid(), COL.name()];\n\nconst MESSAGE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'ROLE', getValue: (item: any) => item.role ?? '' },\n {\n header: 'CONTENT',\n getValue: (item: any) => String(item.content ?? '').slice(0, 80),\n maxWidth: 80,\n },\n {\n header: 'TOOL_CALLS',\n getValue: (item: any) =>\n Array.isArray(item.tool_calls) && item.tool_calls.length > 0\n ? item.tool_calls.map((t: any) => t.function?.name ?? '?').join(',')\n : '',\n },\n COL.created(),\n];\n\nexport const chatsDomain: DomainDef = {\n name: 'chats',\n description: 'Manage chats',\n commands: [\n ...crudCommands({\n prefix: ['chats'],\n entityName: 'chat',\n listMethod: 'getChats',\n getMethod: 'getChat',\n createMethod: 'createChat',\n updateMethod: 'updateChat',\n deleteMethod: 'deleteChat',\n archiveMethod: 'archiveChat',\n unarchiveMethod: 'unarchiveChat',\n columns: COLUMNS,\n paginationSupport: 'full',\n listArgs: [\n { name: 'search', description: 'Search by name' },\n { name: 'channel', description: 'Filter by channel (phone, sms, web, email)' },\n {\n name: 'is-anonymous',\n description: 'Show only anonymous chats (requires CHATS_ADMIN)',\n isFlag: true,\n },\n { name: 'is-test', description: 'Show only test chats', isFlag: true },\n { name: 'member-id', description: 'Filter by member ID' },\n ],\n }),\n // Messages\n {\n path: ['chats', 'messages', 'list'],\n description:\n 'List messages for a chat. Use --limit/--offset to page; the API caps a single request at 100. Tool-call shell rows that the API filter excludes (parent_message_id IS NOT NULL or parent_call_id IS NOT NULL) are still hidden — use `gr chats inspect --id <chat>` for the full debug view.',\n requiresWorkspace: true,\n args: [\n { name: 'chat-id', description: 'Chat ID', required: true },\n {\n name: 'limit',\n description: 'Max messages to return (1-100, default 100)',\n },\n {\n name: 'offset',\n description: 'Offset for pagination (default 0)',\n },\n ],\n handler: async ({ ctx, workspace, args }) => {\n // Default to 100 (the API max). The API's own default of 10\n // hides almost every message in long voice chats — operators\n // hit it constantly when debugging EventRule canned messages\n // that show up later in the conversation. See\n // docs/dev/xai-grok-voice-agent-audit-2026-04-24.md \"P5\".\n const rawLimit = (args as any).limit;\n const rawOffset = (args as any).offset;\n const limit =\n rawLimit === undefined || rawLimit === null || rawLimit === ''\n ? 100\n : Number(rawLimit);\n const offset =\n rawOffset === undefined || rawOffset === null || rawOffset === ''\n ? 0\n : Number(rawOffset);\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) {\n throw new Error('--limit must be an integer between 1 and 100');\n }\n if (!Number.isInteger(offset) || offset < 0) {\n throw new Error('--offset must be a non-negative integer');\n }\n const result = await requireAuth(ctx).apiClient.getChatMessages(\n workspace,\n requireNumber(args, 'chat-id'),\n limit,\n offset\n );\n outputData(result, ctx, MESSAGE_COLUMNS);\n },\n },\n {\n path: ['chats', 'messages', 'send'],\n description:\n 'Send a user message to a chat (triggers AI inference). Use --stream to stream the response.',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'chat-id', description: 'Chat ID', required: true },\n { name: 'stream', description: 'Stream the AI response via AG-UI', isFlag: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const content = typeof data === 'string' ? data : (data as any)?.content;\n if (!content)\n throw new Error(\n 'Message content is required (pass --data \\'\"your message\"\\' or --data \\'{\"content\":\"your message\"}\\')'\n );\n const chatId = requireNumber(args, 'chat-id');\n\n if (args.stream) {\n // Stream via AG-UI protocol\n const aguiClient = new AGUIClient({\n baseUrl: ctx.envConfig.apiUrl,\n workspaceUuid: workspace,\n chatId,\n accessToken: requireAuth(ctx).accessToken,\n });\n process.stdout.write('\\x1B[32mAssistant:\\x1B[0m ');\n await aguiClient.sendMessage([{ role: 'user', content }], (event) => {\n const delta = getTextDelta(event);\n if (delta) process.stdout.write(delta);\n const errorMsg = getErrorMessage(event);\n if (errorMsg) process.stderr.write(`\\n\\x1B[31mError: ${errorMsg}\\x1B[0m\\n`);\n });\n process.stdout.write('\\n');\n } else {\n const result = await requireAuth(ctx).apiClient.sendChatMessage(\n workspace,\n chatId,\n content\n );\n outputSingle(result, ctx, MESSAGE_COLUMNS);\n }\n },\n },\n {\n path: ['chats', 'messages', 'send-as-assistant'],\n description: 'Send an assistant message to a chat (does not trigger AI inference)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'chat-id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.sendAssistantMessage(\n workspace,\n requireNumber(args, 'chat-id'),\n data as any\n );\n outputSingle(result, ctx, MESSAGE_COLUMNS);\n },\n },\n // Summarize\n {\n path: ['chats', 'summarize'],\n description: 'Summarize a chat',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.summarizeChat(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n // Export\n {\n path: ['chats', 'export'],\n description: 'Export a single chat',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.exportChat(\n workspace,\n requireNumber(args, 'id')\n );\n process.stdout.write(await result.text());\n },\n },\n {\n path: ['chats', 'export-all'],\n description: 'Export all chats',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.exportChats(workspace);\n process.stdout.write(await result.text());\n },\n },\n // Token usage\n {\n path: ['chats', 'token-usage'],\n description: 'Get token usage for a chat',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getChatTokenUsage(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n // Needs response\n {\n path: ['chats', 'needs-response'],\n description: 'List chats that need a response',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getChatsNeedsResponse(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n // Inspect (aggregated debug view)\n {\n path: ['chats', 'inspect'],\n description: 'Inspect a chat with messages, assignment state, and data records',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const chatId = requireNumber(args, 'id');\n const [chat, messages, ws] = await Promise.all([\n requireAuth(ctx).apiClient.getChat(workspace, chatId),\n requireAuth(ctx).apiClient.getChatMessages(workspace, chatId),\n requireAuth(ctx).apiClient.getWorkspace(workspace),\n ]);\n const isHipaa = ws.features?.includes('hipaa_compliance' as any);\n\n const truncate = (content: unknown) => {\n const text = typeof content === 'string' ? content : JSON.stringify(content);\n return text.slice(0, 200);\n };\n\n const result: Record<string, unknown> = {\n chat: {\n id: chat.id,\n title: chat.title,\n channel: chat.channel,\n chatType: chat.chatType,\n workflowId: chat.workflowId,\n assignmentId: chat.assignmentId,\n messageCount: chat.messageCount,\n createdAt: chat.createdAt,\n },\n messages: messages.map((m: any) => ({\n id: m.id,\n role: m.role,\n content: isHipaa ? '[REDACTED — HIPAA workspace]' : truncate(m.content),\n })),\n };\n\n // If assignment chat, fetch assignment with current task + data records\n const assignmentId = chat.assignmentId;\n if (assignmentId) {\n const assignment = await requireAuth(ctx).apiClient.getAssignment(\n workspace,\n assignmentId\n );\n result.assignment = {\n id: assignment.id,\n status: assignment.status,\n workflowId: assignment.workflowId,\n workflowName: assignment.workflowName,\n currentTask: assignment.currentTask,\n dataRecords: assignment.dataRecords?.map((dr: any) => ({\n id: dr.id,\n dataTypeId: dr.dataTypeId,\n fieldValues: isHipaa ? '[REDACTED — HIPAA workspace]' : dr.fieldValues,\n })),\n };\n }\n\n outputSingle(result, ctx);\n },\n },\n // Chat Labels CRUD\n ...crudCommands({\n prefix: ['chats', 'labels'],\n entityName: 'chat label',\n listMethod: 'getChatLabels',\n getMethod: 'getChatLabel',\n createMethod: 'createChatLabel',\n updateMethod: 'updateChatLabel',\n deleteMethod: 'deleteChatLabel',\n columns: LABEL_COLUMNS,\n }),\n // Chat Filters CRUD\n ...crudCommands({\n prefix: ['chats', 'filters'],\n entityName: 'chat filter',\n listMethod: 'getChatFilters',\n getMethod: 'getChatFilter',\n createMethod: 'createChatFilter',\n updateMethod: 'updateChatFilter',\n deleteMethod: 'deleteChatFilter',\n columns: FILTER_COLUMNS,\n }),\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { CLIError } from '../lib/errors';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n COL.name(),\n { header: 'ROLE', getValue: (item: any) => item.role ?? '' },\n COL.status(),\n COL.created(),\n];\n\nconst LABEL_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n COL.name(),\n { header: 'COLOR', getValue: (item: any) => item.color ?? '' },\n];\n\nconst FILTER_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.uuid(), COL.name()];\n\nconst FIELD_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'TYPE', getValue: (item: any) => item.field_type ?? '' },\n { header: 'REQUIRED', getValue: (item: any) => String(item.required ?? false) },\n];\n\nconst ROLE_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.uuid(), COL.name()];\n\nexport const membersDomain: DomainDef = {\n name: 'members',\n description: 'Manage members',\n commands: [\n ...crudCommands({\n prefix: ['members'],\n entityName: 'member',\n listMethod: 'getWorkspaceMembers',\n getMethod: 'getWorkspaceMember',\n createMethod: 'createWorkspaceMember',\n updateMethod: 'updateMember',\n deleteMethod: 'deleteMember',\n archiveMethod: 'archiveMember',\n unarchiveMethod: 'unarchiveMember',\n columns: COLUMNS,\n }),\n // Current member\n {\n path: ['members', 'me'],\n description: 'Get the current member',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getCurrentMember(workspace);\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Import/Export\n {\n path: ['members', 'import'],\n description: 'Import members from data',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await (requireAuth(ctx).apiClient as any).importMembers(workspace, data);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['members', 'export'],\n description: 'Export members',\n requiresWorkspace: true,\n args: [\n {\n name: 'fields',\n description:\n 'Comma-separated field names (default: id,name,email,phone,member_type,labels)',\n },\n {\n name: 'member-type',\n description: 'Filter by member type: member, test, anonymous',\n },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const defaultFields = ['id', 'name', 'email', 'phone', 'member_type', 'labels'];\n const fields = args.fields\n ? String(args.fields)\n .split(',')\n .map((f: string) => f.trim())\n : defaultFields;\n const memberType = args['member-type'] as 'member' | 'test' | 'anonymous' | undefined;\n const result = await (requireAuth(ctx).apiClient as any).exportMembers(\n workspace,\n fields,\n [],\n memberType\n );\n process.stdout.write(await result.text());\n },\n },\n // Member Labels CRUD\n ...crudCommands({\n prefix: ['members', 'labels'],\n entityName: 'member label',\n listMethod: 'getMemberLabels',\n getMethod: 'getMemberLabel',\n createMethod: 'createMemberLabel',\n updateMethod: 'updateMemberLabel',\n deleteMethod: 'deleteMemberLabel',\n columns: LABEL_COLUMNS,\n }),\n // Member Filters CRUD\n ...crudCommands({\n prefix: ['members', 'filters'],\n entityName: 'member filter',\n listMethod: 'getMemberFilters',\n getMethod: 'getMemberFilter',\n createMethod: 'createMemberFilter',\n updateMethod: 'updateMemberFilter',\n deleteMethod: 'deleteMemberFilter',\n columns: FILTER_COLUMNS,\n }),\n // Member Fields — nested resource requiring memberId\n {\n path: ['members', 'fields', 'list'],\n description: 'List fields for a member',\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const memberId = requireNumber(args, 'member-id');\n const result = await requireAuth(ctx).apiClient.getMemberFields(workspace, memberId);\n outputData(result, ctx, FIELD_COLUMNS);\n },\n },\n {\n path: ['members', 'fields', 'create'],\n description: 'Create a member field',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const memberId = requireNumber(args, 'member-id');\n const result = await requireAuth(ctx).apiClient.createMemberField(\n workspace,\n memberId,\n data as any\n );\n outputSingle(result, ctx, FIELD_COLUMNS);\n },\n },\n {\n path: ['members', 'fields', 'update'],\n description: 'Update a member field',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'id', description: 'Field ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const memberId = requireNumber(args, 'member-id');\n const fieldId = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.updateMemberField(\n workspace,\n memberId,\n fieldId,\n data as any\n );\n outputSingle(result, ctx, FIELD_COLUMNS);\n },\n },\n {\n path: ['members', 'fields', 'delete'],\n description: 'Delete a member field',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'id', description: 'Field ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const memberId = requireNumber(args, 'member-id');\n const fieldId = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.deleteMemberField(workspace, memberId, fieldId);\n process.stdout.write(`Deleted member field ${fieldId}\\n`);\n },\n },\n // Member Roles CRUD\n ...crudCommands({\n prefix: ['members', 'roles'],\n entityName: 'member role',\n listMethod: 'getMemberRoles',\n getMethod: 'getMemberRole',\n createMethod: 'createMemberRole',\n updateMethod: 'updateMemberRole',\n deleteMethod: 'deleteMemberRole',\n columns: ROLE_COLUMNS,\n }),\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n COL.name(),\n COL.status(),\n {\n header: 'WORKFLOW',\n getValue: (item: any) => item.workflow_name ?? String(item.workflow_id ?? ''),\n },\n COL.created(),\n];\n\nexport const tasksDomain: DomainDef = {\n name: 'tasks',\n description: 'Manage tasks',\n commands: [\n ...crudCommands({\n prefix: ['tasks'],\n entityName: 'task',\n listMethod: 'getTasks',\n getMethod: 'getTask',\n createMethod: 'createTask',\n updateMethod: 'updateTask',\n deleteMethod: 'deleteTask',\n archiveMethod: 'archiveTask',\n unarchiveMethod: 'unarchiveTask',\n columns: COLUMNS,\n }),\n {\n path: ['tasks', 'clone'],\n description: 'Clone a task',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Task ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.cloneTask(\n workspace,\n requireNumber(args, 'id'),\n (data as any)?.name ?? '',\n (data as any)?.slug\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['tasks', 'ability-types'],\n description: 'List available ability types',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getAbilityTypes(workspace);\n outputData(result, ctx);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { CLIError } from '../lib/errors';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n COL.name(),\n { header: 'TASKS', getValue: (item: any) => String(item.taskCount ?? '') },\n COL.created(),\n];\n\nconst NOTE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'TITLE', getValue: (item: any) => item.title ?? '' },\n {\n header: 'CONTENT',\n getValue: (item: any) => String(item.content ?? '').slice(0, 60),\n maxWidth: 60,\n },\n COL.created(),\n];\n\nconst CONTRIBUTOR_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n {\n header: 'ACCOUNT',\n getValue: (item: any) => item.account_name ?? String(item.account_id ?? ''),\n },\n { header: 'ROLE', getValue: (item: any) => item.role ?? '' },\n];\n\nconst TEMPLATE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n {\n header: 'DESCRIPTION',\n getValue: (item: any) => String(item.description ?? '').slice(0, 60),\n maxWidth: 60,\n },\n];\n\nexport const workflowsDomain: DomainDef = {\n name: 'workflows',\n description: 'Manage workflows',\n commands: [\n ...crudCommands({\n prefix: ['workflows'],\n entityName: 'workflow',\n listMethod: 'getWorkflows',\n getMethod: 'getWorkflow',\n createMethod: 'createWorkflow',\n updateMethod: 'updateWorkflow',\n deleteMethod: 'deleteWorkflow',\n supportsCascade: true,\n archiveMethod: 'archiveWorkflow',\n unarchiveMethod: 'unarchiveWorkflow',\n columns: COLUMNS,\n }),\n // Clone\n {\n path: ['workflows', 'clone'],\n description: 'Clone a workflow',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.cloneWorkflow(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Templates\n {\n path: ['workflows', 'templates'],\n description: 'List workflow templates',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getWorkflowTemplates(workspace);\n outputData(result, ctx, TEMPLATE_COLUMNS);\n },\n },\n {\n path: ['workflows', 'create-from-template'],\n description: 'Create a workflow from a template',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.createWorkflowFromTemplate(\n workspace,\n (data as any)?.templateUuid ?? '',\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Activity\n {\n path: ['workflows', 'activity'],\n description: 'Get workflow activity',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getWorkflowActivity(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n // Diagram\n {\n path: ['workflows', 'diagram'],\n description: 'Get workflow diagram',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getWorkflowDiagram(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n // Notes — nested resource requiring workflowId\n {\n path: ['workflows', 'notes', 'list'],\n description: 'List workflow notes',\n requiresWorkspace: true,\n args: [{ name: 'workflow-id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const workflowId = requireNumber(args, 'workflow-id');\n const result = await requireAuth(ctx).apiClient.getWorkflowNotes(workspace, workflowId);\n outputData(result, ctx, NOTE_COLUMNS);\n },\n },\n {\n path: ['workflows', 'notes', 'create'],\n description: 'Create a workflow note',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'workflow-id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const workflowId = requireNumber(args, 'workflow-id');\n const result = await requireAuth(ctx).apiClient.createWorkflowNote(\n workspace,\n workflowId,\n data as any\n );\n outputSingle(result, ctx, NOTE_COLUMNS);\n },\n },\n {\n path: ['workflows', 'notes', 'update'],\n description: 'Update a workflow note',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'workflow-id', description: 'Workflow ID', required: true },\n { name: 'id', description: 'Note ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const workflowId = requireNumber(args, 'workflow-id');\n const noteId = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.updateWorkflowNote(\n workspace,\n workflowId,\n noteId,\n data as any\n );\n outputSingle(result, ctx, NOTE_COLUMNS);\n },\n },\n {\n path: ['workflows', 'notes', 'delete'],\n description: 'Delete a workflow note',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'workflow-id', description: 'Workflow ID', required: true },\n { name: 'id', description: 'Note ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const workflowId = requireNumber(args, 'workflow-id');\n const noteId = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.deleteWorkflowNote(workspace, workflowId, noteId);\n process.stdout.write(`Deleted workflow note ${noteId}\\n`);\n },\n },\n // Contributors — nested resource requiring workflowId\n {\n path: ['workflows', 'contributors', 'list'],\n description: 'List workflow contributors',\n requiresWorkspace: true,\n args: [{ name: 'workflow-id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const workflowId = requireNumber(args, 'workflow-id');\n const result = await requireAuth(ctx).apiClient.getWorkflowContributors(\n workspace,\n workflowId\n );\n outputData(result, ctx, CONTRIBUTOR_COLUMNS);\n },\n },\n {\n path: ['workflows', 'contributors', 'create'],\n description: 'Add a workflow contributor',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'workflow-id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const workflowId = requireNumber(args, 'workflow-id');\n const result = await requireAuth(ctx).apiClient.createWorkflowContributor(\n workspace,\n workflowId,\n data as any\n );\n outputSingle(result, ctx, CONTRIBUTOR_COLUMNS);\n },\n },\n {\n path: ['workflows', 'contributors', 'update'],\n description: 'Update a workflow contributor',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'workflow-id', description: 'Workflow ID', required: true },\n { name: 'id', description: 'Contributor ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const workflowId = requireNumber(args, 'workflow-id');\n const contributorId = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.updateWorkflowContributor(\n workspace,\n workflowId,\n contributorId,\n data as any\n );\n outputSingle(result, ctx, CONTRIBUTOR_COLUMNS);\n },\n },\n {\n path: ['workflows', 'contributors', 'delete'],\n description: 'Remove a workflow contributor',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'workflow-id', description: 'Workflow ID', required: true },\n { name: 'id', description: 'Contributor ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const workflowId = requireNumber(args, 'workflow-id');\n const contributorId = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.deleteWorkflowContributor(\n workspace,\n workflowId,\n contributorId\n );\n process.stdout.write(`Deleted workflow contributor ${contributorId}\\n`);\n },\n },\n ],\n};\n","import { type DomainDef, requireString, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst WORKFLOW_UUID_ARG = {\n name: 'workflow-uuid',\n description: 'Workflow UUID',\n required: true,\n} as const;\n\nconst VERSION_ARG = {\n name: 'version',\n description: 'Version number',\n required: true,\n} as const;\n\nconst COLUMNS: TableColumn<unknown>[] = [\n { header: 'VERSION', getValue: (item: any) => String(item.versionNumber ?? '') },\n COL.uuid(),\n COL.name(),\n {\n header: 'ACTIVE',\n getValue: (item: any) => (item.isActive ? 'yes' : 'no'),\n },\n {\n header: 'SOURCE',\n getValue: (item: any) => item.sourceType ?? '',\n },\n {\n header: 'PUBLISHED',\n getValue: (item: any) => item.publishedAt ?? '',\n },\n {\n header: 'SUMMARY',\n getValue: (item: any) => (item.changeSummary ?? '').slice(0, 50),\n maxWidth: 50,\n },\n];\n\nexport const workflowVersionsDomain: DomainDef = {\n name: 'workflow-versions',\n description: 'Manage workflow versions (publish, activate, inspect snapshots)',\n commands: [\n // List versions\n {\n path: ['workflow-versions', 'list'],\n description: 'List all published versions of a workflow',\n requiresWorkspace: true,\n args: [WORKFLOW_UUID_ARG],\n handler: async ({ ctx, workspace, args }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const result = await requireAuth(ctx).apiClient.getWorkflowVersions(\n workspace,\n workflowUuid\n );\n process.stderr.write(`Next version number: ${result.nextVersionNumber}\\n`);\n outputData(result.versions, ctx, COLUMNS);\n },\n },\n // Get specific version\n {\n path: ['workflow-versions', 'get'],\n description: 'Get a specific version by number (includes full snapshot)',\n requiresWorkspace: true,\n args: [WORKFLOW_UUID_ARG, VERSION_ARG],\n handler: async ({ ctx, workspace, args }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const versionNumber = requireNumber(args, 'version');\n const result = await requireAuth(ctx).apiClient.getWorkflowVersion(\n workspace,\n workflowUuid,\n versionNumber\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Get active version\n {\n path: ['workflow-versions', 'active'],\n description: 'Get the currently active version of a workflow',\n requiresWorkspace: true,\n args: [WORKFLOW_UUID_ARG],\n handler: async ({ ctx, workspace, args }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const result = await requireAuth(ctx).apiClient.getWorkflowVersionActive(\n workspace,\n workflowUuid\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Publish\n {\n path: ['workflow-versions', 'publish'],\n description: 'Publish the live workflow as a new immutable version',\n mutates: true,\n requiresWorkspace: true,\n args: [\n WORKFLOW_UUID_ARG,\n {\n name: 'name',\n description: 'Human-readable version name',\n required: false,\n },\n {\n name: 'summary',\n description: 'Change summary',\n required: false,\n },\n {\n name: 'no-activate',\n description: 'Publish without activating',\n isFlag: true,\n required: false,\n },\n ],\n examples: [\n 'workflow-versions publish --workflow-uuid $UUID',\n 'workflow-versions publish --workflow-uuid $UUID --name \"v2 Release\" --summary \"Added triage step\"',\n 'workflow-versions publish --workflow-uuid $UUID --no-activate',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const body = (data as Record<string, unknown>) ?? {};\n // CLI flags override JSON data\n if (args.name) body.name = args.name;\n if (args.summary) body.changeSummary = args.summary;\n if (args['no-activate']) body.activate = false;\n const result = await requireAuth(ctx).apiClient.publishWorkflowVersion(\n workspace,\n workflowUuid,\n body\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Activate\n {\n path: ['workflow-versions', 'activate'],\n description: 'Activate a version so it receives new assignments',\n mutates: true,\n requiresWorkspace: true,\n args: [WORKFLOW_UUID_ARG, VERSION_ARG],\n handler: async ({ ctx, workspace, args }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const versionNumber = requireNumber(args, 'version');\n const result = await requireAuth(ctx).apiClient.activateWorkflowVersion(\n workspace,\n workflowUuid,\n versionNumber\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Deactivate\n {\n path: ['workflow-versions', 'deactivate'],\n description: 'Deactivate a version so it no longer receives new assignments',\n mutates: true,\n requiresWorkspace: true,\n args: [WORKFLOW_UUID_ARG, VERSION_ARG],\n handler: async ({ ctx, workspace, args }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const versionNumber = requireNumber(args, 'version');\n const result = await requireAuth(ctx).apiClient.deactivateWorkflowVersion(\n workspace,\n workflowUuid,\n versionNumber\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Diff (compare two versions, 0 = draft)\n {\n path: ['workflow-versions', 'diff'],\n description: 'Compare two versions (use 0 for draft)',\n requiresWorkspace: true,\n args: [\n WORKFLOW_UUID_ARG,\n { name: 'from', description: 'Base version number (0 = draft)', required: true },\n { name: 'to', description: 'Target version number (0 = draft)', required: true },\n ],\n examples: [\n 'workflow-versions diff --workflow-uuid $UUID --from 1 --to 2',\n 'workflow-versions diff --workflow-uuid $UUID --from 1 --to 0 # compare v1 to draft',\n ],\n handler: async ({ ctx, workspace, args }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const from = requireNumber(args, 'from');\n const to = requireNumber(args, 'to');\n const diff = await requireAuth(ctx).apiClient.diffWorkflowVersions(\n workspace,\n workflowUuid,\n from,\n to\n );\n\n if (ctx.outputFormat === 'json') {\n process.stdout.write(JSON.stringify(diff, null, 2) + '\\n');\n return;\n }\n\n // Human-readable output\n process.stdout.write(\n `\\nComparing ${diff.fromVersion.label} → ${diff.toVersion.label}\\n`\n );\n process.stdout.write(\n `Changes: +${diff.summary.added} −${diff.summary.removed} ~${diff.summary.modified}\\n\\n`\n );\n\n if (diff.changes.length === 0) {\n process.stdout.write('No differences.\\n');\n return;\n }\n\n let currentCategory = '';\n for (const change of diff.changes) {\n if (change.category !== currentCategory) {\n currentCategory = change.category;\n process.stdout.write(`[${currentCategory}]\\n`);\n }\n const prefix =\n change.changeType === 'added'\n ? ' + '\n : change.changeType === 'removed'\n ? ' − '\n : ' ~ ';\n const fieldSummary =\n change.fields && change.fields.length > 0\n ? ` (${change.fields.map((f: any) => f.field).join(', ')})`\n : '';\n process.stdout.write(`${prefix}${change.label}${fieldSummary}\\n`);\n\n // Show text-level diffs for fields with old/new values\n if (change.fields) {\n for (const field of change.fields) {\n if (field.oldValue != null || field.newValue != null) {\n process.stdout.write(` ${field.field}:\\n`);\n if (field.oldValue != null) {\n process.stdout.write(` - ${field.oldValue}\\n`);\n }\n if (field.newValue != null) {\n process.stdout.write(` + ${field.newValue}\\n`);\n }\n }\n }\n }\n }\n process.stdout.write('\\n');\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { CLIError } from '../lib/errors';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { listResult } from '../lib/pagination';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n COL.name(),\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.status(),\n COL.created(),\n];\n\nconst PRODUCT_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.uuid(), COL.name(), COL.status()];\n\nconst INVITATION_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'EMAIL', getValue: (item: any) => item.email ?? '' },\n COL.status(),\n COL.created(),\n];\n\nconst NOTIFICATION_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'TYPE', getValue: (item: any) => item.type ?? '' },\n { header: 'READ', getValue: (item: any) => String(item.read ?? false) },\n COL.created(),\n];\n\nconst FEATURE_COLUMNS: TableColumn<unknown>[] = [\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.name(),\n { header: 'CATEGORY', getValue: (item: any) => item.category ?? '' },\n];\n\nconst SCOPE_COLUMNS: TableColumn<unknown>[] = [\n COL.name(),\n { header: 'CATEGORY', getValue: (item: any) => item.category ?? '' },\n COL.description(),\n];\n\nconst THEME_COLUMNS: TableColumn<unknown>[] = [\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.name(),\n COL.description(),\n];\n\nconst DM_COLUMNS: TableColumn<unknown>[] = [\n { header: 'ID', getValue: (item: any) => String(item.id ?? '') },\n {\n header: 'PARTICIPANTS',\n getValue: (item: any) => (item.participants ?? []).map((p: any) => p.name).join(', '),\n maxWidth: 40,\n },\n {\n header: 'SUMMARY',\n getValue: (item: any) => String(item.summary ?? '').slice(0, 60),\n maxWidth: 60,\n },\n { header: 'UPDATED', getValue: (item: any) => item.updatedAt ?? '' },\n];\n\nconst MESSAGE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'ROLE', getValue: (item: any) => item.role ?? '' },\n {\n header: 'CONTENT',\n getValue: (item: any) => String(item.content ?? '').slice(0, 80),\n maxWidth: 80,\n },\n COL.created(),\n];\n\nexport const workspacesDomain: DomainDef = {\n name: 'workspaces',\n description: 'Manage workspaces',\n commands: [\n // List workspaces (no workspace required)\n ...crudCommands({\n prefix: ['workspaces'],\n entityName: 'workspace',\n listMethod: 'getWorkspaces',\n // getMethod omitted — custom get below accepts -w as the identifier\n updateMethod: 'updateWorkspace',\n deleteMethod: 'deleteWorkspace',\n columns: COLUMNS,\n requiresWorkspace: false,\n }),\n // Custom get that accepts either --id or -w as the workspace identifier\n {\n path: ['workspaces', 'get'],\n description: 'Get a workspace by UUID (via --id or -w)',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Workspace UUID (or use -w)' }],\n handler: async ({ ctx, workspace, args }) => {\n const id = (args.id ?? args.uuid ?? workspace) as string | undefined;\n if (!id) throw new CLIError('Provide workspace UUID via --id or -w');\n const result = await requireAuth(ctx).apiClient.getWorkspace(id);\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Create a workspace via the public endpoint\n {\n path: ['workspaces', 'create'],\n description: 'Create a workspace',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const payload = data as Record<string, unknown>;\n if (!payload.organizationId) {\n throw new CLIError(\n 'organizationId is required in --data (e.g. --data \\'{\"organizationId\": 1, \"name\": \"My Workspace\"}\\')'\n );\n }\n const result = await requireAuth(ctx).apiClient.createWorkspace(payload as any);\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Defaults\n {\n path: ['workspaces', 'defaults'],\n description: 'Get workspace defaults',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getWorkspaceDefaults(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['workspaces', 'update-defaults'],\n description: 'Update workspace defaults',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.updateWorkspaceDefaults(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n // Counts\n {\n path: ['workspaces', 'counts'],\n description: 'Get workspace entity counts',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getWorkspaceCounts(workspace);\n outputSingle(result, ctx);\n },\n },\n // Export/Import\n {\n path: ['workspaces', 'export'],\n description: 'Export workspace configuration',\n requiresWorkspace: true,\n args: [\n {\n name: 'scope',\n description: 'Export scope: \"workflows\" for workflow-only export',\n },\n {\n name: 'workflow-id',\n description: 'Export a single workflow by ID',\n },\n {\n name: 'exclude',\n description: 'Comma-separated categories to exclude (e.g. \"channels\")',\n },\n ],\n examples: [\n 'yarn gr workspaces export -w $UUID --env prod',\n 'yarn gr workspaces export -w $UUID --env prod --scope workflows',\n 'yarn gr workspaces export -w $UUID --env prod --workflow-id 42',\n 'yarn gr workspaces export -w $UUID --env prod --exclude channels',\n ],\n handler: async ({ ctx, workspace, args }) => {\n const scope = args['scope'] as string | undefined;\n const workflowIdStr = args['workflow-id'] as string | undefined;\n const exclude = args['exclude'] as string | undefined;\n const workflowId = workflowIdStr ? Number(workflowIdStr) : undefined;\n if (workflowId !== undefined && isNaN(workflowId)) {\n throw new CLIError('--workflow-id must be a number');\n }\n if (scope && workflowId !== undefined) {\n throw new CLIError('Cannot specify both --scope and --workflow-id');\n }\n if (scope && scope !== 'workflows') {\n throw new CLIError('--scope must be \"workflows\"');\n }\n const result = await requireAuth(ctx).apiClient.exportWorkspace(\n workspace,\n workflowId,\n scope as 'workflows' | undefined,\n exclude\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['workspaces', 'import'],\n description: 'Import workspace configuration',\n mutates: true,\n requiresWorkspace: true,\n args: [\n {\n name: 'create-all',\n description:\n 'Auto-generate createNew entries for all entities in the export data. Use when importing into a fresh workspace.',\n isFlag: true,\n },\n ],\n examples: [\n 'yarn gr workspaces import -w $UUID --env dev --file export.json --create-all',\n 'yarn gr workspaces import -w $UUID --env dev --data \\'{\"exportData\": ..., \"createNew\": ..., \"importMappings\": {}}\\'',\n ],\n handler: async ({ ctx, workspace, data, args }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const payload = data as Record<string, unknown>;\n const createAll = args['create-all'] === true;\n\n // Detect if input is a full import payload or raw export data\n let exportData: Record<string, unknown>;\n let importMappings: Record<string, Record<string, string>>;\n let createNew: Record<string, string[]>;\n\n if (payload.exportData && typeof payload.exportData === 'object') {\n // Full import payload: {exportData, importMappings?, createNew?}\n exportData = payload.exportData as Record<string, unknown>;\n importMappings =\n (payload.importMappings as Record<string, Record<string, string>>) ?? {};\n createNew = (payload.createNew as Record<string, string[]>) ?? {};\n } else if (payload.version && payload.workflows) {\n // Raw export data (has version + entity arrays at top level)\n exportData = payload;\n importMappings = {};\n createNew = {};\n } else {\n throw new CLIError(\n 'Unrecognized data format. Provide either raw export data (from \"workspaces export\") or a full import payload with {exportData, importMappings, createNew}.'\n );\n }\n\n if (createAll) {\n // Auto-generate createNew from all UUIDs in the export data.\n // Entity keys that contain arrays of objects with uuid fields.\n const entityKeys = [\n 'workflows',\n 'tasks',\n 'dataTypes',\n 'agents',\n 'memberLabels',\n 'files',\n 'eventRules',\n 'memberRoles',\n 'phoneNumbers',\n 'sites',\n 'inboxes',\n 'routines',\n 'memberFilters',\n 'memberFilterRules',\n 'milestones',\n 'milestoneGoals',\n 'customToolkits',\n 'customTools',\n 'pages',\n 'menuItems',\n 'mcpServers',\n 'fileFolders',\n 'fileLabels',\n 'workflowNotes',\n 'abilities',\n 'qualifications',\n 'chatLabels',\n 'chatFilters',\n 'chatFilterRules',\n 'calendars',\n 'calendarEventTypes',\n 'calendarSchedules',\n 'journeys',\n ];\n for (const key of entityKeys) {\n const entities = exportData[key];\n if (Array.isArray(entities)) {\n createNew[key] = entities\n .map((e: Record<string, unknown>) => e.uuid as string)\n .filter(Boolean);\n }\n }\n }\n\n const result = await requireAuth(ctx).apiClient.importWorkspace(\n workspace,\n exportData as any,\n importMappings as any,\n createNew as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['workspaces', 'preview-import'],\n description: 'Preview workspace import',\n requiresWorkspace: true,\n args: [\n {\n name: 'create-all',\n description: 'Auto-generate createNew entries for all entities in the export data',\n isFlag: true,\n },\n ],\n handler: async ({ ctx, workspace, data, args }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const payload = data as Record<string, unknown>;\n const createAll = args['create-all'] === true;\n\n let exportData: Record<string, unknown>;\n let importMappings: Record<string, Record<string, string>>;\n let createNew: Record<string, string[]>;\n\n if (payload.exportData && typeof payload.exportData === 'object') {\n exportData = payload.exportData as Record<string, unknown>;\n importMappings =\n (payload.importMappings as Record<string, Record<string, string>>) ?? {};\n createNew = (payload.createNew as Record<string, string[]>) ?? {};\n } else if (payload.version && payload.workflows) {\n exportData = payload;\n importMappings = {};\n createNew = {};\n } else {\n throw new CLIError(\n 'Unrecognized data format. Provide either raw export data (from \"workspaces export\") or a full import payload with {exportData, importMappings, createNew}.'\n );\n }\n\n if (createAll) {\n const entityKeys = [\n 'workflows',\n 'tasks',\n 'dataTypes',\n 'agents',\n 'memberLabels',\n 'files',\n 'eventRules',\n 'memberRoles',\n 'phoneNumbers',\n 'sites',\n 'inboxes',\n 'routines',\n 'memberFilters',\n 'memberFilterRules',\n 'milestones',\n 'milestoneGoals',\n 'customToolkits',\n 'customTools',\n 'pages',\n 'menuItems',\n 'mcpServers',\n 'fileFolders',\n 'fileLabels',\n 'workflowNotes',\n 'abilities',\n 'qualifications',\n 'chatLabels',\n 'chatFilters',\n 'chatFilterRules',\n 'calendars',\n 'calendarEventTypes',\n 'calendarSchedules',\n 'journeys',\n ];\n for (const key of entityKeys) {\n const entities = exportData[key];\n if (Array.isArray(entities)) {\n createNew[key] = entities\n .map((e: Record<string, unknown>) => e.uuid as string)\n .filter(Boolean);\n }\n }\n }\n\n const result = await requireAuth(ctx).apiClient.previewImportWorkspace(\n workspace,\n exportData as any,\n importMappings as any,\n createNew as any\n );\n outputSingle(result, ctx);\n },\n },\n // Features\n {\n path: ['workspaces', 'features'],\n description: 'List available workspace features',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getAvailableWorkspaceFeatures();\n outputData(listResult(result, false), ctx, FEATURE_COLUMNS);\n },\n },\n // Scopes\n {\n path: ['workspaces', 'scopes'],\n description: 'List workspace scopes',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getWorkspaceScopes();\n outputData(listResult(result, false), ctx, SCOPE_COLUMNS);\n },\n },\n // Products — getProduct is a global endpoint (no workspace param), so use a custom get handler\n ...crudCommands({\n prefix: ['workspaces', 'products'],\n entityName: 'product',\n listMethod: 'getProducts',\n // getMethod omitted — custom get below handles the global endpoint\n createMethod: 'createProduct',\n updateMethod: 'updateProduct',\n deleteMethod: 'deleteProduct',\n columns: PRODUCT_COLUMNS,\n }),\n {\n path: ['workspaces', 'products', 'get'],\n description: 'Get a product by ID',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Product ID', required: true }],\n handler: async ({ ctx, args }) => {\n const id = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.getProduct(id);\n outputSingle(result, ctx, PRODUCT_COLUMNS);\n },\n },\n // Invitations — workspace-scoped admin methods\n {\n path: ['workspaces', 'invitations', 'list'],\n description: 'List workspace invitations',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result =\n await requireAuth(ctx).apiClient.listWorkspaceInvitationsAdmin(workspace);\n outputData(listResult(result, false), ctx, INVITATION_COLUMNS);\n },\n },\n {\n path: ['workspaces', 'invitations', 'delete'],\n description: 'Delete a workspace invitation',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Invitation ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const invitationId = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.deleteWorkspaceInvitationAdmin(\n workspace,\n invitationId\n );\n process.stdout.write(`Deleted invitation ${invitationId}\\n`);\n },\n },\n {\n path: ['workspaces', 'invitations', 'invite'],\n description: 'Invite a user to the workspace',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const payload = data as Record<string, unknown> | undefined;\n if (!payload) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const emailOrAccountId = (payload.email ?? payload.accountId) as string | number;\n if (!emailOrAccountId) {\n throw new CLIError('--data must include \"email\" or \"accountId\"');\n }\n const result = await requireAuth(ctx).apiClient.inviteToWorkspace(\n workspace,\n emailOrAccountId,\n payload.message as string | undefined,\n payload.memberRoleId !== undefined ? Number(payload.memberRoleId) : undefined,\n payload.name as string | undefined\n );\n outputSingle(result, ctx, INVITATION_COLUMNS);\n },\n },\n {\n path: ['workspaces', 'invitations', 'approve'],\n description: 'Approve a workspace invitation',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Invitation ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const invitationId = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.approveWorkspaceInvitation(\n workspace,\n invitationId\n );\n outputSingle(result, ctx, INVITATION_COLUMNS);\n },\n },\n {\n path: ['workspaces', 'invitations', 'deny'],\n description: 'Deny a workspace invitation',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Invitation ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const invitationId = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.denyWorkspaceInvitation(\n workspace,\n invitationId\n );\n outputSingle(result, ctx, INVITATION_COLUMNS);\n },\n },\n // Notifications\n ...crudCommands({\n prefix: ['workspaces', 'notifications'],\n entityName: 'notification',\n listMethod: 'getNotifications',\n getMethod: 'getNotification',\n columns: NOTIFICATION_COLUMNS,\n paginationSupport: 'full',\n }),\n {\n path: ['workspaces', 'notifications', 'mark-read'],\n description: 'Mark a notification as read',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Notification ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.markNotificationAsRead(\n workspace,\n requireNumber(args, 'id')\n );\n process.stdout.write(`Marked notification ${args.id} as read\\n`);\n },\n },\n {\n path: ['workspaces', 'notifications', 'dismiss-all'],\n description: 'Dismiss all notifications',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n await requireAuth(ctx).apiClient.dismissAllNotifications(workspace);\n process.stdout.write('Dismissed all notifications\\n');\n },\n },\n // Themes\n {\n path: ['workspaces', 'themes', 'list'],\n description: 'List workspace themes',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getWorkspaceThemes(workspace);\n outputData(listResult(result, false), ctx, THEME_COLUMNS);\n },\n },\n {\n path: ['workspaces', 'themes', 'update'],\n description: 'Update workspace themes',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.updateWorkspaceThemes(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n // Direct Messages (via chats API with chatType=dm)\n {\n path: ['workspaces', 'dms', 'list'],\n description: 'List direct message chats',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getChats(workspace, {\n chatType: 'member',\n mine: true,\n sortBy: 'updatedAt',\n sortOrder: 'desc',\n });\n outputData(listResult(result, false), ctx, DM_COLUMNS);\n },\n },\n {\n path: ['workspaces', 'dms', 'get'],\n description: 'Get messages for a DM chat',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getChatMessages(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(listResult(result, false), ctx, MESSAGE_COLUMNS);\n },\n },\n {\n path: ['workspaces', 'dms', 'send'],\n description: 'Send a message in a DM chat',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const chatId = requireNumber(args, 'id');\n const content = (data as any)?.content ?? '';\n const result = await requireAuth(ctx).apiClient.sendChatMessage(\n workspace,\n chatId,\n content\n );\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.status(),\n { header: 'MEMBER', getValue: (item: any) => String(item.member_id ?? '') },\n { header: 'TASK', getValue: (item: any) => String(item.current_assignment_task_id ?? '') },\n { header: 'WF_VERSION', getValue: (item: any) => String(item.workflowVersionNumber ?? '') },\n COL.created(),\n];\n\nconst MESSAGE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'ROLE', getValue: (item: any) => item.role ?? '' },\n { header: 'CONTENT', getValue: (item: any) => (item.content ?? '').slice(0, 80) },\n COL.created(),\n];\n\nconst TASK_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.name(), COL.status()];\n\nconst TOOL_COLUMNS: TableColumn<unknown>[] = [\n COL.name(),\n { header: 'DESCRIPTION', getValue: (item: any) => (item.description ?? '').slice(0, 60) },\n];\n\nexport const assignmentsDomain: DomainDef = {\n name: 'assignments',\n description: 'Manage assignments',\n commands: [\n ...crudCommands({\n prefix: ['assignments'],\n entityName: 'assignment',\n listMethod: 'getAssignments',\n getMethod: 'getAssignment',\n createMethod: 'createAssignment',\n updateMethod: 'updateAssignment',\n deleteMethod: 'deleteAssignment',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n {\n path: ['assignments', 'cancel'],\n description: 'Cancel an assignment',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Assignment ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const body = (data as any) ?? {};\n const result = await requireAuth(ctx).apiClient.cancelAssignment(\n workspace,\n requireNumber(args, 'id'),\n body\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['assignments', 'messages', 'list'],\n description: 'List messages for an assignment',\n requiresWorkspace: true,\n args: [{ name: 'assignment-id', description: 'Assignment ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getAssignmentMessages(\n workspace,\n requireNumber(args, 'assignment-id')\n );\n outputData(result, ctx, MESSAGE_COLUMNS);\n },\n },\n {\n path: ['assignments', 'tasks', 'get'],\n description: 'Get an assignment task',\n requiresWorkspace: true,\n args: [\n { name: 'assignment-id', description: 'Assignment ID', required: true },\n { name: 'id', description: 'Assignment task ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getAssignmentTask(\n workspace,\n requireNumber(args, 'assignment-id'),\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, TASK_COLUMNS);\n },\n },\n {\n path: ['assignments', 'tasks', 'detail'],\n description: 'Get current task detail for an assignment',\n requiresWorkspace: true,\n args: [{ name: 'assignment-id', description: 'Assignment ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getAssignmentTaskDetail(\n workspace,\n requireNumber(args, 'assignment-id')\n );\n outputSingle(result, ctx, TASK_COLUMNS);\n },\n },\n {\n path: ['assignments', 'tasks', 'select'],\n description: 'Select current assignment task',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'assignment-id', description: 'Assignment ID', required: true },\n { name: 'id', description: 'Assignment task ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.selectCurrentAssignmentTask(\n workspace,\n requireNumber(args, 'assignment-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write(`Selected assignment task ${args.id}\\n`);\n },\n },\n {\n path: ['assignments', 'tools', 'list'],\n description: 'List tools for an assignment',\n requiresWorkspace: true,\n args: [{ name: 'assignment-id', description: 'Assignment ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getAssignmentTools(\n workspace,\n requireNumber(args, 'assignment-id')\n );\n const tools = result.tools ?? result;\n outputData(Array.isArray(tools) ? tools : [tools], ctx, TOOL_COLUMNS);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'TIMEZONE', getValue: (item: any) => item.timezone ?? '' },\n];\n\nconst SCHEDULE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'CALENDAR', getValue: (item: any) => String(item.calendar_id ?? '') },\n];\n\nconst EVENT_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'TITLE', getValue: (item: any) => item.title ?? item.name ?? '' },\n { header: 'START', getValue: (item: any) => item.start_time ?? item.start ?? '' },\n { header: 'END', getValue: (item: any) => item.end_time ?? item.end ?? '' },\n COL.status(),\n];\n\nconst EVENT_TYPE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'DURATION', getValue: (item: any) => String(item.duration ?? '') },\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n];\n\nexport const calendarsDomain: DomainDef = {\n name: 'calendars',\n description: 'Manage calendars, schedules, events, and event types',\n commands: [\n ...crudCommands({\n prefix: ['calendars'],\n entityName: 'calendar',\n listMethod: 'getCalendars',\n getMethod: 'getCalendar',\n createMethod: 'createCalendar',\n updateMethod: 'updateCalendar',\n deleteMethod: 'deleteCalendar',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n // Schedules sub-resource\n {\n path: ['calendars', 'schedules', 'list'],\n description: 'List schedules for a calendar',\n requiresWorkspace: true,\n args: [{ name: 'calendar-id', description: 'Calendar ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getCalendarSchedules(\n workspace,\n requireNumber(args, 'calendar-id')\n );\n outputData(result, ctx, SCHEDULE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'schedules', 'create'],\n description: 'Create a schedule',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'calendar-id', description: 'Calendar ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.createCalendarSchedule(\n workspace,\n requireNumber(args, 'calendar-id'),\n data as any\n );\n outputSingle(result, ctx, SCHEDULE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'schedules', 'update'],\n description: 'Update a schedule',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'calendar-id', description: 'Calendar ID', required: true },\n { name: 'id', description: 'Schedule ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateCalendarSchedule(\n workspace,\n requireNumber(args, 'calendar-id'),\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, SCHEDULE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'schedules', 'delete'],\n description: 'Delete a schedule',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'calendar-id', description: 'Calendar ID', required: true },\n { name: 'id', description: 'Schedule ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deleteCalendarSchedule(\n workspace,\n requireNumber(args, 'calendar-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write(`Deleted schedule ${args.id}\\n`);\n },\n },\n // Events sub-resource\n {\n path: ['calendars', 'events', 'list'],\n description: 'List calendar events (optionally filter by calendar)',\n requiresWorkspace: true,\n args: [{ name: 'calendar-id', description: 'Calendar ID (optional filter)' }],\n handler: async ({ ctx, workspace, args }) => {\n const calendarId = args['calendar-id'] ? requireNumber(args, 'calendar-id') : undefined;\n const result = await requireAuth(ctx).apiClient.getCalendarEvents(workspace, {\n ...(calendarId ? { calendarId } : {}),\n });\n outputData(result, ctx, EVENT_COLUMNS);\n },\n },\n {\n path: ['calendars', 'events', 'get'],\n description: 'Get a calendar event',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getCalendarEvent(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, EVENT_COLUMNS);\n },\n },\n {\n path: ['calendars', 'events', 'create'],\n description: 'Create a calendar event',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.createCalendarEvent(\n workspace,\n data as any\n );\n outputSingle(result, ctx, EVENT_COLUMNS);\n },\n },\n {\n path: ['calendars', 'events', 'update'],\n description: 'Update a calendar event',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateCalendarEvent(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, EVENT_COLUMNS);\n },\n },\n {\n path: ['calendars', 'events', 'cancel'],\n description: 'Cancel a calendar event',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.cancelCalendarEvent(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, EVENT_COLUMNS);\n },\n },\n {\n path: ['calendars', 'events', 'delete'],\n description: 'Delete a calendar event',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deleteCalendarEvent(\n workspace,\n requireNumber(args, 'id')\n );\n process.stdout.write(`Deleted calendar event ${args.id}\\n`);\n },\n },\n // Event types sub-resource\n {\n path: ['calendars', 'event-types', 'list'],\n description: 'List calendar event types',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getCalendarEventTypes(workspace);\n outputData(result, ctx, EVENT_TYPE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'event-types', 'get'],\n description: 'Get a calendar event type',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event type ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getCalendarEventType(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, EVENT_TYPE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'event-types', 'create'],\n description: 'Create a calendar event type',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.createCalendarEventType(\n workspace,\n data as any\n );\n outputSingle(result, ctx, EVENT_TYPE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'event-types', 'update'],\n description: 'Update a calendar event type',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event type ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateCalendarEventType(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, EVENT_TYPE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'event-types', 'delete'],\n description: 'Delete a calendar event type',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event type ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deleteCalendarEventType(\n workspace,\n requireNumber(args, 'id')\n );\n process.stdout.write(`Deleted event type ${args.id}\\n`);\n },\n },\n ],\n};\n","import { type DomainDef, requireString, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { fetchAllPages, parsePaginationArgs, listResult } from '../lib/pagination';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.status(),\n];\n\nconst RECORD_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'DATA TYPE', getValue: (item: any) => String(item.data_type_id ?? '') },\n { header: 'MEMBER', getValue: (item: any) => String(item.member_id ?? '') },\n COL.updated(),\n];\n\nexport const dataTypesDomain: DomainDef = {\n name: 'data-types',\n description: 'Manage data types and records',\n commands: [\n ...crudCommands({\n prefix: ['data-types'],\n entityName: 'data type',\n listMethod: 'getDataTypes',\n getMethod: 'getDataType',\n createMethod: 'createDataType',\n updateMethod: 'updateDataType',\n deleteMethod: 'deleteDataType',\n archiveMethod: 'archiveDataType',\n unarchiveMethod: 'unarchiveDataType',\n columns: COLUMNS,\n }),\n {\n path: ['data-types', 'clone'],\n description: 'Clone a data type',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Data type ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.cloneDataType(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['data-types', 'get-by-slug'],\n description: 'Get a data type by slug',\n requiresWorkspace: true,\n args: [{ name: 'slug', description: 'Data type slug', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getDataTypeBySlug(\n workspace,\n requireString(args, 'slug')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Data Records sub-resource\n {\n path: ['data-types', 'records', 'list'],\n description: 'List records for a data type',\n requiresWorkspace: true,\n args: [\n { name: 'data-type-id', description: 'Data type ID', required: true },\n { name: 'page', description: 'Page number (default: 1)' },\n { name: 'page-size', description: 'Page size (default: 10)' },\n { name: 'all', description: 'Fetch all pages', isFlag: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const dataTypeId = requireNumber(args, 'data-type-id');\n const pag = parsePaginationArgs(args);\n\n if (pag.all) {\n const allItems = await fetchAllPages(({ page, pageSize }) =>\n requireAuth(ctx).apiClient.getDataRecords(workspace, dataTypeId, {\n page,\n pageSize,\n })\n );\n outputData(allItems, ctx, RECORD_COLUMNS);\n } else {\n const options: { page?: number; pageSize?: number } = {};\n if (pag.page) options.page = pag.page;\n if (pag.pageSize) options.pageSize = pag.pageSize;\n const result = await requireAuth(ctx).apiClient.getDataRecords(\n workspace,\n dataTypeId,\n options\n );\n // Explicit contract: supportsAll=true because this command HAS --all\n outputData(listResult(result, true), ctx, RECORD_COLUMNS);\n }\n },\n },\n {\n path: ['data-types', 'records', 'get'],\n description: 'Get a data record',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Record ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getDataRecord(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, RECORD_COLUMNS);\n },\n },\n {\n path: ['data-types', 'records', 'create'],\n description: 'Create a data record',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'data-type-id', description: 'Data type ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.createDataRecord(\n workspace,\n requireNumber(args, 'data-type-id'),\n data as any\n );\n outputSingle(result, ctx, RECORD_COLUMNS);\n },\n },\n {\n path: ['data-types', 'records', 'update'],\n description: 'Update a data record',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'data-type-id', description: 'Data type ID', required: true },\n { name: 'id', description: 'Record ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateDataRecord(\n workspace,\n requireNumber(args, 'data-type-id'),\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, RECORD_COLUMNS);\n },\n },\n {\n path: ['data-types', 'records', 'delete'],\n description: 'Delete a data record',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'data-type-id', description: 'Data type ID', required: true },\n { name: 'id', description: 'Record ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deleteDataRecord(\n workspace,\n requireNumber(args, 'data-type-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write(`Deleted data record ${args.id}\\n`);\n },\n },\n ],\n};\n","import { EventRuleActionType, EventRuleEventType, EventRuleObjectType } from '@gravity-rail/sdk';\nimport { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { fetchAllPages, listResult } from '../lib/pagination';\nimport { requireAuth } from '../lib/context';\n\ninterface SearchEventRulesArgs {\n objectType?: EventRuleObjectType;\n eventType?: EventRuleEventType;\n actionType?: EventRuleActionType;\n taskId?: number;\n dataTypeId?: number;\n routineId?: number;\n workflowId?: number;\n journeyStepId?: number;\n includeDisabled?: boolean;\n}\n\nconst RULE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'EVENT', getValue: (item: any) => item.eventType ?? '' },\n { header: 'ACTIVE', getValue: (item: any) => String(item.active ?? '') },\n];\n\nconst EVENT_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.status(),\n];\n\n// Generate event rules CRUD commands (get/create/update/delete only — list is customized below)\nconst eventRulesCrudNoList = crudCommands({\n prefix: ['events', 'rules'],\n entityName: 'event rule',\n getMethod: 'getEventRule',\n createMethod: 'createEventRule',\n updateMethod: 'updateEventRule',\n deleteMethod: 'deleteEventRule',\n columns: RULE_COLUMNS,\n createExamples: [\n 'gr events rules create -w $WID --data \\'{\"name\":\"Label on step\",\"objectType\":\"journey\",',\n ' \"eventType\":\"journey_step:execute\",\"actionType\":\"member:label\",',\n ' \"actionParams\":{\"addLabelIds\":[\"<label-uuid>\"]},\"journeyStepId\":<step-id>}\\'',\n '',\n 'Required: objectType, eventType, actionType',\n 'Optional: name, actionParams, conditions (CEL), journeyStepId, delay (sec), order',\n '',\n 'Common eventTypes: journey_step:execute, journey:enrolled, journey:completed,',\n ' task:created, chat:created, data_record:created, member:created',\n '',\n 'Common actionTypes: member:label, member:notify, webhook:send, email:send,',\n ' sms:send, chat:create, member:upsert',\n '',\n 'member:label actionParams: {\"addLabelIds\":[\"uuid\"],\"removeLabelIds\":[\"uuid\"]}',\n ],\n});\n\n// Custom list command for event rules — supports journey-step-id / event-type filters.\n// When filters are provided, routes to searchEventRules (unpaginated, filter-aware);\n// otherwise falls back to the paginated getEventRules endpoint with --page/--page-size/--all.\nconst eventRulesListCmd = {\n path: ['events', 'rules', 'list'],\n description: 'List event rules (use --journey-step-id or --event-type to filter)',\n requiresWorkspace: true,\n columns: RULE_COLUMNS,\n args: [\n { name: 'journey-step-id', description: 'Filter by journey step ID' },\n { name: 'event-type', description: 'Filter by event type (e.g. journey_step:execute)' },\n { name: 'object-type', description: 'Filter by object type (e.g. journey, task)' },\n { name: 'include-disabled', description: 'Include inactive rules', isFlag: true as const },\n { name: 'page', description: 'Page number (without filters)' },\n { name: 'page-size', description: 'Page size (without filters)' },\n {\n name: 'all',\n description: 'Fetch all pages (without filters)',\n isFlag: true as const,\n },\n ],\n handler: async ({ ctx, workspace, args }: any) => {\n const client = requireAuth(ctx).apiClient;\n const journeyStepId = args['journey-step-id']\n ? requireNumber(args, 'journey-step-id')\n : undefined;\n const eventType = args['event-type'] as EventRuleEventType | undefined;\n const objectType = args['object-type'] as EventRuleObjectType | undefined;\n const includeDisabled = args['include-disabled'] === true;\n\n // When any filter (including --include-disabled) is specified, delegate\n // to searchEventRules. The paginated getEventRules endpoint returns only\n // active rules and ignores includeDisabled, so we must route through\n // search to honor it.\n if (\n journeyStepId !== undefined ||\n eventType !== undefined ||\n objectType !== undefined ||\n includeDisabled\n ) {\n const result = await client.searchEventRules(workspace, {\n ...(journeyStepId !== undefined ? { journeyStepId } : {}),\n ...(eventType ? { eventType } : {}),\n ...(objectType ? { objectType } : {}),\n ...(includeDisabled ? { includeDisabled: true } : {}),\n });\n outputData(listResult(result, false), ctx, RULE_COLUMNS);\n return;\n }\n\n // No filters — paginated getEventRules\n if (args['all']) {\n const allItems = await fetchAllPages(async ({ page, pageSize }) =>\n client.getEventRules(workspace, { page, pageSize })\n );\n outputData(allItems, ctx, RULE_COLUMNS);\n return;\n }\n const page = args['page'] ? requireNumber(args, 'page') : undefined;\n const pageSize = args['page-size'] ? requireNumber(args, 'page-size') : undefined;\n const result = await client.getEventRules(workspace, {\n ...(page !== undefined ? { page } : {}),\n ...(pageSize !== undefined ? { pageSize } : {}),\n });\n outputData(listResult(result, true), ctx, RULE_COLUMNS);\n },\n};\n\n// Combine into the full set used by eventsDomain\nconst eventRulesCrud = [eventRulesListCmd, ...eventRulesCrudNoList];\n\n// Build aliases: \"events list\" → \"events rules list\", \"events get\" → \"events rules get\"\nconst eventRulesAliases = eventRulesCrud\n .filter((cmd) => {\n const verb = cmd.path[cmd.path.length - 1];\n return verb === 'list' || verb === 'get';\n })\n .map((cmd) => ({\n ...cmd,\n path: ['events', cmd.path[cmd.path.length - 1]!],\n description: `${cmd.description} (alias for events rules ${cmd.path[cmd.path.length - 1]})`,\n }));\n\nexport const eventsDomain: DomainDef = {\n name: 'events',\n description: 'Manage event rules and custom events',\n commands: [\n // Event rules\n ...eventRulesCrud,\n // Aliases: \"events list\" → \"events rules list\", etc.\n ...eventRulesAliases,\n {\n path: ['events', 'rules', 'executions'],\n description: 'List executions for an event rule',\n requiresWorkspace: true,\n args: [{ name: 'rule-id', description: 'Event rule ID' }],\n handler: async ({ ctx, workspace, args }) => {\n const ruleId = args['rule-id'] ? requireNumber(args, 'rule-id') : undefined;\n const result = await requireAuth(ctx).apiClient.getRuleExecutions(workspace, {\n ...(ruleId ? { ruleId } : {}),\n });\n outputData(result, ctx);\n },\n },\n {\n // The /event-rules/search endpoint returns an unpaginated list — the\n // server applies the filters and returns whatever matches. No --all\n // flag is needed; if the result becomes too large in practice,\n // tighten the filter rather than paginate.\n path: ['events', 'rules', 'search'],\n description: 'Search event rules by object/event/action type or related entity ID',\n requiresWorkspace: true,\n args: [\n {\n name: 'object-type',\n description:\n 'Filter by object type (task, routine, journey, workflow, calendar, ...)',\n },\n { name: 'event-type', description: 'Filter by event type' },\n { name: 'action-type', description: 'Filter by action type' },\n { name: 'task-id', description: 'Filter by task ID' },\n { name: 'data-type-id', description: 'Filter by data type ID' },\n { name: 'routine-id', description: 'Filter by routine ID' },\n { name: 'workflow-id', description: 'Filter by workflow ID' },\n { name: 'journey-step-id', description: 'Filter by journey step ID' },\n {\n name: 'include-disabled',\n description: 'Include inactive rules (default: active only)',\n },\n ],\n columns: RULE_COLUMNS,\n handler: async ({ ctx, workspace, args }) => {\n const opts: SearchEventRulesArgs = {};\n if (args['object-type']) opts.objectType = args['object-type'] as EventRuleObjectType;\n if (args['event-type']) opts.eventType = args['event-type'] as EventRuleEventType;\n if (args['action-type']) opts.actionType = args['action-type'] as EventRuleActionType;\n if (args['task-id']) opts.taskId = requireNumber(args, 'task-id');\n if (args['data-type-id']) opts.dataTypeId = requireNumber(args, 'data-type-id');\n if (args['routine-id']) opts.routineId = requireNumber(args, 'routine-id');\n if (args['workflow-id']) opts.workflowId = requireNumber(args, 'workflow-id');\n if (args['journey-step-id'])\n opts.journeyStepId = requireNumber(args, 'journey-step-id');\n if (args['include-disabled']) opts.includeDisabled = true;\n const result = await requireAuth(ctx).apiClient.searchEventRules(workspace, opts);\n outputData(result, ctx, RULE_COLUMNS);\n },\n },\n // Routines\n ...crudCommands({\n prefix: ['routines'],\n entityName: 'routine',\n listMethod: 'getRoutines',\n getMethod: 'getRoutine',\n createMethod: 'createRoutine',\n updateMethod: 'updateRoutine',\n deleteMethod: 'deleteRoutine',\n paginationSupport: 'full',\n columns: EVENT_COLUMNS,\n }),\n {\n path: ['routines', 'run'],\n description: 'Run a routine now',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Routine ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.runRoutine(\n workspace,\n requireNumber(args, 'id'),\n (data ?? {}) as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['routines', 'runs', 'list'],\n description: 'List runs for a routine',\n requiresWorkspace: true,\n args: [\n {\n name: 'id',\n description: 'Routine ID (aligns with routines get/run/update/delete)',\n },\n { name: 'status', description: 'Filter by run status' },\n { name: 'page', description: 'Page number (1-indexed)' },\n { name: 'page-size', description: 'Page size (max 100)' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const routineId = args.id ? requireNumber(args, 'id') : undefined;\n const page = args.page ? requireNumber(args, 'page') : undefined;\n const pageSize = args['page-size'] ? requireNumber(args, 'page-size') : undefined;\n const status = (args.status as string | undefined) ?? undefined;\n const result = await requireAuth(ctx).apiClient.getRoutineRuns(workspace, {\n ...(routineId !== undefined ? { routineId } : {}),\n ...(page !== undefined ? { page } : {}),\n ...(pageSize !== undefined ? { pageSize } : {}),\n ...(status ? { status } : {}),\n });\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'TYPE', getValue: (item: any) => item.content_type ?? item.type ?? '' },\n { header: 'SIZE', getValue: (item: any) => String(item.size ?? '') },\n { header: 'FOLDER', getValue: (item: any) => String(item.folder_id ?? '') },\n];\n\nconst FOLDER_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'PARENT', getValue: (item: any) => String(item.parentId ?? '') },\n { header: 'CHILDREN', getValue: (item: any) => String(item.childCount ?? '') },\n { header: 'FILES', getValue: (item: any) => String(item.fileCount ?? '') },\n { header: 'ACCESS', getValue: (item: any) => item.access ?? '' },\n];\n\nconst LABEL_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'COLOR', getValue: (item: any) => item.color ?? '' },\n];\n\nexport const filesDomain: DomainDef = {\n name: 'files',\n description: 'Manage files, folders, and labels',\n commands: [\n ...crudCommands({\n prefix: ['files'],\n entityName: 'file',\n listMethod: 'getFiles',\n getMethod: 'getFile',\n createMethod: 'createFile',\n updateMethod: 'updateFile',\n deleteMethod: 'deleteFile',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n // Folders sub-resource\n ...crudCommands({\n prefix: ['files', 'folders'],\n entityName: 'folder',\n listMethod: 'getFolders',\n getMethod: 'getFolder',\n createMethod: 'createFolder',\n updateMethod: 'updateFolder',\n deleteMethod: 'deleteFolder',\n columns: FOLDER_COLUMNS,\n listArgs: [\n {\n name: 'parent-id',\n description: 'Parent folder ID (required)',\n required: true,\n },\n ],\n }),\n {\n path: ['files', 'folders', 'reindex'],\n description: 'Reindex a folder',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Folder ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.reindexFolder(workspace, requireNumber(args, 'id'));\n process.stdout.write(`Reindexing folder ${args.id}\\n`);\n },\n },\n // Labels sub-resource\n ...crudCommands({\n prefix: ['files', 'labels'],\n entityName: 'file label',\n listMethod: 'getFileLabels',\n getMethod: 'getFileLabel',\n createMethod: 'createFileLabel',\n updateMethod: 'updateFileLabel',\n deleteMethod: 'deleteFileLabel',\n columns: LABEL_COLUMNS,\n }),\n ],\n};\n","import { EventRuleEventType } from '@gravity-rail/sdk';\nimport { requireAuth, type AuthenticatedContext } from '../lib/context';\nimport { CLIError } from '../lib/errors';\nimport type { TableColumn } from '../lib/output';\nimport { COL, outputData, outputSingle } from '../lib/output';\nimport { listResult } from '../lib/pagination';\nimport type { DomainDef } from '../lib/types';\nimport { requireNumber, requireString } from '../lib/types';\n\n// ── Column definitions ──────────────────────────────────────────────\n\nconst JOURNEY_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'UUID', getValue: (item: any) => (item.uuid ?? '').slice(0, 8) },\n COL.name(),\n COL.status(),\n COL.created(),\n];\n\nconst STEP_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'UUID', getValue: (item: any) => (item.uuid ?? '').slice(0, 8) },\n COL.name(),\n { header: 'TYPE', getValue: (item: any) => item.stepType ?? '' },\n { header: 'TRIGGER', getValue: (item: any) => item.triggerType ?? '' },\n { header: 'ORDER', getValue: (item: any) => String(item.order ?? '') },\n];\n\nconst MEMBER_JOURNEY_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'MEMBER', getValue: (item: any) => String(item.memberId ?? '') },\n COL.status(),\n { header: 'ENROLLED', getValue: (item: any) => item.enrolledAt ?? '' },\n];\n\nconst MEMBER_STEP_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'STEP', getValue: (item: any) => String(item.journeyStepId ?? '') },\n COL.status(),\n { header: 'ELIGIBLE', getValue: (item: any) => item.eligibleAt ?? '' },\n { header: 'COMPLETED', getValue: (item: any) => item.completedAt ?? '' },\n];\n\nconst GOAL_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'UUID', getValue: (item: any) => (item.uuid ?? '').slice(0, 8) },\n COL.name(),\n { header: 'VALUE', getValue: (item: any) => (item.value != null ? String(item.value) : '') },\n {\n header: 'ACHIEVED',\n getValue: (item: any) => (item.achievedCount != null ? String(item.achievedCount) : ''),\n },\n {\n header: 'ENROLLED',\n getValue: (item: any) => (item.totalEnrolled != null ? String(item.totalEnrolled) : ''),\n },\n];\n\nconst CONNECTION_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'PARENT', getValue: (item: any) => String(item.parentStepId ?? '') },\n { header: 'CHILD', getValue: (item: any) => String(item.childStepId ?? '') },\n { header: 'REQUIRED', getValue: (item: any) => (item.required ? 'yes' : '') },\n {\n header: 'TIMEOUT',\n getValue: (item: any) => (item.timeoutSeconds != null ? `${item.timeoutSeconds}s` : ''),\n },\n { header: 'CONDITION', getValue: (item: any) => item.celCondition ?? '' },\n {\n header: 'FILTER',\n getValue: (item: any) => (item.filterId != null ? String(item.filterId) : ''),\n },\n];\n\nconst NOTE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'AUTHOR', getValue: (item: any) => String(item.creatorId ?? '') },\n { header: 'CONTENT', getValue: (item: any) => (item.contents ?? '').slice(0, 60) },\n { header: 'CREATED', getValue: (item: any) => item.createdAt ?? '' },\n];\n\nconst ACTION_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'UUID', getValue: (item: any) => (item.uuid ?? '').slice(0, 8) },\n COL.name(),\n { header: 'EVENT', getValue: (item: any) => item.eventType ?? '' },\n { header: 'ACTION', getValue: (item: any) => item.actionType ?? '' },\n { header: 'ACTIVE', getValue: (item: any) => String(item.active ?? '') },\n { header: 'CONDITIONS', getValue: (item: any) => (item.conditions ?? '').slice(0, 40) },\n];\n\n// ── REST helpers ────────────────────────────────────────────────────\n\nfunction baseUrl(ctx: AuthenticatedContext, wid: string): string {\n return `${ctx.envConfig.apiUrl}/api/v2/w/${wid}/journeys`;\n}\n\nfunction notesUrl(ctx: AuthenticatedContext, wid: string, journeyId: string): string {\n return `${baseUrl(ctx, wid)}/${journeyId}/notes`;\n}\n\nfunction headers(ctx: AuthenticatedContext): Record<string, string> {\n return {\n Authorization: `Bearer ${ctx.accessToken}`,\n 'Content-Type': 'application/json',\n };\n}\n\nasync function errorDetail(res: Response): Promise<string> {\n try {\n const text = await res.text();\n const json = JSON.parse(text);\n return json.detail ?? json.message ?? text;\n } catch {\n return '';\n }\n}\n\nasync function apiGet(ctx: AuthenticatedContext, url: string): Promise<unknown> {\n const res = await fetch(url, { headers: headers(ctx) });\n if (!res.ok) {\n const detail = await errorDetail(res);\n throw new CLIError(`GET ${url} failed: ${res.status}${detail ? ` — ${detail}` : ''}`);\n }\n return res.json();\n}\n\nasync function apiPost(ctx: AuthenticatedContext, url: string, body?: unknown): Promise<unknown> {\n const res = await fetch(url, {\n method: 'POST',\n headers: headers(ctx),\n body: body ? JSON.stringify(body) : undefined,\n });\n if (!res.ok) {\n const detail = await errorDetail(res);\n throw new CLIError(`POST ${url} failed: ${res.status}${detail ? ` — ${detail}` : ''}`);\n }\n return res.json();\n}\n\nasync function apiPut(ctx: AuthenticatedContext, url: string, body: unknown): Promise<unknown> {\n const res = await fetch(url, {\n method: 'PUT',\n headers: headers(ctx),\n body: JSON.stringify(body),\n });\n if (!res.ok) {\n const detail = await errorDetail(res);\n throw new CLIError(`PUT ${url} failed: ${res.status}${detail ? ` — ${detail}` : ''}`);\n }\n return res.json();\n}\n\nasync function apiDelete(ctx: AuthenticatedContext, url: string): Promise<void> {\n const res = await fetch(url, { method: 'DELETE', headers: headers(ctx) });\n if (!res.ok) {\n const detail = await errorDetail(res);\n throw new CLIError(`DELETE ${url} failed: ${res.status}${detail ? ` — ${detail}` : ''}`);\n }\n}\n\n// ── Domain definition ───────────────────────────────────────────────\n\nexport const journeysDomain: DomainDef = {\n name: 'journeys',\n description: 'Manage journeys, steps, goals, connections, and enrollment',\n commands: [\n // ── Journey CRUD ───────────────────────────────────────────\n {\n path: ['journeys', 'list'],\n description: 'List all journeys in a workspace',\n requiresWorkspace: true,\n examples: ['gr journeys list -w $WID --env staging'],\n handler: async ({ ctx, workspace }) => {\n const result = await apiGet(requireAuth(ctx), baseUrl(requireAuth(ctx), workspace));\n outputData(listResult(result, false), ctx, JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'get'],\n description: 'Get a journey by ID',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n const result = await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}`\n );\n outputSingle(result, ctx, JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'create'],\n description: 'Create a journey',\n mutates: true,\n requiresWorkspace: true,\n examples: [\n 'gr journeys create -w $WID --data \\'{\"name\":\"Onboarding\",\"description\":\"New patient flow\",\"status\":\"draft\"}\\'',\n '',\n 'Fields: name (required), description, status (draft|active|paused)',\n ' ownerId (member ID), autoEnrollFilterId (filter ID)',\n ],\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await apiPost(\n requireAuth(ctx),\n baseUrl(requireAuth(ctx), workspace),\n data\n );\n outputSingle(result, ctx, JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'update'],\n description: 'Update a journey',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: ['gr journeys update -w $WID --id <journey-id> --data \\'{\"status\":\"active\"}\\''],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = requireString(args, 'id');\n const result = await apiPut(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}`,\n data\n );\n outputSingle(result, ctx, JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'archive'],\n description: 'Archive a journey (soft delete)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n await apiDelete(requireAuth(ctx), `${baseUrl(requireAuth(ctx), workspace)}/${id}`);\n process.stdout.write(`Archived journey ${id}\\n`);\n },\n },\n\n // ── Steps ──────────────────────────────────────────────────\n {\n path: ['journeys', 'steps', 'list'],\n description: 'List steps for a journey (from journey detail)',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: ['gr journeys steps list -w $WID --id <id>'],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n const result = (await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}`\n )) as any;\n outputData(result?.steps ?? [], ctx, STEP_COLUMNS);\n },\n },\n {\n path: ['journeys', 'steps', 'create'],\n description: 'Create a step in a journey',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'journey-id', description: 'Journey ID', required: true }],\n examples: [\n 'gr journeys steps create -w $WID --journey-id <journey-id> --data \\'{\"name\":\"Intake\"}\\'',\n '',\n 'Fields: name (required), description, order (int), workflowId (int),',\n ' assigneeId (member ID), posX/posY (canvas coords)',\n '',\n 'Attach event rules (e.g. label member) via \"gr events rules create\"',\n 'with eventType \"journey_step:execute\" and journeyStepId <step-id>',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const journeyId = requireString(args, 'journey-id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/steps`,\n data\n );\n outputSingle(result, ctx, STEP_COLUMNS);\n },\n },\n {\n path: ['journeys', 'steps', 'update'],\n description: 'Update a step',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Step UUID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const journeyId = requireString(args, 'journey-id');\n const stepId = requireString(args, 'id');\n const result = await apiPut(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/steps/${stepId}`,\n data\n );\n outputSingle(result, ctx, STEP_COLUMNS);\n },\n },\n {\n path: ['journeys', 'steps', 'archive'],\n description: 'Archive a step',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Step UUID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const stepId = requireString(args, 'id');\n await apiDelete(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/steps/${stepId}`\n );\n process.stdout.write(`Archived step ${stepId}\\n`);\n },\n },\n\n // ── Connections ────────────────────────────────────────────\n {\n path: ['journeys', 'connections', 'list'],\n description: 'List connections for a journey (aggregated from steps)',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: ['gr journeys connections list -w $WID --id <id>'],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n const result = (await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}`\n )) as any;\n // Connections are nested in steps — dedupe by id from childConnections\n const seen = new Set<number>();\n const connections: unknown[] = [];\n for (const step of result?.steps ?? []) {\n for (const conn of step?.childConnections ?? []) {\n if (!seen.has(conn.id)) {\n seen.add(conn.id);\n connections.push(conn);\n }\n }\n }\n outputData(connections, ctx, CONNECTION_COLUMNS);\n },\n },\n {\n path: ['journeys', 'connections', 'create'],\n description: 'Create a DAG edge between two steps (with optional CEL condition)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'journey-id', description: 'Journey ID', required: true }],\n examples: [\n 'gr journeys connections create -w $WID --journey-id <journey-id> \\\\',\n ' --data \\'{\"parentStepUuid\":\"<src>\",\"childStepUuid\":\"<dst>\"}\\'',\n '',\n 'Fields: parentStepUuid (required), childStepUuid (required),',\n ' order (int), celCondition (CEL expression string),',\n ' required (bool, default false), timeoutSeconds (int),',\n ' filterId (member filter ID, optional)',\n '',\n 'CEL condition example: \"member.labels.contains(\\\\\"step-1-done\\\\\")\"',\n '',\n 'Required edge (AND-gate — child waits for this parent):',\n ' --data \\'{\"parentStepUuid\":\"<src>\",\"childStepUuid\":\"<dst>\",\"required\":true}\\'',\n '',\n 'Edge with CEL timeout (300s = 5 min):',\n ' --data \\'{\"parentStepUuid\":\"<src>\",\"childStepUuid\":\"<dst>\",',\n ' \"celCondition\":\"member.labels.contains(\\\\\"approved\\\\\")\",\"timeoutSeconds\":300}\\'',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const journeyId = requireString(args, 'journey-id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/connections`,\n data\n );\n outputSingle(result, ctx, CONNECTION_COLUMNS);\n },\n },\n {\n path: ['journeys', 'connections', 'update'],\n description: 'Update a connection',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Connection ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const journeyId = requireString(args, 'journey-id');\n const connId = requireString(args, 'id');\n const result = await apiPut(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/connections/${connId}`,\n data\n );\n outputSingle(result, ctx, CONNECTION_COLUMNS);\n },\n },\n {\n path: ['journeys', 'connections', 'delete'],\n description: 'Remove a connection',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Connection ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const connId = requireString(args, 'id');\n await apiDelete(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/connections/${connId}`\n );\n process.stdout.write(`Deleted connection ${connId}\\n`);\n },\n },\n\n // ── Goals ──────────────────────────────────────────────────\n {\n path: ['journeys', 'goals', 'list'],\n description: 'List goals for a journey (from journey detail)',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: ['gr journeys goals list -w $WID --id <id>'],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n const result = (await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}`\n )) as any;\n outputData(result?.goals ?? [], ctx, GOAL_COLUMNS);\n },\n },\n {\n path: ['journeys', 'goals', 'create'],\n description: 'Create a goal (high-value outcome to track) for a journey',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'journey-id', description: 'Journey ID', required: true }],\n examples: [\n 'gr journeys goals create -w $WID --journey-id <journey-id> \\\\',\n ' --data \\'{\"name\":\"Onboarded\",\"goalStepUuid\":\"<step-uuid>\"}\\'',\n '',\n 'Fields: name (required), description, goalStepUuid (step that satisfies goal),',\n ' completionCel (CEL expression), value (float), order (int)',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const journeyId = requireString(args, 'journey-id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/goals`,\n data\n );\n outputSingle(result, ctx, GOAL_COLUMNS);\n },\n },\n {\n path: ['journeys', 'goals', 'update'],\n description: 'Update a goal',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Goal UUID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const journeyId = requireString(args, 'journey-id');\n const goalId = requireString(args, 'id');\n const result = await apiPut(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/goals/${goalId}`,\n data\n );\n outputSingle(result, ctx, GOAL_COLUMNS);\n },\n },\n {\n path: ['journeys', 'goals', 'delete'],\n description: 'Delete a goal',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Goal UUID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const goalId = requireString(args, 'id');\n await apiDelete(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/goals/${goalId}`\n );\n process.stdout.write(`Deleted goal ${goalId}\\n`);\n },\n },\n\n // ── Enrollment ─────────────────────────────────────────────\n {\n path: ['journeys', 'enroll'],\n description: 'Enroll member(s) in a journey',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: [\n 'gr journeys enroll -w $WID --id <id> --data \\'{\"memberIds\":[1,2,3]}\\'',\n 'gr journeys enroll -w $WID --id <id> --data \\'{\"memberId\":42}\\'',\n '',\n 'Fields: memberId (single) or memberIds (batch, max 100)',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = requireString(args, 'id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}/enroll`,\n data\n );\n outputData(listResult(result, false), ctx, MEMBER_JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'unenroll'],\n description: 'Unenroll member(s) from a journey',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: [\n 'gr journeys unenroll -w $WID --id <journey-id> --data \\'{\"memberIds\":[1],\"canceledReason\":\"test\"}\\'',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = requireString(args, 'id');\n await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}/unenroll`,\n data\n );\n process.stdout.write(`Unenrolled member(s) from journey ${id}\\n`);\n },\n },\n {\n path: ['journeys', 'reenroll'],\n description: 'Re-enroll a canceled member back into a journey',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = requireString(args, 'id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}/reenroll`,\n data\n );\n outputSingle(result, ctx, MEMBER_JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'members', 'delete'],\n description: 'Hard-delete a canceled enrollment so member can re-enroll fresh',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'member-id', description: 'Member ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const memberId = requireString(args, 'member-id');\n await apiDelete(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/members/${memberId}`\n );\n process.stdout.write(\n `Deleted enrollment for member ${memberId} from journey ${journeyId}\\n`\n );\n },\n },\n {\n path: ['journeys', 'members', 'list'],\n description: 'List members enrolled in a journey',\n requiresWorkspace: true,\n args: [{ name: 'journey-id', description: 'Journey ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const result = await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/members`\n );\n outputData(listResult(result, false), ctx, MEMBER_JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'members', 'get'],\n description: \"Get a member's journeys\",\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const memberId = requireString(args, 'member-id');\n const result = await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/by-member/${memberId}`\n );\n outputData(listResult(result, false), ctx, MEMBER_JOURNEY_COLUMNS);\n },\n },\n\n // ── Step progression ───────────────────────────────────────\n {\n path: ['journeys', 'steps', 'advance'],\n description: 'Mark a step as completed for a member (triggers downstream propagation)',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Step UUID', required: true },\n ],\n examples: [\n 'gr journeys steps advance -w $WID --journey-id <journey-id> --id <step-uuid>',\n 'gr journeys steps advance -w $WID --journey-id <journey-id> --id <step-uuid> --data \\'{\"memberId\":42,\"notes\":\"Passed\"}\\'',\n '',\n 'Fields: memberId (defaults to current user), notes (optional)',\n 'Completing a step makes downstream steps eligible (if all parents complete)',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const journeyId = requireString(args, 'journey-id');\n const stepId = requireString(args, 'id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/steps/${stepId}/advance`,\n data ?? {}\n );\n outputSingle(result, ctx, MEMBER_STEP_COLUMNS);\n },\n },\n {\n path: ['journeys', 'steps', 'skip'],\n description: 'Skip a step for a member (requires journeys:admin scope)',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Step UUID', required: true },\n ],\n examples: [\n 'gr journeys steps skip -w $WID --journey-id <journey-id> --id <step-uuid> --data \\'{\"memberId\":42,\"reason\":\"N/A\"}\\'',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const journeyId = requireString(args, 'journey-id');\n const stepId = requireString(args, 'id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/steps/${stepId}/skip`,\n data ?? {}\n );\n outputSingle(result, ctx, MEMBER_STEP_COLUMNS);\n },\n },\n\n // ── Step member visibility ──────────────────────────────────\n {\n path: ['journeys', 'steps', 'members'],\n description: 'List members at a specific journey step',\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Step UUID', required: true },\n ],\n examples: [\n 'gr journeys steps members -w $WID --journey-id 5 --id <step-uuid>',\n 'gr journeys steps members -w $WID --journey-id 5 --id <step-uuid> --data \\'{\"status\":\"in_progress\"}\\'',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const journeyId = requireString(args, 'journey-id');\n const stepId = requireString(args, 'id');\n const qs = new URLSearchParams();\n if (data && typeof data === 'object') {\n const d = data as Record<string, unknown>;\n if (d.status) qs.set('status', String(d.status));\n if (d.mode) qs.set('mode', String(d.mode));\n if (d.page) qs.set('page', String(d.page));\n if (d.pageSize) qs.set('pageSize', String(d.pageSize));\n }\n const query = qs.toString();\n const url = `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/steps/${stepId}/members${query ? `?${query}` : ''}`;\n const result = await apiGet(requireAuth(ctx), url);\n const STEP_MEMBER_COLS: TableColumn<unknown>[] = [\n { header: 'MEMBER_ID', getValue: (item: any) => String(item.memberId ?? '') },\n { header: 'NAME', getValue: (item: any) => item.memberName ?? '' },\n { header: 'STATUS', getValue: (item: any) => item.stepStatus ?? '' },\n { header: 'ELIGIBLE', getValue: (item: any) => item.eligibleAt ?? '' },\n { header: 'ACTIVATED', getValue: (item: any) => item.activatedAt ?? '' },\n { header: 'COMPLETED', getValue: (item: any) => item.completedAt ?? '' },\n ];\n outputData(listResult(result, false), ctx, STEP_MEMBER_COLS);\n },\n },\n {\n path: ['journeys', 'step-member-counts'],\n description: 'Get member counts per step for a journey',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: ['gr journeys step-member-counts -w $WID --id 5'],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n const result = await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}/step-member-counts`\n );\n const COUNT_COLS: TableColumn<unknown>[] = [\n { header: 'STEP_ID', getValue: (item: any) => String(item.stepId ?? '') },\n {\n header: 'STEP_UUID',\n getValue: (item: any) => (item.stepUuid ?? '').slice(0, 8),\n },\n { header: 'TOTAL', getValue: (item: any) => String(item.total ?? 0) },\n {\n header: 'BY_STATUS',\n getValue: (item: any) => {\n const bs = item.byStatus;\n if (!bs || typeof bs !== 'object') return '';\n return Object.entries(bs)\n .filter(([, v]) => (v as number) > 0)\n .map(([k, v]) => `${k}:${v}`)\n .join(', ');\n },\n },\n ];\n outputData(listResult(result, false), ctx, COUNT_COLS);\n },\n },\n\n // ── Notes ───────────────────────────────────────────────────\n {\n path: ['journeys', 'notes', 'list'],\n description: 'List notes for a journey',\n requiresWorkspace: true,\n args: [{ name: 'journey-id', description: 'Journey ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const result = await apiGet(\n requireAuth(ctx),\n notesUrl(requireAuth(ctx), workspace, journeyId)\n );\n outputData(listResult(result, false), ctx, NOTE_COLUMNS);\n },\n },\n {\n path: ['journeys', 'notes', 'create'],\n description: 'Create a note on a journey (canvas sticky note)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'journey-id', description: 'Journey ID', required: true }],\n examples: [\n 'gr journeys notes create -w $WID --journey-id 5 --data \\'{\"posX\":0,\"posY\":0,\"contents\":\"Note text\"}\\'',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data with content)');\n const journeyId = requireString(args, 'journey-id');\n const result = await apiPost(\n requireAuth(ctx),\n notesUrl(requireAuth(ctx), workspace, journeyId),\n data\n );\n outputSingle(result, ctx, NOTE_COLUMNS);\n },\n },\n {\n path: ['journeys', 'notes', 'update'],\n description: 'Update a journey note',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Note ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data with content)');\n const journeyId = requireString(args, 'journey-id');\n const noteId = requireString(args, 'id');\n const result = await apiPut(\n requireAuth(ctx),\n `${notesUrl(requireAuth(ctx), workspace, journeyId)}/${noteId}`,\n data\n );\n outputSingle(result, ctx, NOTE_COLUMNS);\n },\n },\n {\n path: ['journeys', 'notes', 'delete'],\n description: 'Delete a journey note',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Note ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const noteId = requireString(args, 'id');\n await apiDelete(\n requireAuth(ctx),\n `${notesUrl(requireAuth(ctx), workspace, journeyId)}/${noteId}`\n );\n process.stdout.write(`Deleted note ${noteId}\\n`);\n },\n },\n\n // ── Step execute actions (event rules scoped to a step) ────────\n {\n path: ['journeys', 'steps', 'actions', 'list'],\n description: 'List event rules (actions) attached to a journey step',\n requiresWorkspace: true,\n args: [\n { name: 'step-id', description: 'Journey step ID (numeric)', required: true },\n {\n name: 'include-disabled',\n description: 'Include inactive/disabled rules',\n isFlag: true,\n },\n ],\n examples: [\n 'gr journeys steps actions list -w $WID --step-id <step-id>',\n 'gr journeys steps actions list -w $WID --step-id <step-id> --include-disabled',\n ],\n handler: async ({ ctx, workspace, args }) => {\n const stepId = requireNumber(args, 'step-id');\n const includeDisabled = args['include-disabled'] === true;\n const result = await requireAuth(ctx).apiClient.searchEventRules(workspace, {\n eventType: EventRuleEventType.JOURNEY_STEP_EXECUTE,\n journeyStepId: stepId,\n ...(includeDisabled ? { includeDisabled: true } : {}),\n });\n outputData(listResult(result, false), ctx, ACTION_COLUMNS);\n },\n },\n {\n path: ['journeys', 'steps', 'actions', 'get'],\n description: 'Get a journey step action (event rule) by ID',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event rule ID', required: true }],\n examples: ['gr journeys steps actions get -w $WID --id <rule-id>'],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.getEventRule(workspace, id);\n outputSingle(result, ctx, ACTION_COLUMNS);\n },\n },\n {\n path: ['journeys', 'steps', 'actions', 'update'],\n description: 'Update a journey step action — modify template, conditions, or active state',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event rule ID', required: true }],\n examples: [\n 'gr journeys steps actions update -w $WID --id <rule-id> \\\\',\n ' --data \\'{\"actionParams\":{\"messageTemplate\":\"Hello {{member.name}}\"}}\\' --allow-write',\n '',\n 'Updatable fields: name, conditions (CEL), actionParams, active, delay, order',\n 'Non-updatable: objectType, eventType, actionType, journeyStepId',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.updateEventRule(\n workspace,\n id,\n data as any\n );\n outputSingle(result, ctx, ACTION_COLUMNS);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport type { TableColumn } from '../lib/output';\nimport { COL } from '../lib/output';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'AGE', getValue: (item: any) => (item.age != null ? String(item.age) : '') },\n {\n header: 'HAS_PHONE',\n getValue: (item: any) => (item.hasPhone ? 'yes' : 'no'),\n },\n {\n header: 'HAS_EMAIL',\n getValue: (item: any) => (item.hasEmail ? 'yes' : 'no'),\n },\n {\n header: 'DATA_RECORDS',\n getValue: (item: any) =>\n item.dataRecords ? String(Object.keys(item.dataRecords).length) : '0',\n },\n COL.created(),\n];\n\nexport const personasDomain: DomainDef = {\n name: 'personas',\n description: 'Manage workspace-scoped test personas (identity templates for scenario runs)',\n commands: [\n ...crudCommands({\n prefix: ['personas'],\n entityName: 'persona',\n listMethod: 'listPersonas',\n getMethod: 'getPersona',\n createMethod: 'createPersona',\n updateMethod: 'updatePersona',\n deleteMethod: 'deletePersona',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst QUALIFICATION_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'WORKFLOW', getValue: (item: any) => String(item.workflowId ?? '') },\n { header: 'WORKFLOW_NAME', getValue: (item: any) => item.workflowName ?? '' },\n COL.created(),\n];\n\nconst SCENARIO_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'PERSONA', getValue: (item: any) => item.personaName ?? '' },\n { header: 'CHANNEL', getValue: (item: any) => item.channel ?? '' },\n];\n\nconst RUN_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'WORKFLOW', getValue: (item: any) => String(item.workflowId ?? '') },\n {\n header: 'SCENARIO',\n getValue: (item: any) =>\n item.scenarioName ?? (item.scenarioId != null ? String(item.scenarioId) : 'ad-hoc'),\n },\n {\n header: 'DRIVER',\n getValue: (item: any) =>\n item.driverMemberId == null\n ? 'auto'\n : (item.driverMemberName ?? `member #${item.driverMemberId}`),\n },\n { header: 'STARTED', getValue: (item: any) => item.startedAt ?? '' },\n { header: 'COMPLETED', getValue: (item: any) => item.completedAt ?? '' },\n {\n header: 'SCORE',\n getValue: (item: any) => (item.overallScore != null ? String(item.overallScore) : ''),\n },\n {\n header: 'PASSED',\n getValue: (item: any) => (item.passed != null ? String(item.passed) : ''),\n },\n];\n\nexport const qualificationsDomain: DomainDef = {\n name: 'qualifications',\n description: 'Manage qualifications, scenarios, and test chat runs',\n commands: [\n {\n path: ['qualifications', 'list'],\n description: 'List qualifications (one per workflow)',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getQualifications(workspace);\n outputData(result.items, ctx, QUALIFICATION_COLUMNS);\n },\n },\n {\n path: ['qualifications', 'get'],\n description: 'Get a qualification by ID',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Qualification ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getQualification(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['qualifications', 'for-workflow'],\n description: 'Fetch (auto-creating if absent) the qualification for a workflow',\n requiresWorkspace: true,\n args: [{ name: 'workflow-id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getOrCreateQualificationForWorkflow(\n workspace,\n requireNumber(args, 'workflow-id')\n );\n outputSingle(result, ctx);\n },\n },\n // Scenarios\n {\n path: ['qualifications', 'scenarios', 'list'],\n description: 'List scenarios on a qualification',\n requiresWorkspace: true,\n args: [{ name: 'qualification-id', description: 'Qualification ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.listScenarios(\n workspace,\n requireNumber(args, 'qualification-id')\n );\n outputData(result, ctx, SCENARIO_COLUMNS);\n },\n },\n {\n path: ['qualifications', 'scenarios', 'get'],\n description: 'Get a scenario',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Scenario ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getScenario(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, SCENARIO_COLUMNS);\n },\n },\n {\n path: ['qualifications', 'scenarios', 'create'],\n description: 'Create a scenario on a qualification (pass JSON via --data)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'qualification-id', description: 'Qualification ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.createScenario(\n workspace,\n requireNumber(args, 'qualification-id'),\n data as any\n );\n outputSingle(result, ctx, SCENARIO_COLUMNS);\n },\n },\n {\n path: ['qualifications', 'scenarios', 'update'],\n description: 'Update a scenario (pass JSON via --data)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Scenario ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateScenario(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, SCENARIO_COLUMNS);\n },\n },\n {\n path: ['qualifications', 'scenarios', 'delete'],\n description: 'Archive a scenario',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Scenario ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deleteScenario(workspace, requireNumber(args, 'id'));\n process.stdout.write(`Archived scenario ${args['id']}\\n`);\n },\n },\n // Test chat runs\n {\n path: ['qualifications', 'runs', 'list'],\n description: 'List recent test chat runs for a workflow',\n requiresWorkspace: true,\n args: [\n { name: 'workflow-id', description: 'Workflow ID', required: true },\n { name: 'scenario-id', description: 'Filter by scenario', required: false },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const scenarioId = args['scenario-id'] ? requireNumber(args, 'scenario-id') : undefined;\n const result = await requireAuth(ctx).apiClient.listTestChatRuns(\n workspace,\n requireNumber(args, 'workflow-id'),\n scenarioId != null ? { scenarioId } : undefined\n );\n outputData(result, ctx, RUN_COLUMNS);\n },\n },\n {\n path: ['qualifications', 'runs', 'get'],\n description: 'Get a test chat run',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Test chat run ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getTestChatRun(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['qualifications', 'runs', 'start'],\n description: 'Start a test chat run',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'workflow-id', description: 'Workflow ID', required: true },\n { name: 'scenario-id', description: 'Bind to a scenario', required: false },\n {\n name: 'persona-id',\n description: 'Persona (required if no scenario)',\n required: false,\n },\n { name: 'goal', description: 'Goal for the user simulator', required: false },\n { name: 'driver', description: 'Driver mode: auto | human', required: false },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const driver = (args['driver'] === 'human' ? 'human' : 'auto') as 'auto' | 'human';\n const scenarioId = args['scenario-id'] ? requireNumber(args, 'scenario-id') : undefined;\n const personaId = args['persona-id'] ? requireNumber(args, 'persona-id') : undefined;\n const result = await requireAuth(ctx).apiClient.startTestChatRun(\n workspace,\n requireNumber(args, 'workflow-id'),\n {\n ...(scenarioId != null ? { scenarioId } : {}),\n ...(personaId != null ? { personaId } : {}),\n ...(args['goal'] ? { goal: String(args['goal']) } : {}),\n driver,\n } as any\n );\n outputSingle(result.run, ctx);\n },\n },\n {\n path: ['qualifications', 'runs', 'evaluate'],\n description: 'Evaluate a completed scenario-bound test chat run',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Test chat run ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.evaluateTestChatRun(\n workspace,\n requireNumber(args, 'id')\n );\n process.stdout.write(`Evaluation started for test chat run ${args['id']}\\n`);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n { header: 'DOMAIN', getValue: (item: any) => item.domain ?? '' },\n];\n\nconst PAGE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'TITLE', getValue: (item: any) => item.title ?? '' },\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.status(),\n];\n\nconst MENU_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'LABEL', getValue: (item: any) => item.label ?? '' },\n { header: 'TYPE', getValue: (item: any) => item.type ?? '' },\n { header: 'ORDER', getValue: (item: any) => String(item.order ?? '') },\n];\n\nexport const sitesDomain: DomainDef = {\n name: 'sites',\n description: 'Manage sites, pages, and menus',\n commands: [\n ...crudCommands({\n prefix: ['sites'],\n entityName: 'site',\n listMethod: 'getSites',\n getMethod: 'getSite',\n createMethod: 'createSite',\n updateMethod: 'updateSite',\n deleteMethod: 'deleteSite',\n columns: COLUMNS,\n }),\n // Pages sub-resource\n {\n path: ['sites', 'pages', 'list'],\n description: 'List pages for a site',\n requiresWorkspace: true,\n args: [{ name: 'site-id', description: 'Site ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getSitePages(\n workspace,\n requireNumber(args, 'site-id')\n );\n outputData(result, ctx, PAGE_COLUMNS);\n },\n },\n {\n path: ['sites', 'pages', 'get'],\n description: 'Get a page',\n requiresWorkspace: true,\n args: [\n { name: 'site-id', description: 'Site ID', required: true },\n { name: 'id', description: 'Page ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getPage(\n workspace,\n requireNumber(args, 'site-id'),\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, PAGE_COLUMNS);\n },\n },\n {\n path: ['sites', 'pages', 'create'],\n description: 'Create a page',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'site-id', description: 'Site ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.createPage(\n workspace,\n requireNumber(args, 'site-id'),\n data as any\n );\n outputSingle(result, ctx, PAGE_COLUMNS);\n },\n },\n {\n path: ['sites', 'pages', 'update'],\n description: 'Update a page',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'site-id', description: 'Site ID', required: true },\n { name: 'id', description: 'Page ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updatePage(\n workspace,\n requireNumber(args, 'site-id'),\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, PAGE_COLUMNS);\n },\n },\n {\n path: ['sites', 'pages', 'delete'],\n description: 'Delete a page',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'site-id', description: 'Site ID', required: true },\n { name: 'id', description: 'Page ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deletePage(\n workspace,\n requireNumber(args, 'site-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write(`Deleted page ${args.id}\\n`);\n },\n },\n // Menu items sub-resource\n {\n path: ['sites', 'menu', 'list'],\n description: 'List menu items for a site',\n requiresWorkspace: true,\n args: [{ name: 'site-id', description: 'Site ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getMenuItems(\n workspace,\n requireNumber(args, 'site-id')\n );\n outputData(result, ctx, MENU_COLUMNS);\n },\n },\n {\n path: ['sites', 'menu', 'create'],\n description: 'Create a menu item',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'site-id', description: 'Site ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.createMenuItem(\n workspace,\n requireNumber(args, 'site-id'),\n data as any\n );\n outputSingle(result, ctx, MENU_COLUMNS);\n },\n },\n {\n path: ['sites', 'menu', 'update'],\n description: 'Update a menu item',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'site-id', description: 'Site ID', required: true },\n { name: 'id', description: 'Menu item ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateMenuItem(\n workspace,\n requireNumber(args, 'site-id'),\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, MENU_COLUMNS);\n },\n },\n {\n path: ['sites', 'menu', 'delete'],\n description: 'Delete a menu item',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'site-id', description: 'Site ID', required: true },\n { name: 'id', description: 'Menu item ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deleteMenuItem(\n workspace,\n requireNumber(args, 'site-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write(`Deleted menu item ${args.id}\\n`);\n },\n },\n ],\n};\n","import { type DomainDef, requireString, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { listResult } from '../lib/pagination';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.status(),\n { header: 'GRANTOR', getValue: (item: any) => String(item.grantor_member_id ?? '') },\n { header: 'GRANTEE', getValue: (item: any) => String(item.grantee_member_id ?? '') },\n COL.created(),\n];\n\nexport const accessGrantsDomain: DomainDef = {\n name: 'access-grants',\n description: 'Manage access grants',\n commands: [\n {\n path: ['access-grants', 'list'],\n description: 'List all access grants',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getAccessGrants(workspace);\n outputData(listResult(result, false), ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'get'],\n description: 'Get an access grant by ID',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Access grant ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getAccessGrant(\n workspace,\n requireString(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'create'],\n description: 'Create an access grant',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.createAccessGrant(\n workspace,\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'received'],\n description: 'List access grants received by me',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMyReceivedGrants(workspace, {\n pageSize: 200,\n });\n outputData(listResult(result, false), ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'given'],\n description: 'List access grants given by me',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMyGivenGrants(workspace, {\n pageSize: 200,\n });\n outputData(listResult(result, false), ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'resolve'],\n description: 'Resolve an access grant',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Access grant ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.resolveAccessGrant(\n workspace,\n requireString(args, 'id'),\n (data ?? {}) as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'revoke'],\n description: 'Revoke an access grant',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Access grant ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.revokeAccessGrant(\n workspace,\n requireString(args, 'id'),\n (data ?? {}) as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'member'],\n description: 'List access grants for a specific member',\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getMemberGrants(\n workspace,\n requireNumber(args, 'member-id')\n );\n outputData(listResult(result, false), ctx, COLUMNS);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n { header: 'ID', getValue: (item: any) => String(item.id ?? item.model_id ?? '') },\n { header: 'NAME', getValue: (item: any) => item.name ?? item.display_name ?? '' },\n { header: 'PROVIDER', getValue: (item: any) => item.provider ?? '' },\n { header: 'TYPE', getValue: (item: any) => item.type ?? '' },\n];\n\nexport const aiModelsDomain: DomainDef = {\n name: 'ai-models',\n description: 'List available AI models',\n commands: [\n {\n path: ['ai-models', 'list'],\n description: 'List all available AI models',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getAllModels();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['ai-models', 'chat'],\n description: 'List chat models',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getChatModels();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['ai-models', 'realtime'],\n description: 'List realtime models',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getRealtimeModels();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['ai-models', 'voice'],\n description: 'List voice models',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getVoiceModels();\n outputData(result, ctx, COLUMNS);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'PREFIX', getValue: (item: any) => item.prefix ?? '' },\n COL.created(),\n];\n\n// Includes the plaintext key — only used on create responses where the key is present.\nconst CREATE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'KEY', getValue: (item: any) => item.key ?? '' },\n { header: 'PREFIX', getValue: (item: any) => item.prefix ?? '' },\n COL.created(),\n];\n\nexport const apiKeysDomain: DomainDef = {\n name: 'api-keys',\n description: 'Manage API keys',\n commands: [\n {\n path: ['api-keys', 'list'],\n description: 'List workspace API keys',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getApiKeys(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['api-keys', 'create'],\n description: 'Create a workspace API key',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.createApiKey(workspace, data as any);\n outputSingle(result, ctx, CREATE_COLUMNS);\n if (ctx.outputFormat === 'table') {\n process.stdout.write('\\n⚠ This key will not be shown again. Copy it now.\\n');\n }\n },\n },\n {\n path: ['api-keys', 'revoke'],\n description: 'Revoke a workspace API key',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'API key ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.revokeApiKey(workspace, id);\n process.stdout.write(`Revoked API key ${id}\\n`);\n },\n },\n {\n path: ['api-keys', 'global', 'list'],\n description: 'List global/account-level API keys',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getGlobalApiKeys();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['api-keys', 'global', 'create'],\n description: 'Create a global/account-level API key',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.createGlobalApiKey(data as any);\n outputSingle(result, ctx, CREATE_COLUMNS);\n if (ctx.outputFormat === 'table') {\n process.stdout.write('\\n⚠ This key will not be shown again. Copy it now.\\n');\n }\n },\n },\n {\n path: ['api-keys', 'global', 'revoke'],\n description: 'Revoke a global/account-level API key',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'API key ID', required: true }],\n handler: async ({ ctx, args }) => {\n const id = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.revokeGlobalApiKey(id);\n process.stdout.write(`Revoked global API key ${id}\\n`);\n },\n },\n ],\n};\n","import { type DomainDef, requireString } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst APP_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'CLIENT_ID', getValue: (item: any) => item.client_id ?? '' },\n COL.status(),\n];\n\nconst BUILDER_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.name(), COL.status()];\n\nconst INQUIRY_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.status(), COL.created()];\n\nexport const appsDomain: DomainDef = {\n name: 'apps',\n description: 'Manage apps, builders, and inquiries',\n commands: [\n // Apps\n {\n path: ['apps', 'list'],\n description: 'List apps',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.listApps();\n outputData(result, ctx, APP_COLUMNS);\n },\n },\n {\n path: ['apps', 'get'],\n description: 'Get an app by ID',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'App ID', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.getApp(requireString(args, 'id'));\n outputSingle(result, ctx, APP_COLUMNS);\n },\n },\n {\n path: ['apps', 'create'],\n description: 'Create an app',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.createApp(data as any);\n outputSingle(result, ctx, APP_COLUMNS);\n },\n },\n {\n path: ['apps', 'update'],\n description: 'Update an app',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'App ID', required: true }],\n handler: async ({ ctx, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateApp(\n requireString(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, APP_COLUMNS);\n },\n },\n {\n path: ['apps', 'delete'],\n description: 'Delete an app',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'App ID', required: true }],\n handler: async ({ ctx, args }) => {\n const id = requireString(args, 'id');\n await requireAuth(ctx).apiClient.deleteApp(id);\n process.stdout.write(`Deleted app ${id}\\n`);\n },\n },\n {\n path: ['apps', 'regenerate-secret'],\n description: 'Regenerate client secret for an app',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'App ID', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.regenerateClientSecret(\n requireString(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n\n // Builders\n ...crudCommands({\n prefix: ['apps', 'builders'],\n entityName: 'builder',\n listMethod: 'listBuilders',\n getMethod: 'getBuilder',\n createMethod: 'createBuilder',\n updateMethod: 'updateBuilder',\n deleteMethod: 'deleteBuilder',\n columns: BUILDER_COLUMNS,\n requiresWorkspace: false,\n }),\n {\n path: ['apps', 'builders', 'apps'],\n description: 'List apps for a builder',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Builder ID', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.getBuilderApps(\n requireString(args, 'id')\n );\n outputData(result, ctx, APP_COLUMNS);\n },\n },\n\n // Inquiries\n ...crudCommands({\n prefix: ['apps', 'inquiries'],\n entityName: 'inquiry',\n listMethod: 'listInquiries',\n getMethod: 'getInquiry',\n createMethod: 'createInquiry',\n updateMethod: 'updateInquiry',\n deleteMethod: 'deleteInquiry',\n columns: INQUIRY_COLUMNS,\n requiresWorkspace: false,\n paginationSupport: 'full',\n }),\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputSingle, outputData } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nexport const authManageDomain: DomainDef = {\n name: 'auth',\n description: 'Manage authentication, 2FA, and credentials',\n commands: [\n {\n path: ['auth', 'account'],\n description: 'Get current user account info',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getUserAccount();\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', 'update-account'],\n description: 'Update current user account',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.updateUserAccount(data as any);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', 'password-status'],\n description: 'Get password status',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getPasswordStatus();\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', 'change-password'],\n description: 'Change password',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.changePassword(\n (data as any)?.currentPassword,\n (data as any)?.newPassword\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', 'set-password'],\n description: 'Set password (for accounts without one)',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.setPassword(data as any);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', '2fa-status'],\n description: 'Get two-factor authentication status',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getTwoFactorStatus();\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', 'pending-credential-changes'],\n description: 'List pending credential changes',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getPendingCredentialChanges();\n outputData(result, ctx);\n },\n },\n {\n path: ['auth', 'request-credential-change'],\n description: 'Request a credential change',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.requestCredentialChange(\n (data as any)?.credentialType,\n (data as any)?.newValue\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', 'cancel-credential-change'],\n description: 'Cancel a pending credential change',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Credential change ID', required: true }],\n handler: async ({ ctx, args }) => {\n await requireAuth(ctx).apiClient.cancelCredentialChange(requireNumber(args, 'id'));\n process.stdout.write(`Cancelled credential change ${args.id}\\n`);\n },\n },\n // ── Consent (GDPR) ──\n {\n path: ['auth', 'consent'],\n description: 'Get current consent state',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getConsentState();\n const columns: TableColumn<unknown>[] = [\n { header: 'TYPE', getValue: (item: any) => item.consent_type ?? '' },\n { header: 'GRANTED', getValue: (item: any) => String(item.granted) },\n { header: 'UPDATED', getValue: (item: any) => item.updated_at ?? '' },\n { header: 'VERSION', getValue: (item: any) => item.policy_version ?? '' },\n ];\n outputData(result.consents, ctx, columns);\n },\n },\n {\n path: ['auth', 'consent-update'],\n description:\n 'Update consent (e.g. --data \\'{\"consents\":[{\"consent_type\":\"cookie_analytics\",\"granted\":true}]}\\')',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const body = data as any;\n const consents = body?.consents;\n if (!Array.isArray(consents) || consents.length === 0) {\n process.stderr.write(\n 'Error: --data must include \"consents\" array, e.g. --data \\'{\"consents\":[{\"consent_type\":\"cookie_analytics\",\"granted\":true}]}\\'\\n'\n );\n process.exit(1);\n }\n const result = await requireAuth(ctx).apiClient.updateConsent(consents);\n const columns: TableColumn<unknown>[] = [\n { header: 'TYPE', getValue: (item: any) => item.consent_type ?? '' },\n { header: 'GRANTED', getValue: (item: any) => String(item.granted) },\n { header: 'UPDATED', getValue: (item: any) => item.updated_at ?? '' },\n { header: 'VERSION', getValue: (item: any) => item.policy_version ?? '' },\n ];\n outputData(result.consents, ctx, columns);\n },\n },\n ],\n};\n","// `Invoice` is not re-exported from the public `@gravity-rail/sdk` surface.\n// Use a structural shape that matches the runtime response.\ninterface Invoice {\n id: number;\n invoiceNumber: string;\n status: string;\n amount: number;\n periodStart?: string;\n periodEnd?: string;\n productName?: string;\n paymentReference?: string | null;\n}\nimport { CLIError } from '../lib/errors';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle } from '../lib/output';\nimport { listResult } from '../lib/pagination';\nimport type { CommandDef, DomainDef } from '../lib/types';\nimport { requireAuth } from '../lib/context';\n\nconst INVOICE_COLUMNS: TableColumn<Invoice>[] = [\n { header: 'ID', getValue: (i) => String(i.id) },\n { header: 'Invoice #', getValue: (i) => i.invoiceNumber },\n { header: 'Status', getValue: (i) => i.status },\n {\n header: 'Amount',\n getValue: (i) => `$${(i.amount / 100).toFixed(2)}`,\n },\n {\n header: 'Period Start',\n getValue: (i) => (i.periodStart ? new Date(i.periodStart).toLocaleDateString() : ''),\n },\n {\n header: 'Period End',\n getValue: (i) => (i.periodEnd ? new Date(i.periodEnd).toLocaleDateString() : ''),\n },\n { header: 'Product', getValue: (i) => i.productName ?? '' },\n { header: 'Ref', getValue: (i) => i.paymentReference ?? '' },\n];\n\nconst commands: CommandDef[] = [\n {\n path: ['billing', 'customers'],\n description: 'List your customer accounts',\n requiresWorkspace: false,\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.getMyCustomers();\n outputData(listResult(result, false), hctx.ctx);\n },\n },\n {\n path: ['billing', 'customer'],\n description: 'Get a customer by UUID',\n args: [{ name: 'uuid', description: 'Customer UUID', required: true }],\n requiresWorkspace: false,\n handler: async (hctx) => {\n const uuid = hctx.args.uuid as string;\n const result = await requireAuth(hctx.ctx).apiClient.getMyCustomer(uuid);\n outputSingle(result, hctx.ctx);\n },\n },\n {\n path: ['billing', 'update-customer'],\n description: 'Update a customer record (billing owner only)',\n mutates: true,\n args: [\n { name: 'uuid', description: 'Customer UUID', required: true },\n { name: 'name', description: 'Customer name' },\n { name: 'email', description: 'Billing email' },\n { name: 'phone', description: 'Phone number' },\n { name: 'description', description: 'Description / notes' },\n ],\n requiresWorkspace: false,\n handler: async (hctx) => {\n const uuid = hctx.args.uuid as string;\n const data: Record<string, string | undefined> = {};\n if (hctx.args.name) data.name = hctx.args.name as string;\n if (hctx.args.email) data.email = hctx.args.email as string;\n if (hctx.args.phone) data.phone = hctx.args.phone as string;\n if (hctx.args.description) data.description = hctx.args.description as string;\n if (Object.keys(data).length === 0 && !hctx.data) {\n throw new CLIError('Provide --name, --email, --phone, --description, or JSON data');\n }\n const result = await requireAuth(hctx.ctx).apiClient.updateMyCustomer(\n uuid,\n hctx.data ? (hctx.data as Record<string, string>) : data\n );\n outputSingle(result, hctx.ctx);\n },\n },\n {\n path: ['billing', 'invoices'],\n description: 'List invoices for a customer',\n args: [{ name: 'uuid', description: 'Customer UUID', required: true }],\n requiresWorkspace: false,\n handler: async (hctx) => {\n const uuid = hctx.args.uuid as string;\n const result = await requireAuth(hctx.ctx).apiClient.getMyCustomerInvoices(uuid);\n outputData(listResult(result, false), hctx.ctx, INVOICE_COLUMNS as TableColumn<unknown>[]);\n },\n },\n {\n path: ['billing', 'subscriptions'],\n description: 'List subscriptions for a customer',\n args: [{ name: 'uuid', description: 'Customer UUID', required: true }],\n requiresWorkspace: false,\n handler: async (hctx) => {\n const uuid = hctx.args.uuid as string;\n const result = await requireAuth(hctx.ctx).apiClient.getMyCustomerSubscriptions(uuid);\n outputData(listResult(result, false), hctx.ctx);\n },\n },\n];\n\nexport const billingPortalDomain: DomainDef = {\n name: 'billing',\n description: 'Billing portal (customer invoices, subscriptions)',\n commands,\n};\n","/**\n * Concierge API client — direct HTTP calls to the global concierge endpoints.\n *\n * The concierge is account-level (no workspace), so these bypass the ApiClient\n * which is workspace-oriented.\n */\n\nimport type { AuthenticatedContext } from './context';\n\nexport interface ConciergeChat {\n id: number;\n uuid: string;\n chatType: string;\n title: string | null;\n threadId: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ConciergeMessage {\n id: string;\n role: string;\n content: string;\n createdAt: string | null;\n toolCalls: any[] | null;\n toolCallId: string | null;\n}\n\nfunction baseUrl(ctx: AuthenticatedContext): string {\n return `${ctx.envConfig.apiUrl}/api/v2/concierge`;\n}\n\nfunction authHeaders(ctx: AuthenticatedContext): Record<string, string> {\n return {\n Authorization: `Bearer ${ctx.accessToken}`,\n 'Content-Type': 'application/json',\n };\n}\n\nfunction toCamelChat(raw: any): ConciergeChat {\n return {\n id: raw.id,\n uuid: raw.uuid,\n chatType: raw.chat_type,\n title: raw.title,\n threadId: raw.thread_id,\n createdAt: raw.created_at,\n updatedAt: raw.updated_at,\n };\n}\n\nfunction toCamelMessage(raw: any): ConciergeMessage {\n return {\n id: raw.id,\n role: raw.role,\n content: raw.content ?? '',\n createdAt: raw.created_at ?? null,\n toolCalls: raw.tool_calls ?? null,\n toolCallId: raw.tool_call_id ?? null,\n };\n}\n\nexport async function listConciergeChats(ctx: AuthenticatedContext): Promise<ConciergeChat[]> {\n const res = await fetch(`${baseUrl(ctx)}/chats`, { headers: authHeaders(ctx) });\n if (!res.ok) throw new Error(`Failed to list concierge chats: ${res.status}`);\n const data = await res.json();\n return (data as any[]).map(toCamelChat);\n}\n\nexport async function createConciergeChat(\n ctx: AuthenticatedContext,\n title?: string\n): Promise<ConciergeChat> {\n const res = await fetch(`${baseUrl(ctx)}/chats`, {\n method: 'POST',\n headers: authHeaders(ctx),\n body: JSON.stringify({ title: title ?? null }),\n });\n if (!res.ok) throw new Error(`Failed to create concierge chat: ${res.status}`);\n return toCamelChat(await res.json());\n}\n\nexport async function getConciergeChat(\n ctx: AuthenticatedContext,\n chatId: number\n): Promise<ConciergeChat> {\n const res = await fetch(`${baseUrl(ctx)}/chats/${chatId}`, { headers: authHeaders(ctx) });\n if (!res.ok) throw new Error(`Failed to get concierge chat ${chatId}: ${res.status}`);\n return toCamelChat(await res.json());\n}\n\nexport async function getConciergeChatMessages(\n ctx: AuthenticatedContext,\n chatId: number\n): Promise<ConciergeMessage[]> {\n const res = await fetch(`${baseUrl(ctx)}/chats/${chatId}/messages`, {\n headers: authHeaders(ctx),\n });\n if (!res.ok)\n throw new Error(`Failed to get concierge messages for chat ${chatId}: ${res.status}`);\n const data = await res.json();\n return (data as any[]).map(toCamelMessage);\n}\n","import type { DomainDef } from '../lib/types';\nimport { requireAuth } from '../lib/context';\nimport { outputData, COL } from '../lib/output';\nimport { listConciergeChats, getConciergeChatMessages } from '../lib/concierge-api';\n\nconst CHAT_COLUMNS = [\n COL.id(),\n COL.uuid(),\n { header: 'TITLE', getValue: (c: any) => c.title ?? '' },\n { header: 'UPDATED', getValue: (c: any) => c.updatedAt ?? '' },\n];\n\nconst MESSAGE_COLUMNS = [\n { header: 'ID', getValue: (m: any) => m.id },\n { header: 'ROLE', getValue: (m: any) => m.role },\n { header: 'CONTENT', getValue: (m: any) => (m.content || '').slice(0, 120) },\n];\n\nexport const conciergeDomain: DomainDef = {\n name: 'concierge',\n description: 'Concierge chat management',\n commands: [\n {\n path: ['concierge', 'list'],\n description: 'List concierge chats',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const auth = requireAuth(ctx);\n const chats = await listConciergeChats(auth);\n outputData(chats, auth, CHAT_COLUMNS);\n },\n },\n {\n path: ['concierge', 'messages'],\n description: 'Show messages for a concierge chat',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, args }) => {\n const auth = requireAuth(ctx);\n const chatId = Number(args.id);\n if (isNaN(chatId)) throw new Error('--id must be a number');\n const messages = await getConciergeChatMessages(auth, chatId);\n outputData(messages, auth, MESSAGE_COLUMNS);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { CLIError } from '../lib/errors';\nimport { outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS = [COL.id(), COL.name(), COL.description(), COL.enabled()];\n\nconst TOOL_COLUMNS = [COL.id(), COL.name(), COL.description()];\n\nexport const customToolkitsDomain: DomainDef = {\n name: 'custom-toolkits',\n description: 'Manage custom toolkits and their tools',\n commands: [\n ...crudCommands({\n prefix: ['custom-toolkits'],\n entityName: 'custom toolkit',\n listMethod: 'getCustomToolkits',\n getMethod: 'getCustomToolkit',\n createMethod: 'createCustomToolkit',\n updateMethod: 'updateCustomToolkit',\n deleteMethod: 'deleteCustomToolkit',\n columns: COLUMNS,\n }),\n {\n path: ['custom-toolkits', 'enable'],\n description: 'Enable a custom toolkit',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Custom toolkit ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.enableCustomToolkit(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['custom-toolkits', 'disable'],\n description: 'Disable a custom toolkit',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Custom toolkit ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.disableCustomToolkit(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Tools — nested resource requiring toolkitId\n {\n path: ['custom-toolkits', 'tools', 'create'],\n description: 'Create a custom tool in a toolkit',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'toolkit-id', description: 'Custom toolkit ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const toolkitId = requireNumber(args, 'toolkit-id');\n const result = await requireAuth(ctx).apiClient.createCustomTool(\n workspace,\n toolkitId,\n data as any\n );\n outputSingle(result, ctx, TOOL_COLUMNS);\n },\n },\n {\n path: ['custom-toolkits', 'tools', 'update'],\n description: 'Update a custom tool',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'toolkit-id', description: 'Custom toolkit ID', required: true },\n { name: 'id', description: 'Tool ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const toolkitId = requireNumber(args, 'toolkit-id');\n const toolId = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.updateCustomTool(\n workspace,\n toolkitId,\n toolId,\n data as any\n );\n outputSingle(result, ctx, TOOL_COLUMNS);\n },\n },\n {\n path: ['custom-toolkits', 'tools', 'delete'],\n description: 'Delete a custom tool',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'toolkit-id', description: 'Custom toolkit ID', required: true },\n { name: 'id', description: 'Tool ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const toolkitId = requireNumber(args, 'toolkit-id');\n const toolId = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.deleteCustomTool(workspace, toolkitId, toolId);\n process.stdout.write(`Deleted custom tool ${toolId}\\n`);\n },\n },\n ],\n};\n","import { type DomainDef, requireString } from '../lib/types';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS = [\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.name(),\n COL.description(),\n];\n\nexport const featuresDomain: DomainDef = {\n name: 'features',\n description: 'List available features',\n commands: [\n {\n path: ['features', 'list'],\n description: 'List all available features',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getFeatureRegistry();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['features', 'get'],\n description: 'Get a feature by slug',\n requiresWorkspace: false,\n args: [{ name: 'slug', description: 'Feature slug', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.getFeatureBySlug(\n requireString(args, 'slug')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['features', 'workspace'],\n description: 'List available features for a workspace',\n requiresWorkspace: true,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getAvailableWorkspaceFeatures();\n outputData(result, ctx, COLUMNS);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'EMAIL', getValue: (item: any) => item.email_address ?? '' },\n COL.status(),\n];\n\nconst EMAIL_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'SUBJECT', getValue: (item: any) => item.subject ?? '' },\n { header: 'FROM', getValue: (item: any) => item.from_address ?? '' },\n { header: 'DATE', getValue: (item: any) => item.received_at ?? '' },\n { header: 'READ', getValue: (item: any) => String(item.is_read ?? '') },\n];\n\nexport const inboxesDomain: DomainDef = {\n name: 'inboxes',\n description: 'Manage email inboxes',\n commands: [\n ...crudCommands({\n prefix: ['inboxes'],\n entityName: 'inbox',\n listMethod: 'getInboxes',\n getMethod: 'getInbox',\n createMethod: 'createInbox',\n updateMethod: 'updateInbox',\n deleteMethod: 'deleteInbox',\n columns: COLUMNS,\n }),\n {\n path: ['inboxes', 'emails', 'list'],\n description: 'List emails in an inbox',\n requiresWorkspace: true,\n args: [{ name: 'inbox-id', description: 'Inbox ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getInboxEmails(\n workspace,\n requireNumber(args, 'inbox-id')\n );\n outputData(result, ctx, EMAIL_COLUMNS);\n },\n },\n {\n path: ['inboxes', 'emails', 'get'],\n description: 'Get a specific email',\n requiresWorkspace: true,\n args: [\n { name: 'inbox-id', description: 'Inbox ID', required: true },\n { name: 'id', description: 'Email ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getInboxEmail(\n workspace,\n requireNumber(args, 'inbox-id'),\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, EMAIL_COLUMNS);\n },\n },\n {\n path: ['inboxes', 'emails', 'threads'],\n description: 'List email threads in an inbox',\n requiresWorkspace: true,\n args: [{ name: 'inbox-id', description: 'Inbox ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getInboxThreads(\n workspace,\n requireNumber(args, 'inbox-id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['inboxes', 'emails', 'mark-read'],\n description: 'Mark an email as read',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'inbox-id', description: 'Inbox ID', required: true },\n { name: 'id', description: 'Email ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.markEmailAsRead(\n workspace,\n requireNumber(args, 'inbox-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write('Email marked as read\\n');\n },\n },\n {\n path: ['inboxes', 'emails', 'mark-unread'],\n description: 'Mark an email as unread',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'inbox-id', description: 'Inbox ID', required: true },\n { name: 'id', description: 'Email ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.markEmailAsUnread(\n workspace,\n requireNumber(args, 'inbox-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write('Email marked as unread\\n');\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS = [\n COL.id(),\n COL.name(),\n { header: 'URL', getValue: (item: any) => item.url ?? '' },\n COL.enabled(),\n];\n\nexport const mcpServersDomain: DomainDef = {\n name: 'mcp-servers',\n description: 'Manage MCP servers',\n commands: [\n ...crudCommands({\n prefix: ['mcp-servers'],\n entityName: 'MCP server',\n listMethod: 'getMcpServers',\n getMethod: 'getMcpServer',\n createMethod: 'createMcpServer',\n updateMethod: 'updateMcpServer',\n deleteMethod: 'deleteMcpServer',\n columns: COLUMNS,\n }),\n {\n path: ['mcp-servers', 'enable'],\n description: 'Enable an MCP server',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'MCP server ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.enableMcpServer(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['mcp-servers', 'disable'],\n description: 'Disable an MCP server',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'MCP server ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.disableMcpServer(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['mcp-servers', 'tools', 'list'],\n description: 'List tools for an MCP server',\n requiresWorkspace: true,\n args: [{ name: 'mcp-server-id', description: 'MCP server ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getMcpServerTools(\n workspace,\n requireNumber(args, 'mcp-server-id')\n );\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber, requireString } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport type { MemoryType } from '@gravity-rail/client';\nimport { outputData } from '../lib/output';\nimport { listResult } from '../lib/pagination';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n { header: 'KEY', getValue: (item: any) => item.key ?? '' },\n { header: 'TYPE', getValue: (item: any) => item.type ?? 'basic' },\n { header: 'DESCRIPTION', getValue: (item: any) => truncate(item.description ?? '', 60) },\n { header: 'PRIORITY', getValue: (item: any) => item.priority ?? 0 },\n { header: 'UPDATED', getValue: (item: any) => item.updatedAt ?? item.createdAt ?? '' },\n];\n\nfunction truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max - 1) + '…' : s;\n}\n\nexport const memberMemoriesDomain: DomainDef = {\n name: 'member-memories',\n description: 'Manage member persistent memories',\n commands: [\n {\n path: ['member-memories', 'list'],\n description: 'List memories for a member',\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n {\n name: 'type',\n description:\n 'Memory type filter (basic, preferences, semantic, summaries, episodic, all)',\n },\n { name: 'query', description: 'Semantic search query (for AgentCore memory types)' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const memberId = requireNumber(args, 'member-id');\n const type = args.type as MemoryType | 'all' | undefined;\n const query = args.query as string | undefined;\n const result = await requireAuth(ctx).apiClient.getMemberMemories(workspace, memberId, {\n type,\n query,\n });\n outputData(listResult(result, false), ctx, COLUMNS);\n },\n },\n {\n path: ['member-memories', 'delete'],\n description: 'Delete a memory for a member',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'key', description: 'Memory key', required: true },\n {\n name: 'type',\n description: 'Memory type (basic, preferences, semantic, summaries, episodic)',\n },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const memberId = requireNumber(args, 'member-id');\n const key = requireString(args, 'key');\n const type = args.type as MemoryType | undefined;\n await requireAuth(ctx).apiClient.deleteMemberMemory(\n workspace,\n memberId,\n key,\n type ? { type } : undefined\n );\n process.stdout.write(`Deleted memory ${key}\\n`);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { COL } from '../lib/output';\n\nconst COLUMNS = [\n COL.id(),\n COL.name(),\n COL.status(),\n { header: 'DUE DATE', getValue: (item: any) => item.due_date ?? '' },\n];\n\nexport const milestonesDomain: DomainDef = {\n name: 'milestones',\n description: 'Manage milestones',\n commands: [\n ...crudCommands({\n prefix: ['milestones'],\n entityName: 'milestone',\n listMethod: 'getMilestones',\n getMethod: 'getMilestone',\n createMethod: 'createMilestone',\n updateMethod: 'updateMilestone',\n deleteMethod: 'deleteMilestone',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { COL } from '../lib/output';\n\nconst COLUMNS = [\n COL.id(),\n COL.name(),\n { header: 'TYPE', getValue: (item: any) => item.noticeType ?? '' },\n COL.enabled(),\n];\n\nexport const notificationRulesDomain: DomainDef = {\n name: 'notification-rules',\n description: 'Manage notification rules',\n commands: [\n ...crudCommands({\n prefix: ['notification-rules'],\n entityName: 'notification rule',\n listMethod: 'getNotificationRules',\n createMethod: 'createNotificationRule',\n updateMethod: 'updateNotificationRule',\n deleteMethod: 'deleteNotificationRule',\n columns: COLUMNS,\n }),\n ],\n};\n","import { type DomainDef, requireString } from '../lib/types';\nimport { outputSingle, outputData } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nexport const oauthDomain: DomainDef = {\n name: 'oauth',\n description: 'Manage OAuth connections',\n commands: [\n {\n path: ['oauth', 'status'],\n description: 'Get OAuth connection status for a provider',\n requiresWorkspace: false,\n args: [{ name: 'provider', description: 'OAuth provider name', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.getOAuthConnectionStatus(\n requireString(args, 'provider') as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['oauth', 'auth-url'],\n description: 'Get OAuth authorization URL for a provider',\n requiresWorkspace: false,\n args: [{ name: 'provider', description: 'OAuth provider name', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.getOAuthAuthorizationUrl(\n requireString(args, 'provider') as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['oauth', 'disconnect'],\n description: 'Disconnect an OAuth provider',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'provider', description: 'OAuth provider name', required: true }],\n handler: async ({ ctx, args }) => {\n const provider = requireString(args, 'provider');\n await requireAuth(ctx).apiClient.disconnectOAuthProvider(provider as any);\n process.stdout.write(`Disconnected OAuth provider ${provider}\\n`);\n },\n },\n {\n path: ['oauth', 'scopes'],\n description: 'List available OAuth scopes',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getAvailableScopes();\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS = [COL.id(), COL.name(), COL.description()];\n\nexport const operatorGroupsDomain: DomainDef = {\n name: 'operator-groups',\n description: 'Manage operator groups',\n commands: [\n ...crudCommands({\n prefix: ['operator-groups'],\n entityName: 'operator group',\n listMethod: 'getOperatorGroups',\n getMethod: 'getOperatorGroup',\n createMethod: 'createOperatorGroup',\n updateMethod: 'updateOperatorGroup',\n deleteMethod: 'deleteOperatorGroup',\n columns: COLUMNS,\n }),\n {\n path: ['operator-groups', 'add-member'],\n description: 'Add a member to an operator group',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'id', description: 'Operator group ID', required: true },\n { name: 'member-id', description: 'Member ID to add', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.addGroupMember(\n workspace,\n requireNumber(args, 'id'),\n { member_id: requireNumber(args, 'member-id') } as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['operator-groups', 'remove-member'],\n description: 'Remove a member from an operator group',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'id', description: 'Operator group ID', required: true },\n { name: 'member-id', description: 'Member ID to remove', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.removeGroupMember(\n workspace,\n requireNumber(args, 'id'),\n requireNumber(args, 'member-id')\n );\n process.stdout.write('Member removed from group\\n');\n },\n },\n {\n path: ['operator-groups', 'live'],\n description: 'List live operators',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getLiveOperators(workspace);\n outputData(result, ctx);\n },\n },\n {\n path: ['operator-groups', 'presence'],\n description: 'Get presence status',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getPresenceStatus(workspace);\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import type { OrgDomain } from '@gravity-rail/sdk';\nimport { requireAuth, type AuthenticatedContext } from '../lib/context';\nimport { CLIError } from '../lib/errors';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle } from '../lib/output';\nimport type { CommandDef, DomainDef, ParsedArgs } from '../lib/types';\n\ntype OrgMembership = Awaited<\n ReturnType<AuthenticatedContext['apiClient']['getMyOrganizations']>\n>[number];\n\nconst ORG_COLUMNS: TableColumn<OrgMembership>[] = [\n { header: 'ID', getValue: (item) => String(item.organizationId ?? '') },\n { header: 'NAME', getValue: (item) => item.organizationName || '' },\n { header: 'ROLE', getValue: (item) => item.role || '' },\n];\n\nconst ORG_DOMAIN_COLUMNS: TableColumn<OrgDomain>[] = [\n { header: 'UUID', getValue: (item) => item.uuid ?? '' },\n { header: 'DOMAIN', getValue: (item) => item.domain ?? '' },\n { header: 'OWNERSHIP', getValue: (item) => item.ownershipStatus ?? '' },\n { header: 'EMAIL', getValue: (item) => item.emailStatus ?? '-' },\n { header: 'SITE', getValue: (item) => item.siteStatus ?? '-' },\n { header: 'TXT HOST', getValue: (item) => item.ownershipDnsRecord?.host ?? '' },\n {\n header: 'TXT VALUE',\n getValue: (item) => item.ownershipDnsRecord?.value ?? '',\n maxWidth: 80,\n },\n];\n\nfunction requireOrgId(args: ParsedArgs): string {\n const val = args['org-uuid'] ?? args.org;\n if (typeof val !== 'string' || !val) {\n throw new CLIError('Missing required argument: --org-uuid');\n }\n return val;\n}\n\nfunction requireDomainUuid(args: ParsedArgs): string {\n const val = args['domain-uuid'] ?? args.uuid;\n if (typeof val !== 'string' || !val) {\n throw new CLIError('Missing required argument: --domain-uuid');\n }\n return val;\n}\n\nfunction requireDomain(args: ParsedArgs): string {\n const val = args.domain;\n if (typeof val !== 'string' || !val) {\n throw new CLIError('Missing required argument: --domain');\n }\n return val;\n}\n\nconst ORG_UUID_ARG = {\n name: 'org-uuid',\n aliases: ['org'],\n description: 'Organization UUID or ID',\n required: true,\n};\n\nconst DOMAIN_UUID_ARG = {\n name: 'domain-uuid',\n aliases: ['domain-id'],\n description: 'OrgDomain UUID',\n required: true,\n};\n\nfunction pluralize(count: number, singular: string, plural = `${singular}s`): string {\n return count === 1 ? singular : plural;\n}\n\nfunction emailVerifyCommand(path: string[], description: string): CommandDef {\n return {\n path,\n description,\n mutates: true,\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: [\n `yarn gr ${path.join(' ')} --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --allow-write`,\n ],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.verifyOrgDomainEmail(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n };\n}\n\nfunction siteVerifyCommand(path: string[], description: string): CommandDef {\n return {\n path,\n description,\n mutates: true,\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: [\n `yarn gr ${path.join(' ')} --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --allow-write`,\n ],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.verifyOrgDomainSite(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n };\n}\n\nfunction registerDomainCommand(path: string[]): CommandDef {\n return {\n path,\n description: 'Register an organization domain and return ownership TXT instructions',\n mutates: true,\n requiresWorkspace: false,\n args: [\n ORG_UUID_ARG,\n { name: 'domain', description: 'Domain to register, e.g. example.com', required: true },\n ],\n examples: [\n `yarn gr ${path.join(' ')} --org-uuid $ORG_UUID --domain example.com --allow-write`,\n ],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.registerOrgDomain(\n requireOrgId(hctx.args),\n requireDomain(hctx.args)\n );\n outputSingle(result, hctx.ctx, ORG_DOMAIN_COLUMNS);\n },\n };\n}\n\nconst domainCommands: CommandDef[] = [\n {\n path: ['org', 'domains', 'list'],\n description: 'List domains registered to an organization',\n requiresWorkspace: false,\n args: [ORG_UUID_ARG],\n examples: ['yarn gr org domains list --org-uuid $ORG_UUID'],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.listOrgDomains(\n requireOrgId(hctx.args)\n );\n outputData(result, hctx.ctx, ORG_DOMAIN_COLUMNS);\n },\n },\n {\n path: ['org', 'domains', 'get'],\n description: 'Get a registered organization domain',\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: ['yarn gr org domains get --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID'],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.getOrgDomain(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx, ORG_DOMAIN_COLUMNS);\n },\n },\n registerDomainCommand(['org', 'domains', 'register']),\n registerDomainCommand(['org', 'domains', 'create']),\n {\n path: ['org', 'domains', 'verify-ownership'],\n description: 'Verify domain ownership by checking the _gravity-verify TXT record',\n mutates: true,\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: [\n 'yarn gr org domains verify-ownership --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --allow-write',\n ],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.verifyOrgDomainOwnership(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n },\n {\n path: ['org', 'domains', 'delete'],\n description: 'Delete a registered organization domain',\n mutates: true,\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: [\n 'yarn gr org domains delete --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --allow-write',\n ],\n handler: async (hctx) => {\n const domainUuid = requireDomainUuid(hctx.args);\n await requireAuth(hctx.ctx).apiClient.deleteOrgDomain(requireOrgId(hctx.args), domainUuid);\n process.stdout.write(`Deleted org domain ${domainUuid}\\n`);\n },\n },\n {\n path: ['org', 'domains', 'email', 'enable'],\n description: 'Enable email DNS records on a verified organization domain',\n mutates: true,\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: [\n 'yarn gr org domains email enable --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --allow-write',\n ],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.enableOrgDomainEmail(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n },\n {\n path: ['org', 'domains', 'email', 'get'],\n description: 'Get email DNS setup and status for an organization domain',\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: ['yarn gr org domains email get --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID'],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.getOrgDomainEmail(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n },\n emailVerifyCommand(\n ['org', 'domains', 'email', 'verify'],\n 'Verify email DNS records, including MX'\n ),\n emailVerifyCommand(\n ['org', 'domains', 'email', 'verify-mx'],\n 'Verify email DNS records, including MX'\n ),\n {\n path: ['org', 'domains', 'email', 'disable'],\n description: 'Disable email on an organization domain',\n mutates: true,\n requiresWorkspace: false,\n args: [\n ORG_UUID_ARG,\n DOMAIN_UUID_ARG,\n {\n name: 'confirm',\n description: 'Confirm removal of inbox routing that depends on this domain',\n isFlag: true,\n },\n ],\n examples: [\n 'yarn gr org domains email disable --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --confirm --allow-write',\n ],\n handler: async (hctx) => {\n const domainUuid = requireDomainUuid(hctx.args);\n const result = await requireAuth(hctx.ctx).apiClient.disableOrgDomainEmail(\n requireOrgId(hctx.args),\n domainUuid,\n hctx.args.confirm === true\n );\n if (!result.ok) {\n const { inboxCount } = result.impact;\n throw new CLIError(\n `Email is still used by ${inboxCount} ${pluralize(\n inboxCount,\n 'inbox',\n 'inboxes'\n )}. Re-run with --confirm to disable it anyway.`\n );\n }\n process.stdout.write(`Disabled email for org domain ${domainUuid}\\n`);\n },\n },\n {\n path: ['org', 'domains', 'site', 'enable'],\n description: 'Enable custom site CNAME verification on a verified organization domain',\n mutates: true,\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: [\n 'yarn gr org domains site enable --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --allow-write',\n ],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.enableOrgDomainSite(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n },\n {\n path: ['org', 'domains', 'site', 'get'],\n description: 'Get custom site CNAME setup and status for an organization domain',\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: ['yarn gr org domains site get --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID'],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.getOrgDomainSite(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n },\n siteVerifyCommand(\n ['org', 'domains', 'site', 'verify'],\n 'Verify the site CNAME points at Gravity Rail'\n ),\n siteVerifyCommand(\n ['org', 'domains', 'site', 'verify-cname'],\n 'Verify the site CNAME points at Gravity Rail'\n ),\n {\n path: ['org', 'domains', 'site', 'disable'],\n description: 'Disable custom site routing on an organization domain',\n mutates: true,\n requiresWorkspace: false,\n args: [\n ORG_UUID_ARG,\n DOMAIN_UUID_ARG,\n {\n name: 'confirm',\n description: 'Confirm removal of site mappings that depend on this domain',\n isFlag: true,\n },\n ],\n examples: [\n 'yarn gr org domains site disable --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --confirm --allow-write',\n ],\n handler: async (hctx) => {\n const domainUuid = requireDomainUuid(hctx.args);\n const result = await requireAuth(hctx.ctx).apiClient.disableOrgDomainSite(\n requireOrgId(hctx.args),\n domainUuid,\n hctx.args.confirm === true\n );\n if (!result.ok) {\n const { siteCount } = result.impact;\n throw new CLIError(\n `Site routing is still used by ${siteCount} ${pluralize(\n siteCount,\n 'site'\n )}. Re-run with --confirm to disable it anyway.`\n );\n }\n process.stdout.write(`Disabled site routing for org domain ${domainUuid}\\n`);\n },\n },\n];\n\nexport const orgDomain: DomainDef = {\n name: 'org',\n description: 'Organization membership and domains',\n commands: [\n {\n path: ['org', 'list'],\n description: 'List my organizations',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getMyOrganizations();\n outputData(result, ctx, ORG_COLUMNS);\n },\n },\n ...domainCommands,\n ],\n};\n","/**\n * Organization-scoped phone number management CLI commands.\n *\n * Covers the /api/v2/o/{org_uuid}/phone-numbers/ routes:\n * - list, search, purchase, assign, reassign, release, delete\n */\nimport { OrgApi } from '@gravity-rail/sdk';\nimport { requireAuth } from '../lib/context';\nimport { CLIError } from '../lib/errors';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle } from '../lib/output';\nimport type { CommandDef, CommandHandlerContext, DomainDef } from '../lib/types';\n\nfunction getOrgApi(hctx: CommandHandlerContext): OrgApi {\n const ctx = requireAuth(hctx.ctx);\n return new OrgApi(ctx.accessToken, ctx.envConfig.apiUrl);\n}\n\ntype AnyRecord = Record<string, any>;\n\nconst PROVIDER_PHONE_COLUMNS: TableColumn<AnyRecord>[] = [\n { header: 'ID', getValue: (p) => String(p.id ?? '') },\n { header: 'UUID', getValue: (p) => (p.uuid ?? '').slice(0, 8) },\n { header: 'Phone', getValue: (p) => p.phoneNumber ?? '' },\n { header: 'Type', getValue: (p) => p.phoneNumberType ?? '' },\n { header: 'Assigned', getValue: (p) => String(p.isAssigned ?? false) },\n { header: 'Workspace', getValue: (p) => p.workspaceName ?? '-' },\n];\n\nconst AVAILABLE_PHONE_COLUMNS: TableColumn<AnyRecord>[] = [\n { header: 'Phone', getValue: (p) => p.phoneNumber ?? '' },\n { header: 'Name', getValue: (p) => p.friendlyName ?? '' },\n { header: 'Locality', getValue: (p) => p.locality ?? '' },\n { header: 'Region', getValue: (p) => p.region ?? '' },\n { header: 'Type', getValue: (p) => p.phoneNumberType ?? '' },\n];\n\nfunction requireOrgUuid(args: Record<string, any>): string {\n const val = args['org-uuid'] ?? args['org'];\n if (typeof val !== 'string' || !val) {\n throw new CLIError('Missing required argument: --org-uuid');\n }\n return val;\n}\n\nconst commands: CommandDef[] = [\n {\n path: ['org', 'phone-numbers', 'list'],\n description: 'List all phone numbers owned by an organization',\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n ],\n requiresWorkspace: false,\n columns: PROVIDER_PHONE_COLUMNS as TableColumn<unknown>[],\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const result = await getOrgApi(hctx).listPhoneNumbers(orgUuid);\n outputData(result, hctx.ctx, PROVIDER_PHONE_COLUMNS);\n },\n },\n {\n path: ['org', 'phone-numbers', 'search'],\n description: 'Search for available phone numbers to purchase',\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n { name: 'number-type', description: 'Number type: local or toll_free', default: 'local' },\n { name: 'area-code', description: 'Area code filter' },\n { name: 'contains', description: 'Phone number pattern to match' },\n { name: 'limit', description: 'Maximum results (default: 20)' },\n ],\n requiresWorkspace: false,\n columns: AVAILABLE_PHONE_COLUMNS as TableColumn<unknown>[],\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const result = await getOrgApi(hctx).searchPhoneNumbers(orgUuid, {\n numberType: (hctx.args['number-type'] as 'local' | 'toll_free') ?? 'local',\n areaCode: hctx.args['area-code'] as string | undefined,\n contains: hctx.args.contains as string | undefined,\n limit: hctx.args.limit ? Number(hctx.args.limit) : undefined,\n });\n outputData(result, hctx.ctx, AVAILABLE_PHONE_COLUMNS);\n },\n },\n {\n path: ['org', 'phone-numbers', 'purchase'],\n description: 'Purchase a phone number from Twilio for this org',\n mutates: true,\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n { name: 'phone-number', description: 'E.164 phone number to purchase', required: true },\n { name: 'number-type', description: 'Number type: local or toll_free', default: 'local' },\n ],\n requiresWorkspace: false,\n columns: PROVIDER_PHONE_COLUMNS as TableColumn<unknown>[],\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const phoneNumber = hctx.args['phone-number'] as string;\n if (!phoneNumber) throw new CLIError('Missing required argument: --phone-number');\n const numberType = (hctx.args['number-type'] as 'local' | 'toll_free') ?? 'local';\n const result = await getOrgApi(hctx).purchasePhoneNumber(orgUuid, phoneNumber, numberType);\n outputSingle(result, hctx.ctx, PROVIDER_PHONE_COLUMNS);\n },\n },\n {\n path: ['org', 'phone-numbers', 'assign'],\n description: 'Assign an org phone number to a workspace',\n mutates: true,\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n { name: 'provider-phone-uuid', description: 'Provider phone UUID', required: true },\n { name: 'workspace-uuid', description: 'Target workspace UUID', required: true },\n ],\n requiresWorkspace: false,\n columns: PROVIDER_PHONE_COLUMNS as TableColumn<unknown>[],\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const providerPhoneUuid = hctx.args['provider-phone-uuid'] as string;\n const workspaceUuid = hctx.args['workspace-uuid'] as string;\n if (!providerPhoneUuid)\n throw new CLIError('Missing required argument: --provider-phone-uuid');\n if (!workspaceUuid) throw new CLIError('Missing required argument: --workspace-uuid');\n const result = await getOrgApi(hctx).assignPhoneToWorkspace(\n orgUuid,\n providerPhoneUuid,\n workspaceUuid\n );\n outputSingle(result, hctx.ctx, PROVIDER_PHONE_COLUMNS);\n },\n },\n {\n path: ['org', 'phone-numbers', 'reassign'],\n description: 'Reassign a phone number to a different workspace',\n mutates: true,\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n { name: 'provider-phone-uuid', description: 'Provider phone UUID', required: true },\n { name: 'new-workspace-uuid', description: 'New workspace UUID', required: true },\n ],\n requiresWorkspace: false,\n columns: PROVIDER_PHONE_COLUMNS as TableColumn<unknown>[],\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const providerPhoneUuid = hctx.args['provider-phone-uuid'] as string;\n const newWorkspaceUuid = hctx.args['new-workspace-uuid'] as string;\n if (!providerPhoneUuid)\n throw new CLIError('Missing required argument: --provider-phone-uuid');\n if (!newWorkspaceUuid)\n throw new CLIError('Missing required argument: --new-workspace-uuid');\n const result = await getOrgApi(hctx).reassignPhone(\n orgUuid,\n providerPhoneUuid,\n newWorkspaceUuid\n );\n outputSingle(result, hctx.ctx, PROVIDER_PHONE_COLUMNS);\n },\n },\n {\n path: ['org', 'phone-numbers', 'release'],\n description: 'Release a phone number from its current workspace',\n mutates: true,\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n { name: 'provider-phone-uuid', description: 'Provider phone UUID', required: true },\n ],\n requiresWorkspace: false,\n columns: PROVIDER_PHONE_COLUMNS as TableColumn<unknown>[],\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const providerPhoneUuid = hctx.args['provider-phone-uuid'] as string;\n if (!providerPhoneUuid)\n throw new CLIError('Missing required argument: --provider-phone-uuid');\n const result = await getOrgApi(hctx).releasePhone(orgUuid, providerPhoneUuid);\n outputSingle(result, hctx.ctx, PROVIDER_PHONE_COLUMNS);\n },\n },\n {\n path: ['org', 'phone-numbers', 'delete'],\n description: 'Delete a phone number from the org (releases from Twilio)',\n mutates: true,\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n { name: 'provider-phone-uuid', description: 'Provider phone UUID', required: true },\n ],\n requiresWorkspace: false,\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const providerPhoneUuid = hctx.args['provider-phone-uuid'] as string;\n if (!providerPhoneUuid)\n throw new CLIError('Missing required argument: --provider-phone-uuid');\n await getOrgApi(hctx).deletePhoneNumber(orgUuid, providerPhoneUuid);\n console.log('Phone number deleted successfully');\n },\n },\n];\n\nexport const orgPhoneNumbersDomain: DomainDef = {\n name: 'org',\n description: 'Organization management',\n commands,\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'NUMBER', getValue: (item: any) => item.phone_number ?? '' },\n { header: 'LABEL', getValue: (item: any) => item.label ?? '' },\n COL.status(),\n];\n\nexport const phoneNumbersDomain: DomainDef = {\n name: 'phone-numbers',\n description: 'Manage phone numbers',\n commands: [\n ...crudCommands({\n prefix: ['phone-numbers'],\n entityName: 'phone number',\n listMethod: 'getPhoneNumbers',\n getMethod: 'getPhoneNumber',\n createMethod: 'createPhoneNumber',\n updateMethod: 'updatePhoneNumber',\n archiveMethod: 'archivePhoneNumber',\n columns: COLUMNS,\n }),\n {\n path: ['phone-numbers', 'available'],\n description: 'List available phone numbers for purchase',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getAvailablePhoneNumbers(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['phone-numbers', 'request'],\n description: 'Request a phone number',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.requestPhoneNumber(\n workspace,\n data as any\n );\n outputData([result], ctx, COLUMNS);\n },\n },\n {\n path: ['phone-numbers', 'calls', 'list'],\n description: 'List calls for a phone number',\n requiresWorkspace: true,\n args: [\n { name: 'phone-number-id', description: 'Phone number ID', required: true },\n { name: 'page', description: 'Page number' },\n { name: 'page-size', description: 'Page size' },\n { name: 'status', description: 'Filter by status' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const status = args.status as string | undefined;\n const result = await requireAuth(ctx).apiClient.getPhoneNumberCalls(\n workspace,\n requireNumber(args, 'phone-number-id'),\n args.page ? Number(args.page) : undefined,\n args['page-size'] ? Number(args['page-size']) : undefined,\n status ? { status } : undefined\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['phone-numbers', 'messages', 'list'],\n description: 'List messages for a phone number',\n requiresWorkspace: true,\n args: [\n { name: 'phone-number-id', description: 'Phone number ID', required: true },\n { name: 'page', description: 'Page number' },\n { name: 'page-size', description: 'Page size' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getPhoneNumberMessages(\n workspace,\n requireNumber(args, 'phone-number-id'),\n args.page ? Number(args.page) : undefined,\n args['page-size'] ? Number(args['page-size']) : undefined\n );\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireString, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'WORD', getValue: (item: any) => item.word ?? '' },\n { header: 'PRONUNCIATION', getValue: (item: any) => item.pronunciation ?? '' },\n { header: 'TYPE', getValue: (item: any) => item.type ?? '' },\n];\n\nexport const pronunciationsDomain: DomainDef = {\n name: 'pronunciations',\n description: 'Manage pronunciation entries',\n commands: [\n {\n path: ['pronunciations', 'list'],\n description: 'List pronunciation entries',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getPronunciationEntries(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['pronunciations', 'create'],\n description: 'Create a pronunciation entry',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.createPronunciationEntry(\n workspace,\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['pronunciations', 'update'],\n description: 'Update a pronunciation entry',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Pronunciation entry ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updatePronunciationEntry(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['pronunciations', 'delete'],\n description: 'Delete a pronunciation entry',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Pronunciation entry ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.deletePronunciationEntry(workspace, id);\n process.stdout.write(`Deleted pronunciation entry ${id}\\n`);\n },\n },\n {\n path: ['pronunciations', 'my-list'],\n description: 'List my personal pronunciations',\n requiresWorkspace: true,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getMyPronunciations();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['pronunciations', 'my-create'],\n description: 'Create a personal pronunciation',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.createMyPronunciation(data as any);\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['pronunciations', 'suggest'],\n description: 'Get pronunciation suggestions for a word',\n requiresWorkspace: true,\n args: [{ name: 'word', description: 'Word to get suggestions for', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.suggestPronunciations(\n requireString(args, 'word')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['pronunciations', 'voices'],\n description: 'Get recommended voices',\n requiresWorkspace: true,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getRecommendedVoices();\n outputData(result, ctx);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport { outputSingle } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nexport const reportsDomain: DomainDef = {\n name: 'reports',\n description: 'View usage reports',\n commands: [\n {\n path: ['reports', 'ai-usage'],\n description: 'Get AI usage report',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getAIUsageReport(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['reports', 'sms-usage'],\n description: 'Get SMS usage report',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getSMSUsageReport(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['reports', 'phone-usage'],\n description: 'Get phone usage report',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getPhoneUsageReport(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['reports', 'voice-usage'],\n description: 'Get voice usage report',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getVoiceUsageReport(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['reports', 'member-usage'],\n description: 'Get usage for a specific member',\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getMemberUsage(\n workspace,\n requireNumber(args, 'member-id')\n );\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.status(),\n { header: 'PLAN', getValue: (item: any) => item.plan_name ?? item.plan ?? '' },\n COL.created(),\n];\n\nexport const subscriptionsDomain: DomainDef = {\n name: 'subscriptions',\n description: 'Manage subscriptions',\n commands: [\n {\n path: ['subscriptions', 'list'],\n description: 'List all subscriptions',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getSubscriptions();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['subscriptions', 'workspace'],\n description: 'List subscriptions for a workspace',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getWorkspaceSubscriptions(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['subscriptions', 'cancel'],\n description: 'Cancel a subscription',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Subscription ID', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.cancelSubscription(\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['subscriptions', 'reactivate'],\n description: 'Reactivate a cancelled subscription',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Subscription ID', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.reactivateSubscription(\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['subscriptions', 'update'],\n description: 'Update a subscription',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Subscription ID', required: true }],\n handler: async ({ ctx, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateSubscription(\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport { outputSingle } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nexport const promptsDomain: DomainDef = {\n name: 'prompts',\n description: 'Inspect and debug LLM prompts',\n commands: [\n {\n path: ['prompts', 'inspect'],\n description: 'Show the full composed prompt for a task or chat, broken into layers',\n requiresWorkspace: true,\n args: [\n { name: 'task-id', description: 'Task ID to inspect (static mode)' },\n { name: 'chat-id', description: 'Chat ID to inspect (live mode)' },\n { name: 'channel', description: 'Channel to simulate (static mode only)' },\n { name: 'turn', description: 'Turn number (chat mode only, default 1)' },\n ],\n examples: [\n 'gr prompts inspect --task-id 42',\n 'gr prompts inspect --task-id 42 --channel phone-voice',\n 'gr prompts inspect --chat-id 789',\n 'gr prompts inspect --chat-id 789 --turn 3',\n ],\n handler: async ({ ctx, workspace, args }) => {\n const taskId = args['task-id'] !== undefined ? requireNumber(args, 'task-id') : undefined;\n const chatId = args['chat-id'] !== undefined ? requireNumber(args, 'chat-id') : undefined;\n\n if (taskId === undefined && chatId === undefined) {\n throw new Error('Provide --task-id or --chat-id');\n }\n if (taskId !== undefined && chatId !== undefined) {\n throw new Error('Provide --task-id or --chat-id, not both');\n }\n\n const channel = (args.channel as string) || undefined;\n const turn = args.turn !== undefined ? requireNumber(args, 'turn') : undefined;\n\n const result = await requireAuth(ctx).apiClient.inspectPrompt(workspace, {\n ...(taskId !== undefined ? { taskId } : { chatId: chatId! }),\n ...(channel ? { channel } : {}),\n ...(turn !== undefined ? { turn } : {}),\n });\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import type { DomainDef, ParsedArgs } from '../lib/types';\nimport { requireString } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { COL, outputData, outputSingle } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst SUPPORT_COLUMNS: TableColumn<unknown>[] = [\n COL.uuid(),\n { header: 'STATUS', getValue: (item: any) => item.status ?? '' },\n { header: 'TYPE', getValue: (item: any) => item.supportRequestType ?? '' },\n { header: 'SEVERITY', getValue: (item: any) => item.severity ?? '' },\n { header: 'SOURCE', getValue: (item: any) => item.source ?? '' },\n { header: 'CREATED', getValue: (item: any) => (item.createdAt ?? '').slice(0, 19) },\n { header: 'TITLE', getValue: (item: any) => item.title ?? '' },\n];\n\nconst CONTEXT_ARGS = [\n { name: 'workspace', aliases: ['w'], description: 'Workspace UUID' },\n { name: 'org-uuid', description: 'Organization UUID' },\n];\n\nfunction listParams(args: ParsedArgs) {\n return {\n page: args.page ? Number(args.page) : undefined,\n pageSize: args['page-size'] ? Number(args['page-size']) : undefined,\n status: args.status as any,\n supportRequestType: args.type as any,\n severity: args.severity as any,\n source: args.source as any,\n };\n}\n\nfunction requestPayload(data: unknown, args: ParsedArgs) {\n const input = (data ?? {}) as Record<string, unknown>;\n return {\n supportRequestType:\n (input.supportRequestType as string | undefined) ??\n (input.support_request_type as string | undefined) ??\n (args.type as string | undefined) ??\n 'question',\n title: (input.title as string | undefined) ?? requireString(args, 'title'),\n description: (input.description as string | undefined) ?? requireString(args, 'description'),\n severity: (input.severity as string | undefined) ?? (args.severity as string | undefined),\n } as any;\n}\n\nfunction commentPayload(data: unknown, args: ParsedArgs) {\n const input = (data ?? {}) as Record<string, unknown>;\n return {\n body: (input.body as string | undefined) ?? requireString(args, 'body'),\n };\n}\n\nexport const supportDomain: DomainDef = {\n name: 'support',\n description: 'Manage support requests',\n commands: [\n {\n path: ['support', 'list'],\n description: 'List support requests',\n args: [\n ...CONTEXT_ARGS,\n { name: 'status', description: 'Filter by status' },\n { name: 'type', description: 'Filter by type: bug, feature_request, question' },\n { name: 'severity', description: 'Filter by severity' },\n { name: 'source', description: 'Filter by source' },\n { name: 'page', description: 'Page number' },\n { name: 'page-size', description: 'Page size' },\n ],\n columns: SUPPORT_COLUMNS,\n handler: async ({ ctx, args, workspace }) => {\n const client = requireAuth(ctx).apiClient;\n const wid = (args.workspace as string | undefined) ?? workspace;\n const orgUuid = args['org-uuid'] as string | undefined;\n const result = wid\n ? await client.listWorkspaceSupportRequests(wid, listParams(args))\n : orgUuid\n ? await client.listOrgSupportRequests(orgUuid, listParams(args))\n : await client.listSupportRequests(listParams(args));\n outputData(result, ctx, SUPPORT_COLUMNS);\n },\n },\n {\n path: ['support', 'get'],\n description: 'Get a support request',\n args: [\n ...CONTEXT_ARGS,\n { name: 'id', aliases: ['uuid'], description: 'Support request UUID', required: true },\n ],\n handler: async ({ ctx, args, workspace }) => {\n const client = requireAuth(ctx).apiClient;\n const id = requireString(args, 'id');\n const wid = (args.workspace as string | undefined) ?? workspace;\n const orgUuid = args['org-uuid'] as string | undefined;\n const result = wid\n ? await client.getWorkspaceSupportRequest(wid, id)\n : orgUuid\n ? await client.getOrgSupportRequest(orgUuid, id)\n : await client.getSupportRequest(id);\n outputSingle(result, ctx, SUPPORT_COLUMNS);\n },\n },\n {\n path: ['support', 'create'],\n description: 'Create a support request',\n mutates: true,\n args: [\n ...CONTEXT_ARGS,\n { name: 'type', description: 'Request type: bug, feature_request, question' },\n { name: 'title', description: 'Support request title' },\n { name: 'description', description: 'Support request description' },\n { name: 'severity', description: 'Optional severity' },\n ],\n handler: async ({ ctx, args, workspace, data }) => {\n const client = requireAuth(ctx).apiClient;\n const wid = (args.workspace as string | undefined) ?? workspace;\n const orgUuid = args['org-uuid'] as string | undefined;\n const payload = requestPayload(data, args);\n const result = wid\n ? await client.createWorkspaceSupportRequest(wid, payload)\n : orgUuid\n ? await client.createOrgSupportRequest(orgUuid, payload)\n : await client.createSupportRequest(payload);\n outputSingle(result, ctx, SUPPORT_COLUMNS);\n },\n },\n {\n path: ['support', 'comment'],\n description: 'Add a customer comment to a support request',\n mutates: true,\n args: [\n ...CONTEXT_ARGS,\n { name: 'id', aliases: ['uuid'], description: 'Support request UUID', required: true },\n { name: 'body', description: 'Comment body' },\n ],\n handler: async ({ ctx, args, workspace, data }) => {\n const client = requireAuth(ctx).apiClient;\n const id = requireString(args, 'id');\n const wid = (args.workspace as string | undefined) ?? workspace;\n const orgUuid = args['org-uuid'] as string | undefined;\n const payload = commentPayload(data, args);\n const result = wid\n ? await client.commentOnWorkspaceSupportRequest(wid, id, payload)\n : orgUuid\n ? await client.commentOnOrgSupportRequest(orgUuid, id, payload)\n : await client.commentOnSupportRequest(id, payload);\n outputSingle(result, ctx, SUPPORT_COLUMNS);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { COL } from '../lib/output';\n\nconst COLUMNS = [\n COL.id(),\n COL.name(),\n { header: 'TYPE', getValue: (item: any) => item.type ?? '' },\n COL.status(),\n];\n\nexport const supervisorsDomain: DomainDef = {\n name: 'supervisors',\n description: 'Manage supervisors',\n commands: [\n ...crudCommands({\n prefix: ['supervisors'],\n entityName: 'supervisor',\n listMethod: 'getSupervisors',\n getMethod: 'getSupervisor',\n createMethod: 'createSupervisor',\n updateMethod: 'updateSupervisor',\n deleteMethod: 'deleteSupervisor',\n columns: COLUMNS,\n }),\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle } from '../lib/output';\nimport { requireNumber } from '../lib/types';\nimport { CLIError } from '../lib/errors';\nimport { requireAuth } from '../lib/context';\n\nconst RUN_COLUMNS: TableColumn<unknown>[] = [\n { header: 'RUN ID', getValue: (item: any) => item.runId ?? '' },\n { header: 'STATUS', getValue: (item: any) => item.status ?? '' },\n { header: 'MODE', getValue: (item: any) => item.mode ?? '' },\n { header: 'TOTAL', getValue: (item: any) => String(item.total ?? 0) },\n { header: 'SYNCED', getValue: (item: any) => String(item.synced ?? 0) },\n { header: 'FAILED', getValue: (item: any) => String(item.failed ?? 0) },\n { header: 'SKIPPED', getValue: (item: any) => String(item.skipped ?? 0) },\n { header: 'DRY RUN', getValue: (item: any) => (item.dryRun ? 'yes' : 'no') },\n { header: 'STARTED', getValue: (item: any) => item.startedAt ?? '' },\n];\n\nconst ITEM_COLUMNS: TableColumn<unknown>[] = [\n { header: 'INDEX', getValue: (item: any) => String(item.index ?? '') },\n { header: 'DIR', getValue: (item: any) => item.direction ?? '' },\n { header: 'STATUS', getValue: (item: any) => item.status ?? '' },\n { header: 'ENTITY', getValue: (item: any) => item.entityType ?? 'member' },\n {\n header: 'MEMBER',\n getValue: (item: any) => (item.memberId != null ? String(item.memberId) : ''),\n },\n { header: 'REMOTE', getValue: (item: any) => item.remoteRecordId ?? '' },\n { header: 'DETAIL', getValue: (item: any) => item.detail ?? '' },\n];\n\nasync function streamSyncRun(response: Response, verbose: boolean): Promise<void> {\n const reader = response.body?.getReader();\n if (!reader) {\n console.error('No response body');\n return;\n }\n\n const decoder = new TextDecoder();\n let buffer = '';\n let lastRun: any = null;\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (!line.startsWith('data: ')) continue;\n try {\n const data = JSON.parse(line.slice(6));\n if (data.type === 'sync_run') {\n lastRun = data;\n if (verbose) {\n const s = data;\n process.stderr.write(\n `\\r ${s.status} — ${s.synced} synced, ${s.failed} failed, ${s.skipped} skipped (${s.total} total)`\n );\n }\n } else if (data.type === 'sync_item') {\n if (verbose) {\n const i = data;\n const detail = i.detail ? ` — ${i.detail}` : '';\n const member = i.memberId != null ? ` member:${i.memberId}` : '';\n const remote = i.remoteRecordId ? ` remote:${i.remoteRecordId}` : '';\n console.error(`\\n [${i.status}] ${i.direction}${member}${remote}${detail}`);\n }\n }\n } catch {\n // Non-JSON line, skip\n }\n }\n }\n\n if (verbose) {\n console.error(''); // newline after progress\n }\n\n if (lastRun) {\n console.log(JSON.stringify(lastRun, null, 2));\n }\n}\n\nexport const syncDomain: DomainDef = {\n name: 'sync',\n description: 'Run and monitor connection syncs',\n commands: [\n {\n path: ['sync', 'run'],\n description: 'Start a sync run and stream progress (SSE)',\n args: [\n { name: 'connection-id', description: 'Connection ID', required: true },\n { name: 'dry-run', description: 'Test sync without making changes', isFlag: true },\n {\n name: 'full-resync',\n description: 'Clear checkpoints and re-sync all records',\n isFlag: true,\n },\n { name: 'quiet', description: 'Only output final result JSON', isFlag: true },\n { name: 'entity-type', description: 'Scope to entity type: member or record' },\n {\n name: 'board-id',\n description: 'Scope to a single board mapping (requires --entity-type)',\n },\n {\n name: 'record-limit',\n description:\n 'Cap the run to a preview sample (1..200). Requires --dry-run and --entity-type.',\n },\n ],\n examples: [\n 'sync run --connection-id 6',\n 'sync run --connection-id 6 --dry-run',\n 'sync run --connection-id 6 --full-resync',\n 'sync run --connection-id 6 --quiet',\n 'sync run --connection-id 6 --entity-type member',\n 'sync run --connection-id 6 --entity-type member --board-id 18406694561',\n 'sync run --connection-id 6 --dry-run --entity-type member --record-limit 20',\n ],\n mutates: true,\n handler: async ({ ctx, args, workspace }) => {\n const connectionId = requireNumber(args, 'connection-id');\n const dryRun = args['dry-run'] === true;\n const fullResync = args['full-resync'] === true;\n const quiet = args['quiet'] === true;\n const VALID_ENTITY_TYPES = ['member', 'record'] as const;\n type ValidEntityType = (typeof VALID_ENTITY_TYPES)[number];\n const rawEntityType = args['entity-type'] as string | undefined;\n let entityType: ValidEntityType | undefined;\n if (rawEntityType) {\n if (!VALID_ENTITY_TYPES.includes(rawEntityType as ValidEntityType)) {\n throw new CLIError(\n `Invalid --entity-type \"${rawEntityType}\". Allowed values: ${VALID_ENTITY_TYPES.join(', ')}`\n );\n }\n entityType = rawEntityType as ValidEntityType;\n }\n const boardId = args['board-id'] as string | undefined;\n const rawRecordLimit = args['record-limit'];\n let recordLimit: number | undefined;\n if (rawRecordLimit !== undefined && rawRecordLimit !== '') {\n const parsed = Number(rawRecordLimit);\n if (!Number.isInteger(parsed) || parsed < 1 || parsed > 200) {\n throw new CLIError(\n `Invalid --record-limit \"${rawRecordLimit}\". Must be an integer between 1 and 200.`\n );\n }\n if (!dryRun) {\n throw new CLIError(\n '--record-limit requires --dry-run: capped runs are preview-only.'\n );\n }\n // Round-2 review: mirror the route-level guard. The engine\n // can't apply a global record cap across heterogeneous\n // entities (member/record/file), so the API rejects a\n // capped run without ``entityType`` with 400. Surface the\n // same message client-side so the operator fails fast\n // before the request goes out.\n if (entityType === undefined) {\n throw new CLIError(\n '--record-limit requires --entity-type: capped previews must target a single entity type.'\n );\n }\n recordLimit = parsed;\n }\n\n // Round-11 review: the route rejects ``resetCheckpoints``\n // combined with ``dryRun`` or ``recordLimit`` (see\n // ``lib/routes/workspace/connection_sync.py`` —\n // \"resetCheckpoints is incompatible with dryRun/recordLimit\").\n // Without this guard ``gr sync run --dry-run --full-resync``\n // and capped previews + ``--full-resync`` always 400 after a\n // network roundtrip. The UI mirrors the same constraint via\n // ``resetCheckpoints: !dryRun && fullResync`` in\n // ``useSyncRunner.ts``; fail fast here so operators see a\n // clear local error instead.\n if (fullResync && (dryRun || recordLimit !== undefined)) {\n throw new CLIError(\n '--full-resync is incompatible with --dry-run / --record-limit: ' +\n 'checkpoint reset must happen on a non-preview run.'\n );\n }\n\n if (!quiet) {\n const flags = [\n dryRun && '(dry run)',\n fullResync && '(full re-sync)',\n entityType && `(${entityType} only)`,\n boardId && `(board ${boardId})`,\n recordLimit !== undefined && `(limit ${recordLimit})`,\n ]\n .filter(Boolean)\n .join(' ');\n console.error(\n `Starting sync for connection ${connectionId}${flags ? ` ${flags}` : ''}...`\n );\n }\n\n const response = await requireAuth(ctx).apiClient.startSyncRun(\n workspace,\n connectionId,\n {\n dryRun,\n resetCheckpoints: fullResync,\n entityType,\n boardId,\n recordLimit,\n }\n );\n\n if (!response.ok) {\n const text = await response.text();\n console.error(`Sync failed: ${response.status} ${text}`);\n process.exit(1);\n }\n\n await streamSyncRun(response, !quiet);\n },\n },\n {\n path: ['sync', 'runs'],\n description: 'List recent sync runs for a connection',\n args: [\n { name: 'connection-id', description: 'Connection ID', required: true },\n { name: 'limit', description: 'Max runs to return' },\n ],\n handler: async ({ ctx, args, workspace }) => {\n const connectionId = requireNumber(args, 'connection-id');\n const limit = args['limit'] ? Number(args['limit']) : 20;\n const runs = await requireAuth(ctx).apiClient.getSyncRuns(\n workspace,\n connectionId,\n limit\n );\n outputData(runs, ctx, RUN_COLUMNS);\n },\n },\n {\n path: ['sync', 'items'],\n description: 'List items for a specific sync run',\n args: [\n { name: 'connection-id', description: 'Connection ID', required: true },\n { name: 'run-id', description: 'Run ID', required: true },\n ],\n handler: async ({ ctx, args, workspace }) => {\n const connectionId = requireNumber(args, 'connection-id');\n const runId = args['run-id'] as string;\n if (!runId) throw new Error('Missing required argument: --run-id');\n const items = await requireAuth(ctx).apiClient.getSyncRunItems(\n workspace,\n connectionId,\n runId\n );\n outputData(items, ctx, ITEM_COLUMNS);\n },\n },\n {\n path: ['sync', 'config'],\n description: 'Get sync configuration for a connection',\n args: [{ name: 'connection-id', description: 'Connection ID', required: true }],\n handler: async ({ ctx, args, workspace }) => {\n const connectionId = requireNumber(args, 'connection-id');\n const config = await requireAuth(ctx).apiClient.getConnectionSyncConfig(\n workspace,\n connectionId\n );\n console.log(JSON.stringify(config, null, 2));\n },\n },\n {\n path: ['sync', 'update-config'],\n description: 'Update sync configuration for a connection',\n args: [{ name: 'connection-id', description: 'Connection ID', required: true }],\n mutates: true,\n examples: [\n 'sync update-config --connection-id 2 --data \\'{\"syncKey\":\"default\",\"entities\":[...]}\\'',\n 'sync update-config --connection-id 2 --file sync-config.json',\n ],\n handler: async ({ ctx, args, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const connectionId = requireNumber(args, 'connection-id');\n const result = await requireAuth(ctx).apiClient.updateConnectionSyncConfig(\n workspace,\n connectionId,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber, requireString } from '../../lib/types';\nimport { outputData, outputSingle, COL } from '../../lib/output';\nimport { requireAuth } from '../../lib/context';\n\nconst COLUMNS = [\n COL.id(),\n COL.name(),\n { header: 'TYPE', getValue: (item: any) => item.type ?? '' },\n COL.status(),\n];\n\nexport const appConnectionsDomain: DomainDef = {\n name: 'app-connections',\n description: 'Manage platform app connections',\n commands: [\n {\n path: ['app-connections', 'available'],\n description: 'List available app connections',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.listAvailableAppConnections(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['app-connections', 'list'],\n description: 'List enabled app connections',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.listAppConnections(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['app-connections', 'enable'],\n description: 'Enable a platform app',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'App connection ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.enablePlatformApp(workspace, {\n app_slug: requireString(args, 'id'),\n } as any);\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['app-connections', 'get'],\n description: 'Get a platform app',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'App connection ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getPlatformApp(\n workspace,\n requireString(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['app-connections', 'update'],\n description: 'Update a platform app',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'App connection ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updatePlatformApp(\n workspace,\n requireString(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['app-connections', 'delete'],\n description: 'Delete a platform app',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'App connection ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n await requireAuth(ctx).apiClient.deletePlatformApp(workspace, id);\n process.stdout.write(`Deleted app connection ${id}\\n`);\n },\n },\n {\n path: ['app-connections', 'sync-config'],\n description: 'Get sync configuration for a connection',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Connection ID (numeric)', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getConnectionSyncConfig(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['app-connections', 'update-sync-config'],\n description: 'Update sync configuration for a connection (pass raw config as --data)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Connection ID (numeric)', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateConnectionSyncConfig(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['app-connections', 'relink-member'],\n description:\n 'Re-enable sync for a previously unlinked member by clearing ' +\n 'the manual-unlink exclusion on this connection. Idempotent: ' +\n 'returns cleared=false when no exclusion exists.',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'id', description: 'Connection ID (numeric)', required: true },\n { name: 'member-id', description: 'Member ID (numeric)', required: true },\n {\n name: 'board-id',\n description:\n 'Optional Monday board ID. Required for Monday connections ' +\n 'where exclusions are board-scoped; omit for single-scope ' +\n 'connectors.',\n },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const boardIdRaw = args['board-id'];\n const options =\n boardIdRaw !== undefined && boardIdRaw !== ''\n ? { boardId: String(boardIdRaw) }\n : undefined;\n const result = await requireAuth(ctx).apiClient.clearConnectionMemberExclusion(\n workspace,\n requireNumber(args, 'id'),\n requireNumber(args, 'member-id'),\n options\n );\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef } from '../../lib/types';\nimport { CLIError } from '../../lib/errors';\nimport { outputData, outputSingle } from '../../lib/output';\nimport { requireAuth } from '../../lib/context';\n\nexport const confluenceDomain: DomainDef = {\n name: 'confluence',\n description: 'Confluence knowledge base integration',\n commands: [\n {\n path: ['confluence', 'status'],\n description: 'Get Confluence connection status',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getConfluenceStatus(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'configure'],\n description: 'Configure Confluence OAuth credentials',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.configureConfluence(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'authorize'],\n description: 'Start Confluence OAuth flow',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.startConfluenceOAuth(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'disconnect'],\n description: 'Disconnect Confluence (clear tokens)',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disconnectConfluence(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'enable'],\n description: 'Enable Confluence connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.enableConfluence(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'disable'],\n description: 'Disable Confluence connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disableConfluence(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'delete'],\n description: 'Delete Confluence connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n await requireAuth(ctx).apiClient.deleteConfluence(workspace);\n process.stdout.write('Deleted Confluence connection\\n');\n },\n },\n {\n path: ['confluence', 'spaces'],\n description: 'List available Confluence spaces',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.listConfluenceSpaces(workspace);\n outputData(result.results, ctx);\n },\n },\n {\n path: ['confluence', 'pages'],\n description: 'List pages in a Confluence space',\n requiresWorkspace: true,\n args: [{ name: 'space-id', description: 'Confluence space ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const spaceId = args['space-id'];\n if (!spaceId || typeof spaceId !== 'string')\n throw new CLIError('--space-id is required');\n const result = await requireAuth(ctx).apiClient.listConfluencePages(workspace, spaceId);\n outputData(result.results, ctx);\n },\n },\n {\n path: ['confluence', 'sync-config'],\n description: 'Get Confluence sync configuration',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const conns = await requireAuth(ctx).apiClient.listAppConnections(workspace);\n const conn = conns.find((c: any) => c.connectionType === 'confluence_connection');\n if (!conn) throw new CLIError('No Confluence connection found');\n const result = await requireAuth(ctx).apiClient.getConnectionSyncConfig(\n workspace,\n conn.id\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'update-sync-config'],\n description: 'Update Confluence sync configuration',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const conns = await requireAuth(ctx).apiClient.listAppConnections(workspace);\n const conn = conns.find((c: any) => c.connectionType === 'confluence_connection');\n if (!conn) throw new CLIError('No Confluence connection found');\n const result = await requireAuth(ctx).apiClient.updateConnectionSyncConfig(\n workspace,\n conn.id,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../../lib/types';\nimport { crudCommands } from '../../lib/crud';\nimport { outputData, outputSingle, COL } from '../../lib/output';\nimport { requireAuth } from '../../lib/context';\n\nconst COLUMNS = [COL.id(), COL.name(), COL.status()];\n\nexport const discordBotsDomain: DomainDef = {\n name: 'discord-bots',\n description: 'Manage Discord bot integrations',\n commands: [\n ...crudCommands({\n prefix: ['discord-bots'],\n entityName: 'Discord bot',\n listMethod: 'getDiscordBots',\n getMethod: 'getDiscordBot',\n createMethod: 'createDiscordBot',\n updateMethod: 'updateDiscordBot',\n deleteMethod: 'deleteDiscordBot',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n {\n path: ['discord-bots', 'register-commands'],\n description: 'Register slash commands for a Discord bot',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Discord bot ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.registerDiscordSlashCommands(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['discord-bots', 'threads'],\n description: 'List Discord threads',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Discord bot ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getDiscordThreads(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['discord-bots', 'guilds'],\n description: 'List Discord guilds',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Discord bot ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getDiscordGuilds(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['discord-bots', 'accounts'],\n description: 'List Discord bot accounts',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Discord bot ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getDiscordBotAccounts(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../../lib/types';\nimport type { TableColumn } from '../../lib/output';\nimport { crudCommands } from '../../lib/crud';\nimport { outputSingle, COL } from '../../lib/output';\nimport { requireAuth } from '../../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'URL', getValue: (item: any) => item.base_url ?? '' },\n COL.status(),\n];\n\nexport const fhirConnectionsDomain: DomainDef = {\n name: 'fhir-connections',\n description: 'Manage FHIR connections',\n commands: [\n ...crudCommands({\n prefix: ['fhir-connections'],\n entityName: 'FHIR connection',\n listMethod: 'getFhirConnections',\n getMethod: 'getFhirConnection',\n createMethod: 'createFhirConnection',\n updateMethod: 'updateFhirConnection',\n deleteMethod: 'deleteFhirConnection',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n {\n path: ['fhir-connections', 'test'],\n description: 'Test a FHIR connection',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'FHIR connection ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.testFhirConnection(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber, requireString } from '../../lib/types';\nimport { CLIError } from '../../lib/errors';\nimport { outputData, outputSingle } from '../../lib/output';\nimport {\n LIST_PAGINATION_ARGS,\n fetchAllPages,\n listResult,\n parsePaginationArgs,\n} from '../../lib/pagination';\nimport { requireAuth } from '../../lib/context';\n\nexport const hubspotDomain: DomainDef = {\n name: 'hubspot',\n description: 'HubSpot CRM integration',\n commands: [\n {\n path: ['hubspot', 'status'],\n description: 'Get HubSpot connection status',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getHubspotStatus(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'configure'],\n description: 'Configure HubSpot connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.configureHubspot(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'authorize'],\n description: 'Start HubSpot OAuth flow',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.startHubspotOAuth(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'disconnect'],\n description: 'Disconnect HubSpot',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disconnectHubspot(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'enable'],\n description: 'Enable HubSpot connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.enableHubspot(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'disable'],\n description: 'Disable HubSpot connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disableHubspot(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'delete'],\n description: 'Delete HubSpot connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n await requireAuth(ctx).apiClient.deleteHubspot(workspace);\n process.stdout.write('Deleted HubSpot connection\\n');\n },\n },\n {\n path: ['hubspot', 'sync-config'],\n description: 'Get HubSpot sync configuration',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n // Find hubspot connection ID\n const conns = await requireAuth(ctx).apiClient.listAppConnections(workspace);\n const conn = conns.find((c: any) => c.connectionType === 'hubspot_connection');\n if (!conn) throw new CLIError('No HubSpot connection found');\n const result = await requireAuth(ctx).apiClient.getConnectionSyncConfig(\n workspace,\n conn.id\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'update-sync-config'],\n description: 'Update HubSpot sync configuration',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const conns = await requireAuth(ctx).apiClient.listAppConnections(workspace);\n const conn = conns.find((c: any) => c.connectionType === 'hubspot_connection');\n if (!conn) throw new CLIError('No HubSpot connection found');\n const result = await requireAuth(ctx).apiClient.updateConnectionSyncConfig(\n workspace,\n conn.id,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'reconciliation'],\n description: 'Find matching HubSpot contacts for workspace members',\n requiresWorkspace: true,\n args: [\n { name: 'offset', description: 'Pagination offset' },\n { name: 'limit', description: 'Max results' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const offset = args['offset'] ? Number(args['offset']) : undefined;\n const limit = args['limit'] ? Number(args['limit']) : undefined;\n const result = await requireAuth(ctx).apiClient.getHubspotReconciliationMatches(\n workspace,\n {\n offset,\n limit,\n }\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['hubspot', 'linked-members'],\n description: 'List members linked to HubSpot contacts',\n requiresWorkspace: true,\n args: LIST_PAGINATION_ARGS,\n handler: async ({ ctx, workspace, args }) => {\n const pag = parsePaginationArgs(args);\n if (pag.all) {\n const allItems = await fetchAllPages(({ page, pageSize }) =>\n requireAuth(ctx).apiClient.getLinkedHubspotMembers(workspace, { page, pageSize })\n );\n outputData(allItems, ctx);\n return;\n }\n const options: { page?: number; pageSize?: number } = {};\n if (pag.page) options.page = pag.page;\n if (pag.pageSize) options.pageSize = pag.pageSize;\n const result = await requireAuth(ctx).apiClient.getLinkedHubspotMembers(\n workspace,\n options\n );\n outputData(listResult(result, true), ctx);\n },\n },\n {\n path: ['hubspot', 'link-member'],\n description: 'Link a member to a HubSpot contact',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'contact-id', description: 'HubSpot contact ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.linkMemberToHubspot(workspace, {\n memberId: requireNumber(args, 'member-id'),\n hubspotRecordId: requireString(args, 'contact-id'),\n });\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'unlink-member'],\n description: 'Unlink a member from HubSpot',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.unlinkMemberFromHubspot(\n workspace,\n requireNumber(args, 'member-id')\n );\n process.stdout.write('Unlinked member from HubSpot\\n');\n },\n },\n {\n path: ['hubspot', 'contact-properties'],\n description: 'List available HubSpot contact properties',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getHubspotContactProperties(workspace);\n outputData(result, ctx);\n },\n },\n {\n path: ['hubspot', 'managed-rules'],\n description: 'List HubSpot managed sync rules and their status',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getHubspotManagedRules(workspace);\n outputData(result, ctx);\n },\n },\n {\n path: ['hubspot', 'transform-presets'],\n description: 'List available HubSpot field transform presets',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getHubspotTransformPresets(workspace);\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber, requireString } from '../../lib/types';\nimport { CLIError } from '../../lib/errors';\nimport { outputData, outputSingle } from '../../lib/output';\nimport {\n LIST_PAGINATION_ARGS,\n fetchAllPages,\n listResult,\n parsePaginationArgs,\n} from '../../lib/pagination';\nimport { requireAuth } from '../../lib/context';\n\nexport const mondayDomain: DomainDef = {\n name: 'monday',\n description: 'Monday.com integration',\n commands: [\n {\n path: ['monday', 'status'],\n description: 'Get Monday.com connection status',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMondayConnectionStatus(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'authorize'],\n description: 'Get Monday.com OAuth authorization URL',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.authorizeMondayConnection(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'configure'],\n description: 'Configure Monday.com connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.configureMondayConnection(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'disconnect'],\n description: 'Disconnect Monday.com',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disconnectMondayConnection(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'enable'],\n description: 'Enable Monday.com connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.enableMondayConnection(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'disable'],\n description: 'Disable Monday.com connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disableMondayConnection(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'delete'],\n description: 'Delete Monday.com connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n await requireAuth(ctx).apiClient.deleteMondayConnection(workspace);\n process.stdout.write('Deleted Monday.com connection\\n');\n },\n },\n {\n path: ['monday', 'sync-config'],\n description: 'Get Monday.com sync configuration',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMondaySyncConfig(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'update-sync-config'],\n description: 'Update Monday.com sync configuration',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n // Accept both the raw config and the full GET response shape\n // ({ syncConfig: {...} }). The API client wraps in { syncConfig },\n // so unwrap here to avoid double-wrapping.\n const syncConfig = (data as any).syncConfig ?? data;\n const result = await requireAuth(ctx).apiClient.updateMondaySyncConfig(\n workspace,\n syncConfig as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'reconciliation'],\n description: 'Find matching Monday.com items for workspace members',\n requiresWorkspace: true,\n args: [\n { name: 'offset', description: 'Pagination offset' },\n { name: 'limit', description: 'Max results' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const offset = args['offset'] ? Number(args['offset']) : undefined;\n const limit = args['limit'] ? Number(args['limit']) : undefined;\n const result = await requireAuth(ctx).apiClient.getMondayReconciliationMatches(\n workspace,\n {\n offset,\n limit,\n }\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['monday', 'linked-members'],\n description: 'List members linked to Monday.com items',\n requiresWorkspace: true,\n args: [{ name: 'board-id', description: 'Board ID' }, ...LIST_PAGINATION_ARGS],\n handler: async ({ ctx, workspace, args }) => {\n const boardId = (args['board-id'] as string) ?? undefined;\n const pag = parsePaginationArgs(args);\n if (pag.all) {\n const allItems = await fetchAllPages(({ page, pageSize }) =>\n requireAuth(ctx).apiClient.getLinkedMondayMembers(workspace, {\n board_id: boardId,\n page,\n pageSize,\n })\n );\n outputData(allItems, ctx);\n return;\n }\n const options: { board_id?: string; page?: number; pageSize?: number } = {};\n if (boardId) options.board_id = boardId;\n if (pag.page) options.page = pag.page;\n if (pag.pageSize) options.pageSize = pag.pageSize;\n const result = await requireAuth(ctx).apiClient.getLinkedMondayMembers(\n workspace,\n options\n );\n outputData(listResult(result, true), ctx);\n },\n },\n {\n path: ['monday', 'link-member'],\n description: 'Link a member to a Monday.com item',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'item-id', description: 'Monday item ID', required: true },\n { name: 'board-id', description: 'Monday board ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.linkMemberToMonday(workspace, {\n memberId: requireNumber(args, 'member-id'),\n mondayItemId: requireString(args, 'item-id'),\n boardId: requireString(args, 'board-id'),\n });\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'unlink-member'],\n description: 'Unlink a member from Monday.com',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'board-id', description: 'Monday board ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.unlinkMemberFromMonday(\n workspace,\n requireNumber(args, 'member-id'),\n requireString(args, 'board-id')\n );\n process.stdout.write('Unlinked member from Monday.com\\n');\n },\n },\n {\n path: ['monday', 'boards'],\n description: 'List Monday.com boards',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMondayBoards(workspace);\n outputData(result, ctx);\n },\n },\n {\n path: ['monday', 'board-columns'],\n description: 'List columns for a Monday.com board',\n requiresWorkspace: true,\n args: [{ name: 'board-id', description: 'Board ID', required: true }],\n handler: async ({ ctx, args, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMondayBoardColumns(\n workspace,\n requireString(args, 'board-id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['monday', 'board-groups'],\n description: 'List groups for a Monday.com board',\n requiresWorkspace: true,\n args: [{ name: 'board-id', description: 'Board ID', required: true }],\n handler: async ({ ctx, args, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMondayBoardGroups(\n workspace,\n requireString(args, 'board-id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['monday', 'user-info'],\n description: 'Get current Monday.com user info',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMondayCurrentUserInfo(workspace);\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber, requireString } from '../../lib/types';\nimport { CLIError } from '../../lib/errors';\nimport { outputData, outputSingle } from '../../lib/output';\nimport {\n LIST_PAGINATION_ARGS,\n fetchAllPages,\n listResult,\n parsePaginationArgs,\n} from '../../lib/pagination';\nimport { requireAuth } from '../../lib/context';\n\nexport const salesforceDomain: DomainDef = {\n name: 'salesforce',\n description: 'Salesforce CRM integration',\n commands: [\n {\n path: ['salesforce', 'status'],\n description: 'Get Salesforce connection status',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getSalesforceStatus(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'configure'],\n description: 'Configure Salesforce connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.configureSalesforce(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'authorize'],\n description: 'Start Salesforce OAuth flow',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.startSalesforceOAuth(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'disconnect'],\n description: 'Disconnect Salesforce',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disconnectSalesforce(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'enable'],\n description: 'Enable Salesforce connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.enableSalesforce(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'disable'],\n description: 'Disable Salesforce connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disableSalesforce(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'delete'],\n description: 'Delete Salesforce connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n await requireAuth(ctx).apiClient.deleteSalesforce(workspace);\n process.stdout.write('Deleted Salesforce connection\\n');\n },\n },\n {\n path: ['salesforce', 'sync-config'],\n description: 'Get Salesforce sync configuration',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getSalesforceSyncConfig(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'update-sync-config'],\n description: 'Update Salesforce sync configuration',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.updateSalesforceSyncConfig(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'reconciliation'],\n description: 'Find matching Salesforce records for workspace members',\n requiresWorkspace: true,\n args: [\n { name: 'offset', description: 'Pagination offset' },\n { name: 'limit', description: 'Max results' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const offset = args['offset'] ? Number(args['offset']) : undefined;\n const limit = args['limit'] ? Number(args['limit']) : undefined;\n const result = await requireAuth(ctx).apiClient.getSalesforceReconciliationMatches(\n workspace,\n {\n offset,\n limit,\n }\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['salesforce', 'linked-members'],\n description: 'List members linked to Salesforce records',\n requiresWorkspace: true,\n args: LIST_PAGINATION_ARGS,\n handler: async ({ ctx, workspace, args }) => {\n const pag = parsePaginationArgs(args);\n if (pag.all) {\n const allItems = await fetchAllPages(({ page, pageSize }) =>\n requireAuth(ctx).apiClient.getLinkedSalesforceMembers(workspace, {\n page,\n pageSize,\n })\n );\n outputData(allItems, ctx);\n return;\n }\n const options: { page?: number; pageSize?: number } = {};\n if (pag.page) options.page = pag.page;\n if (pag.pageSize) options.pageSize = pag.pageSize;\n const result = await requireAuth(ctx).apiClient.getLinkedSalesforceMembers(\n workspace,\n options\n );\n outputData(listResult(result, true), ctx);\n },\n },\n {\n path: ['salesforce', 'link-member'],\n description: 'Link a member to a Salesforce record',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'record-id', description: 'Salesforce record ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.linkMemberToSalesforce(workspace, {\n memberId: requireNumber(args, 'member-id'),\n salesforceRecordId: requireString(args, 'record-id'),\n });\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'unlink-member'],\n description: 'Unlink a member from Salesforce',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.unlinkMemberFromSalesforce(\n workspace,\n requireNumber(args, 'member-id')\n );\n process.stdout.write('Unlinked member from Salesforce\\n');\n },\n },\n {\n path: ['salesforce', 'describe'],\n description: 'Describe a Salesforce object schema',\n requiresWorkspace: true,\n args: [\n {\n name: 'object-type',\n description: 'Salesforce object type (e.g., Contact)',\n required: true,\n },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.describeSalesforceObject(\n workspace,\n requireString(args, 'object-type')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'search'],\n description: 'Search Salesforce records',\n requiresWorkspace: true,\n args: [\n { name: 'query', description: 'Search query', required: true },\n { name: 'object-type', description: 'Salesforce object type' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.searchSalesforceRecords(workspace, {\n query: requireString(args, 'query'),\n objectType: (args['object-type'] as string) ?? undefined,\n } as any);\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../../lib/types';\nimport { crudCommands } from '../../lib/crud';\nimport { CLIError } from '../../lib/errors';\nimport { outputData, outputSingle, COL } from '../../lib/output';\nimport { requireAuth } from '../../lib/context';\n\nconst COLUMNS = [COL.id(), COL.name(), COL.status()];\n\n/** Inject computed Slack integration URLs into the response object. */\nfunction addSlackUrls(\n data: Record<string, unknown>,\n apiUrl: string,\n workspaceUuid: string\n): Record<string, unknown> {\n const base = `${apiUrl}/api/v2/w/${workspaceUuid}/app-connections/slack`;\n return {\n ...data,\n _urls: {\n eventsEndpoint: `${base}/routines`,\n oauthBotCallback: `${base}/oauth/callback`,\n oauthUserCallback: `${base}/oauth/user/callback`,\n oauthInstall: `${base}/oauth/install?app_uuid=${data.uuid ?? ''}`,\n },\n };\n}\n\nexport const slackAppsDomain: DomainDef = {\n name: 'slack-apps',\n description: 'Manage Slack app integrations',\n commands: [\n // List + delete from CRUD; get/create/update are custom to inject URLs\n ...crudCommands({\n prefix: ['slack-apps'],\n entityName: 'Slack app',\n listMethod: 'getSlackApps',\n deleteMethod: 'deleteSlackApp',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n {\n path: ['slack-apps', 'get'],\n description: 'Get a Slack app by ID',\n args: [{ name: 'id', description: 'Slack app ID', required: true }],\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getSlackApp(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(addSlackUrls(result as any, ctx.envConfig.apiUrl, workspace), ctx);\n },\n },\n {\n path: ['slack-apps', 'create'],\n description: 'Create a Slack app',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.createSlackApp(workspace, data as any);\n outputSingle(addSlackUrls(result as any, ctx.envConfig.apiUrl, workspace), ctx);\n },\n },\n {\n path: ['slack-apps', 'update'],\n description: 'Update a Slack app',\n mutates: true,\n args: [{ name: 'id', description: 'Slack app ID', required: true }],\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.updateSlackApp(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(addSlackUrls(result as any, ctx.envConfig.apiUrl, workspace), ctx);\n },\n },\n {\n path: ['slack-apps', 'threads'],\n description: 'List Slack threads',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Slack app ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getSlackThreads(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['slack-apps', 'installations'],\n description: 'List Slack installations',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Slack app ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getSlackInstallations(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['slack-apps', 'accounts'],\n description: 'List Slack app accounts',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Slack app ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getSlackAppAccounts(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../../lib/types';\nimport { crudCommands } from '../../lib/crud';\nimport { CLIError } from '../../lib/errors';\nimport { outputData, outputSingle, COL } from '../../lib/output';\nimport { requireAuth } from '../../lib/context';\n\nconst COLUMNS = [COL.id(), COL.name(), COL.status()];\n\n/** Inject computed Teams integration URLs into the response object. */\nfunction addTeamsUrls(\n data: Record<string, unknown>,\n apiUrl: string,\n workspaceUuid: string\n): Record<string, unknown> {\n const base = `${apiUrl}/api/v2/w/${workspaceUuid}/app-connections/teams`;\n return {\n ...data,\n _urls: {\n eventsEndpoint: `${base}/events`,\n oauthUserAuthorize: `${base}/oauth/user/authorize?app_id=${data.id ?? ''}`,\n oauthUserCallback: `${base}/oauth/user/callback`,\n },\n };\n}\n\nexport const teamsAppsDomain: DomainDef = {\n name: 'teams-apps',\n description: 'Manage Microsoft Teams app integrations',\n commands: [\n ...crudCommands({\n prefix: ['teams-apps'],\n entityName: 'Teams app',\n listMethod: 'getTeamsApps',\n deleteMethod: 'deleteTeamsApp',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n {\n path: ['teams-apps', 'get'],\n description: 'Get a Teams app by ID',\n args: [{ name: 'id', description: 'Teams app ID', required: true }],\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getTeamsApp(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(addTeamsUrls(result as any, ctx.envConfig.apiUrl, workspace), ctx);\n },\n },\n {\n path: ['teams-apps', 'create'],\n description: 'Create a Teams app',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.createTeamsApp(workspace, data as any);\n outputSingle(addTeamsUrls(result as any, ctx.envConfig.apiUrl, workspace), ctx);\n },\n },\n {\n path: ['teams-apps', 'update'],\n description: 'Update a Teams app',\n mutates: true,\n args: [{ name: 'id', description: 'Teams app ID', required: true }],\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.updateTeamsApp(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(addTeamsUrls(result as any, ctx.envConfig.apiUrl, workspace), ctx);\n },\n },\n {\n path: ['teams-apps', 'conversations'],\n description: 'List Teams conversations linked to chats',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Teams app ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getTeamsConversations(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['teams-apps', 'installations'],\n description: 'List per-tenant Teams installations',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Teams app ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getTeamsInstallations(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['teams-apps', 'accounts'],\n description: 'List linked Teams (Entra) accounts for this app',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Teams app ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getTeamsAppAccounts(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n ],\n};\n","import type { CommandRegistry } from '../lib/registry';\n\n// Core domains — Phase 2a\nimport { agentTasksDomain } from './agent-tasks';\nimport { agentsDomain } from './agents';\nimport { chatsDomain } from './chats';\nimport { membersDomain } from './members';\nimport { tasksDomain } from './tasks';\nimport { workflowsDomain } from './workflows';\nimport { workflowVersionsDomain } from './workflow-versions';\nimport { workspacesDomain } from './workspaces';\n\n// Core domains — Phase 2b\nimport { assignmentsDomain } from './assignments';\nimport { calendarsDomain } from './calendars';\nimport { dataTypesDomain } from './data-types';\nimport { eventsDomain } from './events';\nimport { filesDomain } from './files';\nimport { journeysDomain } from './journeys';\nimport { personasDomain } from './personas';\nimport { qualificationsDomain } from './qualifications';\nimport { sitesDomain } from './sites';\n\n// Secondary domains — Phase 3\nimport { accessGrantsDomain } from './access-grants';\nimport { aiModelsDomain } from './ai-models';\nimport { apiKeysDomain } from './api-keys';\nimport { appsDomain } from './apps';\nimport { authManageDomain } from './auth-manage';\nimport { billingPortalDomain } from './billing-portal';\nimport { conciergeDomain } from './concierge';\nimport { customToolkitsDomain } from './custom-toolkits';\nimport { featuresDomain } from './features';\nimport { inboxesDomain } from './inboxes';\nimport { mcpServersDomain } from './mcp-servers';\nimport { memberMemoriesDomain } from './member-memories';\nimport { milestonesDomain } from './milestones';\nimport { notificationRulesDomain } from './notification-rules';\nimport { oauthDomain } from './oauth';\nimport { operatorGroupsDomain } from './operator-groups';\nimport { orgDomain } from './org';\nimport { orgPhoneNumbersDomain } from './org-phone-numbers';\nimport { phoneNumbersDomain } from './phone-numbers';\nimport { pronunciationsDomain } from './pronunciations';\nimport { reportsDomain } from './reports';\nimport { subscriptionsDomain } from './subscriptions';\nimport { promptsDomain } from './prompts';\nimport { supportDomain } from './support';\nimport { supervisorsDomain } from './supervisors';\nimport { syncDomain } from './sync';\n\n// Integration domains — Phase 4\nimport { appConnectionsDomain } from './integrations/app-connections';\nimport { confluenceDomain } from './integrations/confluence';\nimport { discordBotsDomain } from './integrations/discord-bots';\nimport { fhirConnectionsDomain } from './integrations/fhir-connections';\nimport { hubspotDomain } from './integrations/hubspot';\nimport { mondayDomain } from './integrations/monday';\nimport { salesforceDomain } from './integrations/salesforce';\nimport { slackAppsDomain } from './integrations/slack-apps';\nimport { teamsAppsDomain } from './integrations/teams-apps';\n\n/**\n * Register the full set of public CLI domains on a registry.\n *\n * This file intentionally does NOT import any admin or infrastructure domains\n * (deploy, rollback, railgun, admin/*). Those live in `@gravity-rail/gr-cli`\n * and are layered on top via its own `registerAllDomains`.\n */\nexport function registerPublicDomains(registry: CommandRegistry): void {\n // Core\n registry.register(tasksDomain);\n registry.register(chatsDomain);\n registry.register(membersDomain);\n registry.register(workspacesDomain);\n registry.register(workflowsDomain);\n registry.register(workflowVersionsDomain);\n registry.register(agentsDomain);\n registry.register(agentTasksDomain);\n registry.register(assignmentsDomain);\n registry.register(dataTypesDomain);\n registry.register(sitesDomain);\n registry.register(filesDomain);\n registry.register(eventsDomain);\n registry.register(calendarsDomain);\n registry.register(qualificationsDomain);\n registry.register(personasDomain);\n registry.register(journeysDomain);\n\n // Secondary\n registry.register(phoneNumbersDomain);\n registry.register(inboxesDomain);\n registry.register(operatorGroupsDomain);\n registry.register(accessGrantsDomain);\n registry.register(notificationRulesDomain);\n registry.register(supervisorsDomain);\n registry.register(promptsDomain);\n registry.register(milestonesDomain);\n registry.register(customToolkitsDomain);\n registry.register(mcpServersDomain);\n registry.register(apiKeysDomain);\n registry.register(subscriptionsDomain);\n registry.register(supportDomain);\n registry.register(reportsDomain);\n registry.register(aiModelsDomain);\n registry.register(featuresDomain);\n registry.register(pronunciationsDomain);\n registry.register(orgDomain);\n registry.register(orgPhoneNumbersDomain);\n registry.register(authManageDomain);\n registry.register(appsDomain);\n registry.register(oauthDomain);\n registry.register(conciergeDomain);\n registry.register(memberMemoriesDomain);\n registry.register(syncDomain);\n\n // Integrations\n registry.register(confluenceDomain);\n registry.register(discordBotsDomain);\n registry.register(slackAppsDomain);\n registry.register(teamsAppsDomain);\n registry.register(fhirConnectionsDomain);\n registry.register(appConnectionsDomain);\n registry.register(hubspotDomain);\n registry.register(mondayDomain);\n registry.register(salesforceDomain);\n\n // Billing portal (non-admin)\n registry.register(billingPortalDomain);\n}\n","import { execFile } from 'child_process';\nimport { stderr } from '../lib/output';\nimport type { AuthenticatedContext } from '../lib/context';\n\n/**\n * Open an authenticated browser session using the CLI's existing credentials.\n *\n * Flow:\n * 1. Get the current account's email from the CLI session\n * 2. Request a magic link via the API (token returned directly since caller is authenticated)\n * 3. Open the magic link URL in the default browser (or print it with --no-open)\n */\nexport async function authBrowserCommand(\n ctx: AuthenticatedContext,\n args: Record<string, unknown>\n): Promise<void> {\n const noOpen = Boolean(args['no-open']);\n\n // Get current account email\n const account = await ctx.apiClient.getUserAccount();\n if (!account.email) {\n process.stderr.write('Error: No email associated with current account\\n');\n process.exit(1);\n }\n\n // Request magic link — since we're authenticated, the API returns the token directly\n const response = await ctx.apiClient.requestMagicLink(account.email);\n\n if (!response.success || !response.magicLinkUrl) {\n process.stderr.write('Error: Failed to create magic link\\n');\n process.exit(1);\n }\n\n const url = response.magicLinkUrl;\n\n if (noOpen) {\n // Just print the URL to stdout for scripting/manual use\n process.stdout.write(url + '\\n');\n return;\n }\n\n // Open in default browser\n stderr(`Opening browser for ${account.email} (${ctx.env})...`);\n openUrl(url);\n stderr('Browser opened. Link expires in 15 minutes.');\n}\n\n/** Open a URL in the default browser (cross-platform). Uses execFile to avoid shell injection. */\nfunction openUrl(url: string): void {\n const platform = process.platform;\n\n let command: string;\n let args: string[];\n\n if (platform === 'darwin') {\n command = 'open';\n args = [url];\n } else if (platform === 'win32') {\n command = 'cmd.exe';\n args = ['/c', 'start', '', url];\n } else {\n command = 'xdg-open';\n args = [url];\n }\n\n execFile(command, args, (err) => {\n if (err) {\n // Non-fatal — user can copy the URL from --no-open output\n process.stderr.write('Warning: Could not open browser automatically\\n');\n }\n });\n}\n","/**\n * Shared chat session infrastructure.\n *\n * Defines the ChatSession abstraction consumed by all chat modes (text, realtime, voice).\n * Entry points (manage, chat, concierge) construct a ChatSession and pass it here.\n */\n\nimport {\n AGUIClient,\n clearScreen,\n getErrorMessage,\n getTextDelta,\n printMessage,\n type AGUIChatMessage,\n} from '../cli-utils';\nimport * as readline from 'readline';\nimport { CLIError } from './errors';\nimport type { AuthenticatedContext } from './context';\nimport { RealtimeClient } from './realtime-client';\nimport { ChatTUI, type ChatItem } from './chat-tui';\nimport {\n checkSoxAvailable,\n listInputDevices,\n listOutputDevices,\n selectDevice,\n MicCapture,\n AudioPlayer,\n} from './audio';\n\n// ─── ChatSession abstraction ─────────────────────────────────────────────────\n\n/** Everything a chat mode needs — constructed differently per entry point. */\nexport interface ChatSession {\n ctx: AuthenticatedContext;\n chatId: number;\n chatUuid: string;\n chatTitle: string;\n aguiEndpointUrl: string;\n wsUrl: string;\n loadMessages: () => Promise<any[]>;\n /** Display label: \"Workspace Manager\", \"Concierge\", etc. */\n label: string;\n /** AGUI request model field. Undefined = omit from body. */\n model?: string;\n}\n\n// ─── Mode dispatcher ─────────────────────────────────────────────────────────\n\nexport async function runChatSession(\n session: ChatSession,\n args: Record<string, any>\n): Promise<void> {\n const debug = !!args.debug;\n const isVoice = !!args.voice;\n const isRealtime = !!args.realtime || isVoice;\n const message = typeof args.message === 'string' ? args.message : undefined;\n const autoApprove = !!args['auto-approve'];\n\n if (args['list-devices']) {\n await listAudioDevices();\n return;\n }\n\n if (!message && !process.stdin.isTTY) {\n throw new CLIError(\n 'Interactive mode requires a TTY. Use --message for non-interactive mode.'\n );\n }\n\n if (message) {\n await singleTurnChatSession(session, message, debug, autoApprove);\n } else if (isVoice) {\n await voiceChatSession(session, vadMode(args), args, debug);\n } else if (isRealtime) {\n await realtimeChatSession(session, vadMode(args), debug);\n } else {\n await interactiveChatSession(session, debug);\n }\n}\n\nexport function vadMode(args: Record<string, any>): 'client' | 'server' {\n return (typeof args.vad === 'string' ? args.vad : 'server') as 'client' | 'server';\n}\n\n// ─── Single-turn text mode (SSE) ────────────────────────────────────────────\n\nasync function singleTurnChatSession(\n session: ChatSession,\n message: string,\n debug: boolean,\n autoApprove: boolean = false\n): Promise<void> {\n const aguiClient = new AGUIClient({\n baseUrl: session.ctx.envConfig.apiUrl,\n endpointUrl: session.aguiEndpointUrl,\n accessToken: session.ctx.accessToken,\n debug,\n model: session.model,\n });\n\n // Stream all SSE events. The AGUI stream includes tool calls, tool\n // results, and text content across all inference turns. We accumulate\n // text and show tool call progress, then poll for final text if the\n // stream ended mid-turn (e.g. after tool calls with no final text).\n let streamText = '';\n let hasToolCalls = false;\n let eventCount = 0;\n\n // Optionally log raw events to a file for debugging\n const logFile = process.env.GR_SSE_LOG;\n const fs = logFile ? await import('fs') : null;\n const logStream = logFile && fs ? fs.createWriteStream(logFile, { flags: 'a' }) : null;\n\n await aguiClient.sendMessage(\n [{ role: 'user', content: message }],\n (event) => {\n eventCount++;\n if (logStream) logStream.write(JSON.stringify(event) + '\\n');\n\n const delta = getTextDelta(event);\n if (delta) streamText += delta;\n\n const type = event.type?.toLowerCase() ?? '';\n if (type === 'tool_call_start') {\n hasToolCalls = true;\n const name = (event as Record<string, any>).name ?? '';\n process.stderr.write(` [${name}]\\n`);\n }\n\n const errorMsg = getErrorMessage(event);\n if (errorMsg) process.stderr.write(`\\x1B[31mError: ${errorMsg}\\x1B[0m\\n`);\n },\n { autoApprove }\n );\n\n if (logStream) logStream.end();\n if (debug) process.stderr.write(` (${eventCount} SSE events)\\n`);\n\n // If we got text from the stream, print it\n if (streamText) {\n process.stdout.write(`\\x1B[32mAssistant:\\x1B[0m ${streamText}\\n`);\n return;\n }\n\n // No text in stream (tool calls only) — poll for the final response\n if (hasToolCalls) {\n process.stderr.write(' (waiting for completion...)\\n');\n const maxWaitMs = 180_000;\n const pollIntervalMs = 2000;\n const startTime = Date.now();\n let finalText = '';\n\n while (Date.now() - startTime < maxWaitMs) {\n await new Promise((r) => setTimeout(r, pollIntervalMs));\n try {\n const msgs = await session.loadMessages();\n // Find the last assistant message with actual text\n for (let i = msgs.length - 1; i >= 0; i--) {\n const m = msgs[i];\n if (m.role === 'assistant' && m.content && !m.tool_calls?.length) {\n finalText = m.content;\n break;\n }\n }\n if (finalText) break;\n } catch {\n // keep polling\n }\n }\n\n process.stdout.write(`\\x1B[32mAssistant:\\x1B[0m ${finalText || '(no text response)'}\\n`);\n } else {\n process.stdout.write(`\\x1B[32mAssistant:\\x1B[0m (no response)\\n`);\n }\n}\n\n// ─── Interactive text mode (SSE) ─────────────────────────────────────────────\n\nasync function interactiveChatSession(session: ChatSession, debug: boolean): Promise<void> {\n const aguiClient = new AGUIClient({\n baseUrl: session.ctx.envConfig.apiUrl,\n endpointUrl: session.aguiEndpointUrl,\n accessToken: session.ctx.accessToken,\n debug,\n model: session.model,\n });\n\n clearScreen();\n console.log('='.repeat(60));\n console.log(session.label);\n console.log('='.repeat(60));\n console.log(`Chat: ${session.chatTitle}`);\n console.log(\"Type your message and press Enter. Type 'exit' or Ctrl+C to quit.\");\n console.log('='.repeat(60));\n console.log('');\n\n const existingMessages = await session.loadMessages();\n if (existingMessages.length > 0) {\n console.log('\\x1B[90m--- Previous messages ---\\x1B[0m\\n');\n for (const msg of existingMessages.slice(-10)) {\n const text = typeof msg.content === 'string' ? msg.content : '';\n if (text && text.trim()) {\n printMessage(text, msg.role as 'user' | 'assistant' | 'system');\n }\n }\n console.log('\\x1B[90m--- End of history ---\\x1B[0m\\n');\n }\n\n const conversationMessages: AGUIChatMessage[] = [];\n for (const msg of existingMessages.slice(-10)) {\n const text = typeof msg.content === 'string' ? msg.content : '';\n if (text && text.trim() && (msg.role === 'user' || msg.role === 'assistant')) {\n conversationMessages.push({ role: msg.role, content: text });\n }\n }\n\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n\n return new Promise<void>((resolve) => {\n const prompt = (): void => {\n rl.question('\\x1B[34mYou:\\x1B[0m ', async (input) => {\n const trimmed = input.trim();\n if (!trimmed) {\n prompt();\n return;\n }\n if (trimmed.toLowerCase() === 'exit' || trimmed.toLowerCase() === 'quit') {\n console.log('\\nGoodbye!');\n rl.close();\n return;\n }\n\n conversationMessages.push({ role: 'user', content: trimmed });\n process.stdout.write('\\n\\x1B[32mAssistant:\\x1B[0m ');\n let assistantContent = '';\n\n try {\n await aguiClient.sendMessage(conversationMessages, (event) => {\n const delta = getTextDelta(event);\n if (delta) {\n process.stdout.write(delta);\n assistantContent += delta;\n }\n const errorMsg = getErrorMessage(event);\n if (errorMsg) console.log(`\\n\\x1B[31mError: ${errorMsg}\\x1B[0m`);\n });\n if (assistantContent)\n conversationMessages.push({ role: 'assistant', content: assistantContent });\n console.log('\\n');\n } catch (error) {\n console.log(\n `\\n\\x1B[31mError: ${error instanceof Error ? error.message : error}\\x1B[0m\\n`\n );\n }\n\n prompt();\n });\n };\n\n rl.on('close', () => {\n console.log('\\nGoodbye!');\n resolve();\n });\n prompt();\n });\n}\n\n// ─── Shared helpers for realtime modes ───────────────────────────────────────\n\nexport function buildHistory(messages: any[]): ChatItem[] {\n const history: ChatItem[] = [];\n for (const msg of messages.slice(-30)) {\n const text = typeof msg.content === 'string' ? msg.content : '';\n if (msg.role === 'user' || msg.role === 'assistant') {\n if (text.trim()) {\n history.push({ role: msg.role, content: text });\n }\n if (msg.role === 'assistant' && msg.tool_calls) {\n for (const tc of msg.tool_calls) {\n history.push({\n kind: 'tool_call',\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments || '',\n done: true,\n });\n }\n }\n } else if (msg.role === 'tool') {\n const toolName = (msg as any).name || 'tool';\n history.push({\n kind: 'tool_result',\n toolCallId: (msg as any).tool_call_id || '',\n toolName,\n content: text,\n });\n }\n }\n return history;\n}\n\nexport function wireRealtimeEvents(client: RealtimeClient, tui: ChatTUI): void {\n client.on('text_start', () => tui.streamStart());\n client.on('text_delta', (data: any) => tui.streamDelta(data.delta));\n client.on('text_end', () => tui.streamEnd());\n\n client.on('tool_call_start', (data: any) => {\n tui.toolCallStart(data.toolCallId, data.toolCallName);\n });\n client.on('tool_call_args', (data: any) => {\n tui.toolCallArgs(data.toolCallId, data.delta);\n });\n client.on('tool_call_end', (data: any) => {\n tui.toolCallEnd(data.toolCallId);\n });\n client.on('tool_call_result', (data: any) => {\n const toolName = tui.findToolCallName(data.toolCallId);\n const content = typeof data.result === 'string' ? data.result : JSON.stringify(data.result);\n tui.toolCallResult(data.toolCallId, toolName, content);\n });\n\n client.on('run_error', (data: any) => {\n tui.showError(data.message);\n });\n\n client.on('error', (err: Error) => {\n tui.showError(`Connection: ${err.message}`);\n });\n\n client.on('ws_recv', (msg: any) => tui.logDebug('in', msg));\n client.on('ws_send', (msg: any) => tui.logDebug('out', msg));\n}\n\n// ─── Realtime text mode (WebSocket + TUI) ────────────────────────────────────\n\nasync function realtimeChatSession(\n session: ChatSession,\n vad: 'client' | 'server',\n debug: boolean\n): Promise<void> {\n const client = new RealtimeClient({\n url: session.wsUrl,\n token: session.ctx.accessToken,\n chatId: session.chatId,\n vadMode: vad,\n debug,\n });\n\n process.stderr.write(`Connecting to ${session.label.toLowerCase()}...\\n`);\n\n try {\n await client.connect();\n } catch (err) {\n throw new CLIError(`Failed to connect: ${err instanceof Error ? err.message : err}`);\n }\n\n const existingMessages = await session.loadMessages();\n const history = buildHistory(existingMessages);\n\n const tui = new ChatTUI({\n onSend: (text) => {\n client.sendTextMessage(text);\n },\n onExit: () => {\n client.close();\n },\n debug,\n env: session.ctx.env,\n });\n\n wireRealtimeEvents(client, tui);\n\n client.on('closed', () => {\n tui.stop();\n console.log('Disconnected.');\n });\n\n tui.loadHistory(history);\n tui.start();\n\n await new Promise<void>((resolve) => {\n client.once('closed', resolve);\n });\n}\n\n// ─── Voice mode (WebSocket + mic + speaker + TUI) ────────────────────────────\n\nasync function voiceChatSession(\n session: ChatSession,\n vad: 'client' | 'server',\n args: Record<string, string | boolean | undefined>,\n debug: boolean\n): Promise<void> {\n if (!checkSoxAvailable()) {\n throw new CLIError(\n 'Voice mode requires SoX. Install it:\\n' +\n ' macOS: brew install sox\\n' +\n ' Linux: apt install sox\\n' +\n ' Windows: choco install sox'\n );\n }\n\n const inputDeviceName =\n typeof args['input-device'] === 'string' ? args['input-device'] : undefined;\n const outputDeviceName =\n typeof args['output-device'] === 'string' ? args['output-device'] : undefined;\n\n let inputDeviceId: string | undefined;\n let outputDeviceId: string | undefined;\n\n if (!inputDeviceName || !outputDeviceName) {\n process.stderr.write('\\n Audio Devices\\n');\n }\n\n if (inputDeviceName) {\n inputDeviceId = inputDeviceName;\n } else {\n const inputDevices = await listInputDevices();\n const selected = await selectDevice(inputDevices, 'Input (microphone)');\n inputDeviceId = selected.id;\n }\n\n if (outputDeviceName) {\n outputDeviceId = outputDeviceName;\n } else {\n const outputDevices = await listOutputDevices();\n const selected = await selectDevice(outputDevices, 'Output (speaker)');\n outputDeviceId = selected.id;\n }\n\n const client = new RealtimeClient({\n url: session.wsUrl,\n token: session.ctx.accessToken,\n chatId: session.chatId,\n vadMode: vad,\n debug,\n });\n\n process.stderr.write(`\\nConnecting to ${session.label.toLowerCase()}...\\n`);\n\n try {\n await client.connect();\n } catch (err) {\n throw new CLIError(`Failed to connect: ${err instanceof Error ? err.message : err}`);\n }\n\n const existingMessages = await session.loadMessages();\n const history = buildHistory(existingMessages);\n\n const mic = new MicCapture((pcm16) => {\n if (!client.isConnected()) return;\n client.sendAudio(pcm16);\n });\n const player = new AudioPlayer(outputDeviceId);\n\n function cleanup(): void {\n mic.stop();\n player.stop();\n client.close();\n }\n\n const tui = new ChatTUI({\n onSend: (text) => {\n client.sendTextMessage(text);\n },\n onExit: () => {\n cleanup();\n },\n debug,\n env: session.ctx.env,\n });\n\n wireRealtimeEvents(client, tui);\n\n client.on('audio', (data: any) => {\n player.write(data.pcm16);\n });\n\n client.on('audio_end', (data: any) => {\n player.endResponse(data?.messageId);\n });\n\n client.on('interrupt', () => {\n const playbackMs = player.getPlaybackTimeMs();\n const messageId = player.playingMessageId;\n\n if (playbackMs !== null && playbackMs > 0 && player.isPlaying) {\n client.sendInterrupt(playbackMs, messageId);\n player.stop();\n\n if (debug) {\n tui.logDebug('in', {\n type: 'CUSTOM',\n name: 'voice.interrupt',\n value: { action: 'echoed', audioEndMs: playbackMs, messageId },\n });\n }\n } else if (debug) {\n tui.logDebug('in', {\n type: 'CUSTOM',\n name: 'voice.interrupt',\n value: { action: 'ignored', wasPlaying: player.isPlaying },\n });\n }\n });\n\n client.on('truncate', (data: any) => {\n player.stop();\n tui.truncateAssistant(\n data.content ?? '',\n data.originalContent,\n data.truncationReason ?? 'barge_in',\n data.truncatedAtMs\n );\n });\n\n client.on('response_message', (data: any) => {\n if (data.role === 'user' && data.content) {\n tui.addTranscription(data.content);\n }\n });\n\n client.on('closed', () => {\n tui.stop();\n cleanup();\n console.log('Disconnected.');\n });\n\n tui.loadHistory(history);\n tui.start();\n\n mic.start(inputDeviceId);\n\n await new Promise<void>((resolve) => {\n client.once('closed', resolve);\n });\n}\n\n// ─── Device listing ──────────────────────────────────────────────────────────\n\nexport async function listAudioDevices(): Promise<void> {\n if (!checkSoxAvailable()) {\n throw new CLIError(\n 'Device listing requires SoX. Install it:\\n' +\n ' macOS: brew install sox\\n' +\n ' Linux: apt install sox\\n' +\n ' Windows: choco install sox'\n );\n }\n\n const inputs = await listInputDevices();\n const outputs = await listOutputDevices();\n\n console.log('Input devices (microphone):');\n for (const dev of inputs) {\n const marker = dev.isDefault ? ' (default)' : '';\n console.log(` ${dev.id}: ${dev.name}${marker}`);\n }\n\n console.log('\\nOutput devices (speaker):');\n for (const dev of outputs) {\n const marker = dev.isDefault ? ' (default)' : '';\n console.log(` ${dev.id}: ${dev.name}${marker}`);\n }\n}\n","/**\n * WebSocket-based AG-UI Realtime Client for CLI\n *\n * Handles the AG-UI protocol over WebSocket for realtime voice and text\n * interactions with the Workspace Manager. Adapted from the browser\n * implementation in src/components/voice/ws-unified.ts.\n *\n * Uses the native WebSocket global (Node.js 22+).\n */\n\nimport { EventEmitter } from 'events';\n\n// AG-UI event format over WebSocket\ninterface AGUIWebSocketEvent {\n type: string;\n name?: string;\n value?: any;\n messageId?: string;\n delta?: string;\n role?: string;\n message?: string;\n code?: string;\n toolCallId?: string;\n toolCallName?: string;\n [key: string]: any;\n}\n\nexport interface RealtimeClientOptions {\n /** WebSocket URL (wss://...) */\n url: string;\n /** JWT access token for authentication */\n token: string;\n /** Chat ID to connect to (null to create a new chat) */\n chatId: number | null;\n /** VAD mode: 'server' (default) or 'client' */\n vadMode?: 'client' | 'server';\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * Realtime WebSocket client for AG-UI protocol.\n *\n * Events:\n * - connected: Login success with chat/member/assistant IDs\n * - audio: Received audio PCM16 buffer\n * - text_start/text_delta/text_end: Streaming text message\n * - transcription: User speech transcription\n * - response_message: Full message object\n * - tool_call_start/tool_call_args/tool_call_end: Tool calls\n * - run_error: Run error from server\n * - error: Connection/protocol error\n * - closed: WebSocket closed\n */\nexport class RealtimeClient extends EventEmitter {\n private ws: WebSocket | null = null;\n private connected = false;\n private options: Required<RealtimeClientOptions>;\n\n constructor(options: RealtimeClientOptions) {\n super();\n this.options = {\n vadMode: 'server',\n debug: false,\n ...options,\n };\n }\n\n /** Connect to the realtime WebSocket endpoint */\n connect(): Promise<void> {\n if (typeof globalThis.WebSocket === 'undefined') {\n return Promise.reject(\n new Error('WebSocket not available. Node.js 22+ is required for realtime mode.')\n );\n }\n\n return new Promise((resolve, reject) => {\n const params = new URLSearchParams();\n if (this.options.vadMode) {\n params.append('vad', this.options.vadMode);\n }\n const url = params.toString()\n ? `${this.options.url}?${params.toString()}`\n : this.options.url;\n\n if (this.options.debug) {\n process.stderr.write(`[debug] Connecting to ${url}\\n`);\n }\n\n this.ws = new WebSocket(url);\n\n this.ws.onerror = (event: Event) => {\n const msg = event instanceof ErrorEvent ? event.message : 'WebSocket connection failed';\n if (!this.connected) {\n reject(new Error(msg));\n } else {\n this.emit('error', new Error(msg));\n }\n };\n\n this.ws.onclose = (event: CloseEvent) => {\n const reason = event.code === 1006 ? 'Connection lost' : event.reason || 'Closed';\n this.connected = false;\n this.emit('closed', { reason, code: event.code });\n };\n\n this.ws.onmessage = (event: MessageEvent) => {\n try {\n const data = typeof event.data === 'string' ? event.data : event.data.toString();\n const parsed: AGUIWebSocketEvent = JSON.parse(data);\n this.emit('ws_recv', parsed);\n this.handleEvent(parsed);\n } catch {\n if (this.options.debug) {\n process.stderr.write(`[debug] Failed to parse message\\n`);\n }\n }\n };\n\n this.ws.onopen = () => {\n if (this.options.debug) {\n process.stderr.write('[debug] WebSocket connected, sending login\\n');\n }\n this.sendCustom('voice.login', {\n token: this.options.token,\n chat_id: this.options.chatId,\n vad: this.options.vadMode,\n });\n };\n\n // Wait for login_success or timeout\n const timeout = setTimeout(() => {\n if (!this.connected) {\n this.close();\n reject(new Error('Connection timeout - no login response within 10s'));\n }\n }, 10000);\n\n this.once('connected', () => {\n clearTimeout(timeout);\n resolve();\n });\n\n this.once('error', () => {\n clearTimeout(timeout);\n });\n });\n }\n\n private handleEvent(event: AGUIWebSocketEvent): void {\n switch (event.type) {\n case 'CUSTOM':\n this.handleCustomEvent(event.name || '', event.value);\n break;\n\n case 'TEXT_MESSAGE_START':\n this.emit('text_start', { messageId: event.messageId || '' });\n break;\n case 'TEXT_MESSAGE_CONTENT':\n this.emit('text_delta', {\n messageId: event.messageId || '',\n delta: event.delta || '',\n });\n break;\n case 'TEXT_MESSAGE_END':\n this.emit('text_end', { messageId: event.messageId || '' });\n break;\n\n case 'TOOL_CALL_START':\n this.emit('tool_call_start', {\n toolCallId: event.toolCallId || '',\n toolCallName: event.toolCallName || '',\n });\n break;\n case 'TOOL_CALL_ARGS':\n this.emit('tool_call_args', {\n toolCallId: event.toolCallId || '',\n delta: event.delta || '',\n });\n break;\n case 'TOOL_CALL_END':\n this.emit('tool_call_end', { toolCallId: event.toolCallId || '' });\n break;\n case 'TOOL_CALL_RESULT':\n this.emit('tool_call_result', {\n toolCallId: event.toolCallId || '',\n result: event.result,\n });\n break;\n\n case 'RUN_STARTED':\n this.emit('run_started', { runId: event.runId });\n break;\n case 'RUN_FINISHED':\n this.emit('run_finished', { runId: event.runId });\n break;\n case 'RUN_ERROR':\n this.emit('run_error', {\n message: event.message || 'Unknown error',\n code: event.code,\n });\n break;\n\n default:\n if (this.options.debug) {\n process.stderr.write(`[debug] Unknown event type: ${event.type}\\n`);\n }\n }\n }\n\n private handleCustomEvent(name: string, value: any): void {\n switch (name) {\n case 'voice.login_success':\n this.connected = true;\n this.emit('connected', {\n chatId: value?.chat_id,\n memberId: value?.member_id,\n assistantId: value?.assistant_id,\n });\n break;\n\n case 'voice.audio':\n if (value?.data) {\n const pcm16 = Buffer.from(value.data, 'base64');\n this.emit('audio', { pcm16, messageId: value.message_id });\n }\n break;\n\n case 'voice.audio_begin':\n this.emit('audio_begin', { messageId: value?.message_id });\n break;\n case 'voice.audio_end':\n this.emit('audio_end', { messageId: value?.message_id });\n break;\n\n case 'voice.interrupt':\n this.emit('interrupt', { messageId: value?.message_id });\n break;\n\n case 'voice.response_message':\n if (value) {\n this.emit('response_message', value);\n }\n break;\n\n case 'voice.transcription':\n if (value) {\n this.emit('transcription', { text: value.text, role: value.role });\n }\n break;\n\n case 'voice.truncate':\n if (value) {\n this.emit('truncate', {\n messageId: value.message_id,\n content: value.content,\n originalContent: value.original_content,\n truncationReason: value.truncation_reason || 'barge_in',\n truncatedAtMs: value.audio_end_ms,\n });\n }\n break;\n\n case 'app.data_update':\n case 'app.navigation':\n case 'app.notification':\n break;\n\n default:\n if (this.options.debug) {\n process.stderr.write(`[debug] Unknown CUSTOM event: ${name}\\n`);\n }\n }\n }\n\n private sendCustom(name: string, value?: any): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n return;\n }\n const event: AGUIWebSocketEvent = { type: 'CUSTOM', name };\n if (value !== undefined) {\n event.value = value;\n }\n this.emit('ws_send', event);\n this.ws.send(JSON.stringify(event));\n }\n\n /** Send raw PCM16 audio data (will be base64-encoded) */\n sendAudio(pcm16: Buffer): void {\n this.sendCustom('voice.audio', {\n data: pcm16.toString('base64'),\n format: 'pcm16',\n sample_rate: 24000,\n });\n }\n\n /** Signal the start of an audio utterance */\n sendAudioBegin(messageId: string): void {\n this.sendCustom('voice.audio_begin', { message_id: messageId });\n }\n\n /** Signal the end of an audio utterance */\n sendAudioEnd(): void {\n this.sendCustom('voice.audio_end');\n }\n\n /** Send a text message (triggers AI inference) */\n sendTextMessage(content: string): void {\n this.sendCustom('voice.user_message', {\n message: { role: 'user', content },\n });\n }\n\n /** Send interrupt signal with playback position */\n sendInterrupt(audioEndMs: number, messageId?: string): void {\n this.sendCustom('voice.interrupt', {\n audio_end_ms: audioEndMs,\n message_id: messageId,\n });\n }\n\n /** Check if the client is connected */\n isConnected(): boolean {\n return this.connected && this.ws?.readyState === WebSocket.OPEN;\n }\n\n /** Close the connection */\n close(): void {\n this.connected = false;\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n }\n}\n","/**\n * Chat TUI — terminal chat interface using ANSI escape codes.\n *\n * Layout (normal):\n * Rows 1..R-2: Message area (full width)\n * Row R-1: Separator + hints\n * Row R: Input (\"You: ...\")\n *\n * Layout (debug):\n * Rows 1..R-2: Chat (left) │ Debug log (right)\n * Row R-1: Separator + hints\n * Row R: Input (\"You: ...\")\n *\n * Keyboard:\n * Up/Down Scroll 1 line\n * Page Up/Down Scroll 1 page\n * Ctrl+B Page up (less-style)\n * Ctrl+F Page down (less-style)\n * Home/End Top / bottom\n * Ctrl+O Toggle detail expansion (tool calls + debug messages)\n * Ctrl+D Toggle debug panel (when --debug)\n * Ctrl+C / exit Quit\n *\n * Mouse:\n * Scroll wheel Scroll 3 lines\n *\n * Zero external dependencies — only Node.js built-ins.\n */\n\nimport { createWriteStream, type WriteStream } from 'fs';\n\n// ─── Public types ─────────────────────────────────────────────────────────────\n\nexport interface ChatMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n /** Reason the message was truncated (voice interruption) */\n truncationReason?: string;\n /** Ms offset where truncation occurred */\n truncatedAtMs?: number;\n /** The full original content before truncation */\n originalContent?: string;\n}\n\nexport interface ChatTUIOptions {\n /** Called when the user sends a message */\n onSend: (text: string) => void;\n /** Called when the user exits (Ctrl+C, 'exit', 'quit') */\n onExit: () => void;\n /** Enable debug panel showing WebSocket traffic */\n debug?: boolean;\n /** Environment name (e.g. 'dev', 'staging', 'prod') — controls debug log file creation */\n env?: string;\n}\n\n// ─── Item types ───────────────────────────────────────────────────────────────\n\nexport interface ToolCallItem {\n kind: 'tool_call';\n id: string;\n name: string;\n args: string;\n done: boolean;\n}\n\nexport interface ToolResultItem {\n kind: 'tool_result';\n toolCallId: string;\n toolName: string;\n content: string;\n}\n\nexport type ChatItem = ChatMessage | ToolCallItem | ToolResultItem;\n\nfunction isToolCall(item: ChatItem): item is ToolCallItem {\n return 'kind' in item && (item as ToolCallItem).kind === 'tool_call';\n}\n\nfunction isToolResult(item: ChatItem): item is ToolResultItem {\n return 'kind' in item && (item as ToolResultItem).kind === 'tool_result';\n}\n\n/** Friendly label for truncation reason */\nfunction getTruncationLabel(reason: string, truncatedAtMs?: number): string {\n const timeStr = truncatedAtMs ? ` at ${(truncatedAtMs / 1000).toFixed(1)}s` : '';\n switch (reason) {\n case 'barge_in':\n return `interrupted: user spoke${timeStr}`;\n case 'client_interrupt':\n return `interrupted${timeStr}`;\n case 'user_cancel':\n return `cancelled by user${timeStr}`;\n case 'error':\n return `error${timeStr}`;\n default:\n return `interrupted${timeStr}`;\n }\n}\n\n/** Extract the unspoken portion of a truncated message */\nfunction getExtraContent(\n content: string | undefined,\n originalContent: string | undefined\n): string | null {\n if (!content || !originalContent) return null;\n const stripped = content.replace(/—interrupted$/, '');\n if (originalContent.startsWith(stripped)) {\n const extra = originalContent.slice(stripped.length);\n return extra.length > 0 ? extra : null;\n }\n return originalContent !== content ? originalContent : null;\n}\n\n// ─── Debug log entry ──────────────────────────────────────────────────────────\n\ninterface DebugEntry {\n direction: 'in' | 'out';\n summary: string; // one-line summary (always shown)\n detail: string; // full JSON (shown when expanded)\n ts: string; // HH:MM:SS\n}\n\n// ─── ANSI helpers ─────────────────────────────────────────────────────────────\n\nconst CSI = '\\x1B[';\nconst HIDE_CURSOR = `${CSI}?25l`;\nconst SHOW_CURSOR = `${CSI}?25h`;\nconst ALT_SCREEN_ON = `${CSI}?1049h`;\nconst ALT_SCREEN_OFF = `${CSI}?1049l`;\nconst CLEAR_EOL = `${CSI}K`;\nconst RESET = `${CSI}0m`;\nconst MOUSE_ON = `${CSI}?1000h${CSI}?1006h`; // Button events + SGR extended\nconst MOUSE_OFF = `${CSI}?1000l${CSI}?1006l`;\n\nconst BLUE = `${CSI}34m`;\nconst GREEN = `${CSI}32m`;\nconst GRAY = `${CSI}90m`;\nconst YELLOW = `${CSI}33m`;\nconst ORANGE = `${CSI}38;5;208m`; // 256-color orange — inbound\nconst LIGHT_BLUE = `${CSI}38;5;117m`; // 256-color light blue — outbound\nconst DIM = `${CSI}2m`;\nconst DIM_ITALIC_GRAY = `${CSI}2;3;90m`; // dim + italic + gray\n\nfunction moveTo(row: number, col: number): string {\n return `${CSI}${row};${col}H`;\n}\n\n// ─── ChatTUI ──────────────────────────────────────────────────────────────────\n\nexport class ChatTUI {\n private items: ChatItem[] = [];\n private inputBuffer = '';\n private isStreaming = false;\n private streamContent = '';\n private scrollOffset = 0;\n private expandDetails = false;\n private rows = 24;\n private cols = 80;\n private started = false;\n private renderTimer: ReturnType<typeof setTimeout> | null = null;\n private displayLinesCache: string[] | null = null;\n private debugLinesCache: string[] | null = null;\n private options: ChatTUIOptions;\n\n // Debug panel state\n private debugEntries: DebugEntry[] = [];\n private debugPanelVisible = false;\n private debugLogStream: WriteStream | null = null;\n\n // Escape sequence accumulator for raw stdin parsing\n private escBuf = '';\n private escTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(options: ChatTUIOptions) {\n this.options = options;\n this.debugPanelVisible = !!options.debug;\n }\n\n /** Whether the debug panel is currently being rendered */\n private get debugVisible(): boolean {\n return this.debugPanelVisible;\n }\n\n // ─── Lifecycle ──────────────────────────────────────────────────────\n\n start(): void {\n this.updateDimensions();\n process.stdout.write(ALT_SCREEN_ON + MOUSE_ON);\n process.stdout.write(`${CSI}1;${Math.max(1, this.rows - 2)}r`);\n\n // Raw mode + direct data handler (not readline — we parse escape seqs ourselves)\n process.stdin.setEncoding('utf8');\n if (process.stdin.isTTY) process.stdin.setRawMode(true);\n process.stdin.on('data', this.onData);\n process.stdin.resume();\n\n process.stdout.on('resize', this.onResize);\n process.on('exit', this.restoreTerminal);\n\n // Debug log file — only write to disk in dev/staging (never in prod to avoid PHI on disk)\n if (this.options.debug && this.options.env !== 'prod') {\n this.debugLogStream = createWriteStream('gr-cli-realtime-debug.log', { flags: 'a' });\n this.debugLogStream.write(`\\n--- session ${new Date().toISOString()} ---\\n`);\n }\n\n this.started = true;\n this.render();\n }\n\n stop(): void {\n if (!this.started) return;\n this.started = false;\n if (this.renderTimer) {\n clearTimeout(this.renderTimer);\n this.renderTimer = null;\n }\n this.clearEsc();\n if (this.debugLogStream) {\n this.debugLogStream.end();\n this.debugLogStream = null;\n }\n this.restoreTerminal();\n process.stdout.removeListener('resize', this.onResize);\n process.stdin.removeListener('data', this.onData);\n if (process.stdin.isTTY) process.stdin.setRawMode(false);\n process.stdin.pause();\n process.removeListener('exit', this.restoreTerminal);\n }\n\n // ─── Chat state ────────────────────────────────────────────────────\n\n loadHistory(items: ChatItem[]): void {\n this.items = items.filter((item) => (isToolCall(item) ? true : item.content?.trim()));\n this.dirty();\n }\n\n streamStart(): void {\n this.isStreaming = true;\n this.streamContent = '';\n this.scrollOffset = 0;\n this.dirty();\n }\n\n streamDelta(delta: string): void {\n this.streamContent += delta;\n this.dirty();\n }\n\n streamEnd(): void {\n if (this.streamContent.trim()) {\n this.items.push({ role: 'assistant', content: this.streamContent });\n }\n this.isStreaming = false;\n this.streamContent = '';\n this.dirty();\n }\n\n toolCallStart(id: string, name: string): void {\n this.items.push({ kind: 'tool_call', id, name, args: '', done: false });\n this.dirty();\n }\n\n toolCallArgs(id: string, delta: string): void {\n const tc = this.findToolCall(id);\n if (tc) {\n tc.args += delta;\n this.dirty();\n }\n }\n\n toolCallEnd(id: string): void {\n const tc = this.findToolCall(id);\n if (tc) {\n tc.done = true;\n this.dirty();\n }\n }\n\n /** Add a transcription of the user's spoken words (voice mode) */\n addTranscription(text: string): void {\n this.items.push({ role: 'user', content: text });\n this.scrollOffset = 0;\n this.dirty();\n }\n\n /**\n * Truncate the most recent assistant message (voice interruption).\n * Replaces its content with the spoken portion and stores the original.\n */\n truncateAssistant(\n content: string,\n originalContent: string | undefined,\n reason: string,\n truncatedAtMs?: number\n ): void {\n // If currently streaming, commit the stream first\n if (this.isStreaming) {\n this.isStreaming = false;\n this.streamContent = '';\n }\n\n // Find the last assistant message and update it\n for (let i = this.items.length - 1; i >= 0; i--) {\n const item = this.items[i]!;\n if ('role' in item && item.role === 'assistant') {\n item.content = content;\n item.truncationReason = reason;\n item.truncatedAtMs = truncatedAtMs;\n item.originalContent = originalContent;\n this.dirty();\n return;\n }\n }\n\n // No existing assistant message — push the truncated content\n this.items.push({\n role: 'assistant',\n content,\n truncationReason: reason,\n truncatedAtMs: truncatedAtMs,\n originalContent,\n });\n this.dirty();\n }\n\n toolCallResult(toolCallId: string, toolName: string, content: string): void {\n this.items.push({ kind: 'tool_result', toolCallId, toolName, content });\n this.dirty();\n }\n\n /** Find the tool name for a given tool call ID */\n findToolCallName(toolCallId: string): string {\n for (let i = this.items.length - 1; i >= 0; i--) {\n const item = this.items[i]!;\n if (isToolCall(item) && item.id === toolCallId) return item.name;\n }\n return 'tool';\n }\n\n showError(msg: string): void {\n this.items.push({ role: 'system', content: `Error: ${msg}` });\n this.dirty();\n }\n\n // ─── Debug panel ──────────────────────────────────────────────────\n\n /** Log a WebSocket message to the debug panel and (optionally) log file */\n logDebug(direction: 'in' | 'out', raw: any): void {\n const redacted = redactAudio(raw);\n const now = new Date();\n const ts = `${pad2(now.getHours())}:${pad2(now.getMinutes())}:${pad2(now.getSeconds())}`;\n\n // Write to log file (JSON lines, with full redacted payload)\n if (this.debugLogStream) {\n const logLine = JSON.stringify({ ts: now.toISOString(), dir: direction, ...redacted });\n this.debugLogStream.write(logLine + '\\n');\n }\n\n // Add to in-memory debug panel\n const summary = buildDebugSummary(direction, redacted);\n let detail: string;\n try {\n detail = JSON.stringify(redacted, null, 2);\n } catch {\n detail = String(redacted);\n }\n this.debugEntries.push({ direction, summary, detail, ts });\n // Cap at 500 entries to prevent memory growth\n if (this.debugEntries.length > 500) {\n this.debugEntries = this.debugEntries.slice(-300);\n }\n this.debugLinesCache = null;\n this.dirty();\n }\n\n // ─── Private helpers ──────────────────────────────────────────────\n\n private findToolCall(id: string): ToolCallItem | undefined {\n for (let i = this.items.length - 1; i >= 0; i--) {\n const item = this.items[i]!;\n if (isToolCall(item) && item.id === id) return item;\n }\n return undefined;\n }\n\n private dirty(): void {\n this.displayLinesCache = null;\n this.debugLinesCache = null;\n this.scheduleRender();\n }\n\n private restoreTerminal = (): void => {\n process.stdout.write(`${MOUSE_OFF}${CSI}r${ALT_SCREEN_OFF}${SHOW_CURSOR}`);\n };\n\n private updateDimensions(): void {\n this.rows = process.stdout.rows || 24;\n this.cols = process.stdout.columns || 80;\n }\n\n /** Width of the chat (left) panel */\n private chatWidth(): number {\n if (!this.debugVisible) return this.cols;\n // 60% for chat, 40% for debug, with 1 col for divider\n return Math.max(30, Math.floor(this.cols * 0.6) - 1);\n }\n\n /** Width of the debug (right) panel */\n private debugWidth(): number {\n if (!this.debugVisible) return 0;\n return this.cols - this.chatWidth() - 1; // -1 for divider\n }\n\n private scrollHeight(): number {\n return Math.max(1, this.rows - 2);\n }\n\n private pageSize(): number {\n return Math.max(1, this.rows - 4);\n }\n\n // ─── Scroll ───────────────────────────────────────────────────────\n\n private scrollUp(lines: number): void {\n const total = this.getDisplayLines().length;\n const max = Math.max(0, total - this.scrollHeight());\n this.scrollOffset = Math.min(max, this.scrollOffset + lines);\n this.render();\n }\n\n private scrollDown(lines: number): void {\n this.scrollOffset = Math.max(0, this.scrollOffset - lines);\n this.render();\n }\n\n private scrollToTop(): void {\n const total = this.getDisplayLines().length;\n this.scrollOffset = Math.max(0, total - this.scrollHeight());\n this.render();\n }\n\n private scrollToBottom(): void {\n this.scrollOffset = 0;\n this.render();\n }\n\n // ─── Raw stdin parsing ────────────────────────────────────────────\n //\n // We parse stdin directly instead of using readline.emitKeypressEvents\n // because readline doesn't understand SGR mouse sequences and leaks\n // their contents into keypress events as regular characters.\n\n private onData = (data: string): void => {\n for (let i = 0; i < data.length; i++) {\n const ch = data[i]!;\n\n // Accumulating an escape sequence\n if (this.escBuf) {\n this.escBuf += ch;\n\n if (this.escBuf.length === 2) {\n if (ch !== '[') {\n // Not a CSI sequence (Alt+key etc.) — discard\n this.clearEsc();\n }\n continue;\n }\n\n // \\x1B[... — wait for a terminating character (letter or ~)\n if (/[A-Za-z~]/.test(ch)) {\n this.handleCSI(this.escBuf.slice(2, -1), ch);\n this.clearEsc();\n } else if (this.escBuf.length > 32) {\n this.clearEsc(); // safety bail\n }\n continue;\n }\n\n // Start of escape sequence\n if (ch === '\\x1B') {\n this.escBuf = '\\x1B';\n this.escTimer = setTimeout(() => {\n // Bare ESC with no follow-up — ignore\n this.escBuf = '';\n this.escTimer = null;\n }, 100);\n continue;\n }\n\n // Regular byte\n this.handleByte(ch);\n }\n };\n\n private clearEsc(): void {\n this.escBuf = '';\n if (this.escTimer) {\n clearTimeout(this.escTimer);\n this.escTimer = null;\n }\n }\n\n /** Handle a parsed CSI sequence: params is everything between \\x1B[ and the final char */\n private handleCSI(params: string, code: string): void {\n // Mouse SGR: \\x1B[<button;col;rowM (press) or m (release)\n if (params.startsWith('<') && (code === 'M' || code === 'm')) {\n if (code === 'm') return; // ignore button release\n const parts = params.slice(1).split(';');\n if (parts.length >= 1) {\n const button = parseInt(parts[0]!, 10);\n if (button === 64) this.scrollUp(3);\n else if (button === 65) this.scrollDown(3);\n }\n return;\n }\n\n // Arrow keys (no params)\n if (!params) {\n if (code === 'A') {\n this.scrollUp(1);\n return;\n }\n if (code === 'B') {\n this.scrollDown(1);\n return;\n }\n // Home/End (xterm-style)\n if (code === 'H') {\n this.scrollToTop();\n return;\n }\n if (code === 'F') {\n this.scrollToBottom();\n return;\n }\n }\n\n // Tilde sequences: Page Up (5~), Page Down (6~), Home (1~), End (4~)\n if (code === '~') {\n if (params === '5') {\n this.scrollUp(this.pageSize());\n return;\n }\n if (params === '6') {\n this.scrollDown(this.pageSize());\n return;\n }\n if (params === '1') {\n this.scrollToTop();\n return;\n }\n if (params === '4') {\n this.scrollToBottom();\n return;\n }\n }\n }\n\n /** Handle a single non-escape byte */\n private handleByte(ch: string): void {\n const code = ch.charCodeAt(0);\n\n // Ctrl+C → exit\n if (code === 0x03) {\n this.stop();\n this.options.onExit();\n return;\n }\n\n // Ctrl+B → page up (less-style)\n if (code === 0x02) {\n this.scrollUp(this.pageSize());\n return;\n }\n\n // Ctrl+F → page down (less-style)\n if (code === 0x06) {\n this.scrollDown(this.pageSize());\n return;\n }\n\n // Ctrl+D → toggle debug panel visibility (always available)\n if (code === 0x04) {\n this.debugPanelVisible = !this.debugPanelVisible;\n this.displayLinesCache = null;\n this.debugLinesCache = null;\n this.render();\n return;\n }\n\n // Ctrl+O → toggle detail expansion (tool calls + debug messages)\n if (code === 0x0f) {\n this.expandDetails = !this.expandDetails;\n this.displayLinesCache = null;\n this.debugLinesCache = null;\n this.render();\n return;\n }\n\n // Enter\n if (code === 0x0d) {\n this.handleEnter();\n return;\n }\n\n // Backspace (0x7F on most terminals, 0x08 on some)\n if (code === 0x7f || code === 0x08) {\n if (this.inputBuffer.length > 0) {\n this.inputBuffer = this.inputBuffer.slice(0, -1);\n this.renderInputLine();\n }\n return;\n }\n\n // Ignore other control characters\n if (code < 0x20) return;\n\n // Printable character → add to input\n this.inputBuffer += ch;\n this.renderInputLine();\n }\n\n private handleEnter(): void {\n const text = this.inputBuffer.trim();\n this.inputBuffer = '';\n if (!text) {\n this.renderInputLine();\n return;\n }\n if (text.toLowerCase() === 'exit' || text.toLowerCase() === 'quit') {\n this.stop();\n this.options.onExit();\n return;\n }\n this.items.push({ role: 'user', content: text });\n this.scrollOffset = 0;\n this.displayLinesCache = null;\n this.render();\n this.options.onSend(text);\n }\n\n // ─── Events ───────────────────────────────────────────────────────\n\n private onResize = (): void => {\n this.updateDimensions();\n process.stdout.write(`${CSI}1;${Math.max(1, this.rows - 2)}r`);\n this.displayLinesCache = null;\n this.debugLinesCache = null;\n this.render();\n };\n\n // ─── Rendering ────────────────────────────────────────────────────\n\n private scheduleRender(): void {\n if (!this.started || this.renderTimer) return;\n this.renderTimer = setTimeout(() => {\n this.renderTimer = null;\n this.render();\n }, 30);\n }\n\n private getDisplayLines(): string[] {\n if (!this.displayLinesCache) {\n this.displayLinesCache = this.buildDisplayLines();\n }\n return this.displayLinesCache;\n }\n\n private getDebugLines(): string[] {\n if (!this.debugLinesCache) {\n this.debugLinesCache = this.buildDebugLines();\n }\n return this.debugLinesCache;\n }\n\n private render(): void {\n if (!this.started) return;\n this.updateDimensions();\n\n const sh = this.scrollHeight();\n const displayLines = this.getDisplayLines();\n const total = displayLines.length;\n\n // Clamp scroll offset\n const maxOff = Math.max(0, total - sh);\n if (this.scrollOffset > maxOff) this.scrollOffset = maxOff;\n\n // Select visible slice for chat\n let visible: string[];\n if (total <= sh) {\n visible = [...new Array<string>(sh - total).fill(''), ...displayLines];\n } else {\n const end = total - this.scrollOffset;\n const start = end - sh;\n visible = displayLines.slice(start, end);\n }\n\n const buf: string[] = [HIDE_CURSOR];\n\n if (this.debugVisible) {\n this.renderSplitScreen(buf, visible, sh);\n } else {\n for (let i = 0; i < sh; i++) {\n buf.push(moveTo(i + 1, 1), visible[i] || '', CLEAR_EOL);\n }\n }\n\n // Separator with hints (row R-1)\n buf.push(moveTo(this.rows - 1, 1), this.buildSeparator(), CLEAR_EOL);\n\n // Input (row R)\n buf.push(moveTo(this.rows, 1), `${BLUE}You:${RESET} ${this.inputBuffer}${CLEAR_EOL}`);\n\n buf.push(SHOW_CURSOR);\n process.stdout.write(buf.join(''));\n }\n\n private renderSplitScreen(buf: string[], chatVisible: string[], sh: number): void {\n const cw = this.chatWidth();\n const dw = this.debugWidth();\n const divCol = cw + 1;\n\n // Debug panel: auto-scroll to bottom (always show latest)\n const debugLines = this.getDebugLines();\n const debugTotal = debugLines.length;\n let debugVisible: string[];\n if (debugTotal <= sh) {\n debugVisible = [...new Array<string>(sh - debugTotal).fill(''), ...debugLines];\n } else {\n debugVisible = debugLines.slice(debugTotal - sh);\n }\n\n for (let i = 0; i < sh; i++) {\n const chatLine = truncateAnsi(chatVisible[i] || '', cw);\n const debugLine = truncateAnsi(debugVisible[i] || '', dw);\n buf.push(\n moveTo(i + 1, 1),\n chatLine,\n CLEAR_EOL, // clear to end handles rest, but we need to position divider\n moveTo(i + 1, divCol),\n `${DIM}\\u2502${RESET}`,\n debugLine\n );\n // Clear remainder of the debug area\n buf.push(CLEAR_EOL);\n }\n }\n\n private renderInputLine(): void {\n process.stdout.write(\n `${moveTo(this.rows, 1)}${BLUE}You:${RESET} ${this.inputBuffer}${CLEAR_EOL}`\n );\n }\n\n // ─── Separator ────────────────────────────────────────────────────\n\n private buildSeparator(): string {\n const hints: string[] = [];\n\n if (this.scrollOffset > 0) {\n hints.push(`\\u2191${this.scrollOffset}`);\n }\n\n const hasDetails =\n this.items.some((i) => isToolCall(i) || isToolResult(i)) || this.options.debug;\n if (hasDetails) {\n hints.push(`^O ${this.expandDetails ? 'collapse' : 'details'}`);\n }\n\n if (this.options.debug) {\n hints.push(`^D ${this.debugPanelVisible ? 'hide' : 'show'} debug`);\n }\n\n const lineWidth = Math.min(this.cols, 60);\n\n if (!hints.length) {\n return `${GRAY}${'\\u2500'.repeat(lineWidth)}${RESET}`;\n }\n\n const hintStr = ` ${hints.join(' ')} `;\n const dashes = Math.max(0, lineWidth - hintStr.length);\n const left = Math.max(2, Math.floor(dashes / 2));\n const right = Math.max(2, dashes - left);\n return `${GRAY}${'\\u2500'.repeat(left)}${hintStr}${'\\u2500'.repeat(right)}${RESET}`;\n }\n\n // ─── Chat display line building ───────────────────────────────────\n\n private buildDisplayLines(): string[] {\n const lines: string[] = [];\n const w = this.chatWidth();\n\n for (const item of this.items) {\n if (isToolCall(item)) {\n this.appendToolCallLines(lines, item, w);\n } else if (isToolResult(item)) {\n this.appendToolResultLines(lines, item, w);\n } else {\n this.appendMessageLines(lines, item, w);\n }\n lines.push('');\n }\n\n if (this.isStreaming) {\n this.appendStreamLines(lines, w);\n }\n\n return lines;\n }\n\n private appendToolCallLines(lines: string[], tc: ToolCallItem, width: number): void {\n const status = tc.done ? 'Called' : 'Calling';\n const summary = ` ${GRAY}${status} ${tc.name}${tc.done ? '' : '...'}${RESET}`;\n\n if (!this.expandDetails) {\n lines.push(summary);\n return;\n }\n\n lines.push(summary);\n if (tc.args) {\n let formatted = tc.args;\n try {\n formatted = JSON.stringify(JSON.parse(tc.args), null, 2);\n } catch {\n // use raw\n }\n const indent = ' ';\n for (const argLine of formatted.split('\\n')) {\n for (const wl of this.wrapText(argLine, width - indent.length)) {\n lines.push(`${indent}${GRAY}${wl}${RESET}`);\n }\n }\n }\n }\n\n private appendToolResultLines(lines: string[], tr: ToolResultItem, width: number): void {\n if (!this.expandDetails) {\n // Collapsed: show truncated one-liner\n const maxLen = width - 10;\n const preview = tr.content.replace(/\\n/g, ' ').slice(0, maxLen);\n const truncated = preview.length < tr.content.length ? '...' : '';\n lines.push(` ${GRAY}\\u2192 ${tr.toolName}: ${preview}${truncated}${RESET}`);\n return;\n }\n\n lines.push(` ${GRAY}\\u2192 ${tr.toolName} result:${RESET}`);\n let formatted = tr.content;\n try {\n formatted = JSON.stringify(JSON.parse(tr.content), null, 2);\n } catch {\n // use raw\n }\n const indent = ' ';\n for (const resultLine of formatted.split('\\n')) {\n for (const wl of this.wrapText(resultLine, width - indent.length)) {\n lines.push(`${indent}${GRAY}${wl}${RESET}`);\n }\n }\n }\n\n private appendMessageLines(lines: string[], msg: ChatMessage, width: number): void {\n if (msg.role === 'system') {\n for (const para of msg.content.split('\\n')) {\n for (const wl of this.wrapText(para, width - 2)) {\n lines.push(` ${GRAY}${wl}${RESET}`);\n }\n }\n return;\n }\n\n const isUser = msg.role === 'user';\n const label = isUser ? `${BLUE}You:${RESET} ` : `${GREEN}Assistant:${RESET} `;\n const labelWidth = isUser ? 5 : 12;\n const indent = ' '.repeat(labelWidth);\n let first = true;\n\n // Strip the \"—interrupted\" suffix from content for display\n const displayContent = msg.truncationReason\n ? msg.content.replace(/—interrupted$/, '')\n : msg.content;\n\n for (const para of displayContent.split('\\n')) {\n for (const wl of this.wrapText(para, width - labelWidth)) {\n lines.push(first ? label + wl : indent + wl);\n first = false;\n }\n }\n\n // Truncation indicator\n if (msg.truncationReason) {\n const reasonLabel = getTruncationLabel(msg.truncationReason, msg.truncatedAtMs);\n lines.push(`${indent}${YELLOW}[${reasonLabel}]${RESET}`);\n\n // Show unspoken text in dim italic gray\n const extra = getExtraContent(msg.content, msg.originalContent);\n if (extra) {\n for (const para of extra.split('\\n')) {\n for (const wl of this.wrapText(para, width - labelWidth)) {\n lines.push(`${indent}${DIM_ITALIC_GRAY}${wl}${RESET}`);\n }\n }\n }\n }\n }\n\n private appendStreamLines(lines: string[], width: number): void {\n const label = `${GREEN}Assistant:${RESET} `;\n const labelWidth = 12;\n const indent = ' '.repeat(labelWidth);\n\n if (!this.streamContent) {\n lines.push(label);\n return;\n }\n\n let first = true;\n for (const para of this.streamContent.split('\\n')) {\n for (const wl of this.wrapText(para, width - labelWidth)) {\n lines.push(first ? label + wl : indent + wl);\n first = false;\n }\n }\n }\n\n // ─── Debug display line building ──────────────────────────────────\n\n private buildDebugLines(): string[] {\n const lines: string[] = [];\n const dw = this.debugWidth();\n if (dw <= 0) return lines;\n\n for (const entry of this.debugEntries) {\n const color = entry.direction === 'in' ? ORANGE : LIGHT_BLUE;\n const arrow = entry.direction === 'in' ? '\\u25bc' : '\\u25b2'; // ▼ in, ▲ out\n const prefix = `${DIM}${entry.ts}${RESET} ${color}${arrow}${RESET} `;\n const prefixWidth = entry.ts.length + 3; // \"HH:MM:SS ▼ \"\n\n if (!this.expandDetails) {\n // Collapsed: single summary line, truncated\n const maxSummary = dw - prefixWidth;\n const summaryText = entry.summary.slice(0, maxSummary);\n lines.push(`${prefix}${color}${summaryText}${RESET}`);\n } else {\n // Expanded: summary + full detail\n lines.push(`${prefix}${color}${entry.summary}${RESET}`);\n const indent = ' '.repeat(prefixWidth);\n for (const detailLine of entry.detail.split('\\n')) {\n for (const wl of this.wrapText(detailLine, dw - prefixWidth)) {\n lines.push(`${indent}${color}${DIM}${wl}${RESET}`);\n }\n }\n lines.push(''); // blank line between expanded entries\n }\n }\n\n return lines;\n }\n\n // ─── Text utilities ───────────────────────────────────────────────\n\n private wrapText(text: string, maxWidth: number): string[] {\n if (maxWidth <= 0) maxWidth = 1;\n if (!text) return [''];\n if (text.length <= maxWidth) return [text];\n\n const words = text.split(' ');\n const result: string[] = [];\n let current = '';\n\n for (const word of words) {\n if (!current) {\n current = word;\n } else if (current.length + 1 + word.length <= maxWidth) {\n current += ' ' + word;\n } else {\n result.push(current);\n current = word;\n }\n }\n if (current) result.push(current);\n\n return result.length ? result : [''];\n }\n}\n\n// ─── Module-level helpers ─────────────────────────────────────────────────────\n\nfunction pad2(n: number): string {\n return n < 10 ? `0${n}` : String(n);\n}\n\n/** Truncate a string (which may contain ANSI codes) to fit in maxCols visible characters */\nfunction truncateAnsi(s: string, maxCols: number): string {\n if (maxCols <= 0) return '';\n let visible = 0;\n let i = 0;\n while (i < s.length && visible < maxCols) {\n if (s[i] === '\\x1B') {\n // Skip ANSI sequence\n const end = s.indexOf('m', i);\n if (end !== -1) {\n i = end + 1;\n } else {\n i++;\n }\n } else {\n visible++;\n i++;\n }\n }\n // Append RESET to close any open ANSI sequences\n return s.slice(0, i) + RESET;\n}\n\n/** Redact audio PCM buffers from WebSocket messages for debug display (does not redact text content) */\nfunction redactAudio(msg: any): any {\n if (!msg || typeof msg !== 'object') return msg;\n const clone = { ...msg };\n // Redact voice.audio CUSTOM events\n if (clone.type === 'CUSTOM' && clone.value && typeof clone.value === 'object') {\n const name = clone.name || '';\n if (name === 'voice.audio' && clone.value.data) {\n clone.value = { ...clone.value, data: '[audio]' };\n }\n }\n return clone;\n}\n\n/** Build a one-line summary of a WebSocket message for the collapsed debug view */\nfunction buildDebugSummary(_direction: 'in' | 'out', msg: any): string {\n if (!msg || typeof msg !== 'object') return String(msg);\n\n if (msg.type === 'CUSTOM') {\n const name = msg.name || '?';\n // For audio, just show the event name\n if (name === 'voice.audio') return name;\n // For other CUSTOM events, show name + compact value hint\n if (msg.value && typeof msg.value === 'object') {\n const keys = Object.keys(msg.value);\n if (keys.length <= 3) {\n return `${name} {${keys.join(', ')}}`;\n }\n return `${name} {${keys.length} keys}`;\n }\n return name;\n }\n\n // Standard AG-UI events: TEXT_MESSAGE_CONTENT, TOOL_CALL_START, etc.\n const type = msg.type || '?';\n if (msg.delta) {\n const preview = msg.delta.length > 30 ? msg.delta.slice(0, 30) + '...' : msg.delta;\n return `${type} \"${preview}\"`;\n }\n if (msg.toolCallName) {\n return `${type} ${msg.toolCallName}`;\n }\n return type;\n}\n","/**\n * Audio I/O for CLI using SoX (Sound eXchange)\n *\n * Uses the `rec` command for microphone capture and `play` for audio playback.\n * SoX is cross-platform and available via:\n * macOS: brew install sox\n * Linux: apt install sox\n * Windows: choco install sox\n */\n\nimport { spawn, execSync, spawnSync, type ChildProcess } from 'child_process';\nimport { EventEmitter } from 'events';\nimport * as readline from 'readline';\n\nconst SAMPLE_RATE = 24000;\n// 100ms of PCM16 audio at 24kHz mono = 4800 bytes\nconst MIC_CHUNK_BYTES = 4800;\n\nexport interface AudioDevice {\n id: string;\n name: string;\n isDefault: boolean;\n}\n\n/** Check if SoX is installed and available */\nexport function checkSoxAvailable(): boolean {\n try {\n execSync('which sox', { stdio: 'pipe' });\n return true;\n } catch {\n return false;\n }\n}\n\n/** List audio input devices via SoX */\nexport async function listInputDevices(): Promise<AudioDevice[]> {\n return listDevices('rec');\n}\n\n/** List audio output devices via SoX */\nexport async function listOutputDevices(): Promise<AudioDevice[]> {\n return listDevices('play');\n}\n\nfunction listDevices(command: string): Promise<AudioDevice[]> {\n return new Promise((resolve) => {\n try {\n // spawnSync avoids shell interpolation — command and args are always separate\n const proc = spawnSync(command, ['--list-devices'], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'pipe'],\n timeout: 5000,\n });\n // SoX outputs device list to stderr; combine both streams to be safe\n const output = (proc.stdout ?? '') + (proc.stderr ?? '');\n\n const devices: AudioDevice[] = [];\n const lines = output.split('\\n');\n for (const line of lines) {\n // Parse lines like: \" Input Device 0 : Built-in Microphone\"\n // or \" Output Device 0 : Built-in Output\"\n const match = line.match(/(?:Input|Output)\\s+Device\\s+(\\d+)\\s*:\\s*(.+)/i);\n if (match && match[1] && match[2]) {\n devices.push({\n id: match[1],\n name: match[2].trim(),\n isDefault: devices.length === 0, // First device is typically the default\n });\n }\n }\n\n // If SoX didn't give us devices, return a default entry\n if (devices.length === 0) {\n devices.push({ id: 'default', name: 'System Default', isDefault: true });\n }\n\n resolve(devices);\n } catch {\n // Fallback to system default\n resolve([{ id: 'default', name: 'System Default', isDefault: true }]);\n }\n });\n}\n\n/** Interactively select an audio device */\nexport async function selectDevice(devices: AudioDevice[], label: string): Promise<AudioDevice> {\n if (devices.length <= 1) {\n return devices[0]!;\n }\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stderr,\n terminal: true,\n });\n\n process.stderr.write(`\\n ${label}:\\n`);\n for (let i = 0; i < devices.length; i++) {\n const dev = devices[i]!;\n const marker = dev.isDefault ? ' (default)' : '';\n process.stderr.write(` ${i + 1}. ${dev.name}${marker}\\n`);\n }\n\n return new Promise((resolve) => {\n const defaultIdx = devices.findIndex((d) => d.isDefault);\n const defaultNum = defaultIdx >= 0 ? defaultIdx + 1 : 1;\n\n rl.question(` Select [${defaultNum}]: `, (answer) => {\n rl.close();\n const num = answer.trim() ? parseInt(answer.trim(), 10) : defaultNum;\n const idx = Math.max(0, Math.min(devices.length - 1, num - 1));\n resolve(devices[idx]!);\n });\n });\n}\n\n/**\n * Microphone capture via SoX `rec`.\n * Streams raw PCM16 signed 16-bit LE mono audio at 24kHz.\n */\nexport class MicCapture {\n private process: ChildProcess | null = null;\n private onData: (pcm16: Buffer) => void;\n private buffer = Buffer.alloc(0);\n\n constructor(onData: (pcm16: Buffer) => void) {\n this.onData = onData;\n }\n\n /** Start recording from the microphone */\n start(deviceId?: string): void {\n const args = [\n '-q', // quiet\n '-t',\n 'raw', // raw PCM output\n '-r',\n String(SAMPLE_RATE),\n '-e',\n 'signed-integer',\n '-b',\n '16', // 16-bit\n '-c',\n '1', // mono\n '-L', // little-endian\n '-', // stdout\n ];\n\n const env = { ...process.env };\n if (deviceId && deviceId !== 'default') {\n env.AUDIODEV = deviceId;\n }\n\n this.process = spawn('rec', args, {\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n this.process.stdout?.on('data', (data: Buffer) => {\n // Accumulate data and emit in consistent chunk sizes\n this.buffer = Buffer.concat([this.buffer, data]);\n while (this.buffer.length >= MIC_CHUNK_BYTES) {\n const chunk = this.buffer.subarray(0, MIC_CHUNK_BYTES);\n this.buffer = this.buffer.subarray(MIC_CHUNK_BYTES);\n this.onData(Buffer.from(chunk));\n }\n });\n\n this.process.stderr?.on('data', (data: Buffer) => {\n // SoX outputs warnings/errors to stderr - ignore unless debugging\n const msg = data.toString().trim();\n if (msg && !msg.includes('WARN')) {\n process.stderr.write(`[mic] ${msg}\\n`);\n }\n });\n\n this.process.on('error', (err) => {\n process.stderr.write(`[mic] Process error: ${err.message}\\n`);\n });\n }\n\n /** Stop recording */\n stop(): void {\n if (this.process) {\n this.process.kill('SIGTERM');\n this.process = null;\n }\n this.buffer = Buffer.alloc(0);\n }\n}\n\n/**\n * Audio playback via SoX `play`.\n * Accepts raw PCM16 signed 16-bit LE mono audio at 24kHz.\n *\n * Streams audio to SoX's stdin so playback begins immediately on the first\n * chunk — no waiting for the full response. Queues back-to-back responses\n * so a second response never kills the first mid-playback.\n *\n * Events:\n * - 'playing': SoX process spawned for a response\n * - 'done': All queued responses finished (or playback was stopped)\n */\nexport class AudioPlayer extends EventEmitter {\n private process: ChildProcess | null = null;\n private deviceId?: string;\n\n // When true, we own the SoX process's stdin and are actively streaming to it.\n // When false with a process, the stdin has been closed and SoX is draining.\n private streaming = false;\n\n // Buffer chunks when another response is already playing\n private pendingChunks: Buffer[] = [];\n private pendingBytes = 0;\n\n // Queue of complete response buffers waiting to play\n private queue: { audio: Buffer; messageId?: string }[] = [];\n\n // Playback position tracking for barge-in\n private currentMessageId?: string;\n private playbackStartTime = 0; // Date.now() when SoX started\n private bytesWritten = 0; // total bytes piped to SoX for duration estimation\n\n constructor(deviceId?: string) {\n super();\n this.deviceId = deviceId;\n }\n\n /** Check if audio is currently playing or queued */\n get isPlaying(): boolean {\n return this.process !== null || this.queue.length > 0;\n }\n\n /** Get the message ID of the currently playing audio */\n get playingMessageId(): string | undefined {\n return this.currentMessageId;\n }\n\n /** Duration of audio written so far in ms */\n private get currentDurationMs(): number {\n // PCM16 mono 24kHz = 48000 bytes/sec\n return (this.bytesWritten / (SAMPLE_RATE * 2)) * 1000;\n }\n\n /**\n * Estimate current playback position in milliseconds.\n * Uses wall-clock time since SoX started playing.\n */\n getPlaybackTimeMs(): number | null {\n if (!this.process || this.playbackStartTime === 0) return null;\n const elapsed = Date.now() - this.playbackStartTime;\n return Math.min(elapsed, this.currentDurationMs);\n }\n\n /**\n * Stream PCM16 audio data for playback.\n * On the first chunk, spawns SoX and begins playback immediately.\n */\n write(pcm16: Buffer): void {\n if (this.process && !this.streaming) {\n // A previous response is still playing/draining — buffer for later\n this.pendingChunks.push(pcm16);\n this.pendingBytes += pcm16.length;\n return;\n }\n\n if (!this.process) {\n this.spawnSoxProcess();\n }\n\n this.process!.stdin!.write(pcm16);\n this.bytesWritten += pcm16.length;\n }\n\n /**\n * End the current audio response.\n * If streaming, closes stdin to let SoX finish playing.\n * If buffering behind another response, adds to the queue.\n */\n endResponse(messageId?: string): void {\n if (this.streaming && this.process) {\n this.currentMessageId = messageId;\n this.streaming = false;\n this.process.stdin!.end();\n } else if (this.pendingChunks.length > 0) {\n const audio = Buffer.concat(this.pendingChunks);\n this.pendingChunks = [];\n this.pendingBytes = 0;\n this.queue.push({ audio, messageId });\n }\n }\n\n /** Stop current playback, discard all queued audio */\n stop(): void {\n this.pendingChunks = [];\n this.pendingBytes = 0;\n this.queue = [];\n this.streaming = false;\n\n const wasPlaying = this.process !== null;\n if (this.process) {\n try {\n this.process.stdin?.destroy();\n this.process.kill('SIGTERM');\n } catch {\n // Ignore\n }\n this.process = null;\n }\n this.currentMessageId = undefined;\n this.playbackStartTime = 0;\n this.bytesWritten = 0;\n if (wasPlaying) {\n this.emit('done');\n }\n }\n\n /** Spawn a SoX `play` process reading raw PCM from stdin */\n private spawnSoxProcess(): void {\n this.bytesWritten = 0;\n this.currentMessageId = undefined;\n\n const args = [\n '-q', // quiet\n '-t',\n 'raw',\n '-r',\n String(SAMPLE_RATE),\n '-e',\n 'signed-integer',\n '-b',\n '16',\n '-c',\n '1',\n '-L', // little-endian\n '-', // read from stdin\n ];\n\n const env = { ...process.env };\n if (this.deviceId && this.deviceId !== 'default') {\n env.AUDIODEV = this.deviceId;\n }\n\n const proc = spawn('play', args, {\n env,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n proc.on('error', (err) => {\n process.stderr.write(`[player] Process error: ${err.message}\\n`);\n });\n\n proc.on('exit', (code, _signal) => {\n // 143 = SIGTERM (normal stop/interrupt)\n if (code !== null && code !== 0 && code !== 143) {\n process.stderr.write(`[player] SoX exited with code ${code}\\n`);\n }\n if (this.process === proc) {\n this.process = null;\n this.streaming = false;\n if (this.queue.length > 0) {\n const next = this.queue.shift()!;\n this.playQueued(next.audio, next.messageId);\n } else {\n this.emit('done');\n }\n }\n });\n\n proc.stderr?.on('data', (data: Buffer) => {\n const msg = data.toString().trim();\n if (msg) {\n process.stderr.write(`[player:sox] ${msg}\\n`);\n }\n });\n\n proc.stdout?.resume();\n\n this.process = proc;\n this.streaming = true;\n this.playbackStartTime = Date.now();\n this.emit('playing');\n }\n\n /** Play a complete pre-buffered response (from the queue) */\n private playQueued(audio: Buffer, messageId?: string): void {\n this.spawnSoxProcess();\n this.currentMessageId = messageId;\n this.process!.stdin!.write(audio);\n this.bytesWritten = audio.length;\n this.process!.stdin!.end();\n this.streaming = false;\n }\n}\n","/**\n * Concierge chat command — interactive chat with the global concierge agent.\n *\n * Supports the same modes as workspace manager chat (text, realtime, voice)\n * but without requiring a workspace.\n */\n\nimport { formatTimestamp, selectFromList } from '../cli-utils';\nimport {\n createConciergeChat,\n getConciergeChat,\n getConciergeChatMessages,\n listConciergeChats,\n type ConciergeChat,\n} from '../lib/concierge-api';\nimport { requireAuth, type AuthenticatedContext } from '../lib/context';\nimport { CLIError } from '../lib/errors';\nimport type { CommandHandlerContext } from '../lib/types';\nimport { runChatSession, type ChatSession } from '../lib/chat-session';\n\nexport async function conciergeCommand(hctx: CommandHandlerContext): Promise<void> {\n const ctx = requireAuth(hctx.ctx);\n const { args } = hctx;\n const chatIdArg = typeof args['chat-id'] === 'string' ? args['chat-id'] : undefined;\n const message = typeof args.message === 'string' ? args.message : undefined;\n\n const chat = await getOrCreateConciergeChat(ctx, chatIdArg, !!message);\n const session = buildConciergeSession(ctx, chat);\n await runChatSession(session, args);\n}\n\nfunction buildConciergeSession(ctx: AuthenticatedContext, chat: ConciergeChat): ChatSession {\n const wsBase = ctx.envConfig.apiUrl.replace(/^https:/, 'wss:').replace(/^http:/, 'ws:');\n return {\n ctx,\n chatId: chat.id,\n chatUuid: chat.uuid,\n chatTitle: chat.title || chat.uuid,\n aguiEndpointUrl: `${ctx.envConfig.apiUrl}/api/v2/concierge/chats/${chat.id}/chat/agui`,\n wsUrl: `${wsBase}/api/v2/concierge/voice/stream-ws`,\n loadMessages: () => getConciergeChatMessages(ctx, chat.id).catch(() => []),\n label: 'Concierge',\n model: undefined, // concierge doesn't send model field\n };\n}\n\nasync function getOrCreateConciergeChat(\n ctx: AuthenticatedContext,\n chatIdArg: string | undefined,\n skipSelection: boolean\n): Promise<ConciergeChat> {\n if (chatIdArg) {\n const id = Number(chatIdArg);\n if (isNaN(id)) throw new CLIError('--chat-id must be a number');\n return getConciergeChat(ctx, id);\n }\n\n if (skipSelection) {\n const chat = await createConciergeChat(ctx);\n process.stderr.write(`Created concierge chat #${chat.id}\\n`);\n return chat;\n }\n\n const chats = await listConciergeChats(ctx);\n\n const { item: selectedChat, isNew } = await selectFromList(chats, {\n title: 'Select a concierge chat or create a new one',\n labelFn: (c) => c.title || `Chat ${c.uuid.slice(0, 8)}...`,\n detailFn: (c) => formatTimestamp(c.updatedAt),\n emptyMessage: 'No existing concierge chats.',\n allowNew: true,\n newLabel: '+ Start new chat',\n });\n\n if (!selectedChat && !isNew) {\n throw new CLIError('No chat selected.');\n }\n\n if (isNew) {\n const chat = await createConciergeChat(ctx);\n process.stderr.write(`Created concierge chat #${chat.id}\\n`);\n return chat;\n }\n return selectedChat!;\n}\n","import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';\nimport { execSync } from 'child_process';\nimport { join } from 'path';\nimport type { AuthenticatedContext } from '../lib/context';\nimport { CLIError } from '../lib/errors';\nimport { stderr } from '../lib/output';\n\nexport async function devImportLocalCommand(\n ctx: AuthenticatedContext,\n workspace: string\n): Promise<void> {\n stderr(`Exporting workspace ${workspace}...`);\n const exportData = await ctx.apiClient.exportWorkspace(workspace);\n\n stderr('Export successful!');\n stderr(` Workflows: ${(exportData.workflows || []).length}`);\n stderr(` Tasks: ${(exportData.tasks || []).length}`);\n stderr(` Data Types: ${(exportData.dataTypes || []).length}`);\n stderr(` Sites: ${(exportData.sites || []).length}`);\n\n const slug = workspace.slice(0, 8);\n const importCacheDir = join(ctx.credentialsManager.getCacheDir(), 'imports');\n if (!existsSync(importCacheDir)) {\n mkdirSync(importCacheDir, { recursive: true });\n }\n const filename = `ws-${slug}-${workspace}.json`;\n const filepath = join(importCacheDir, filename);\n writeFileSync(filepath, JSON.stringify(exportData, null, 2));\n stderr(`Saved to: ${filepath}`);\n\n stderr('Running dev:restore...');\n const rootDir = findProjectRoot();\n const relativePath = filepath.replace(rootDir + '/', '');\n\n try {\n const result = execSync(`yarn dev:restore ${relativePath}`, {\n cwd: rootDir,\n stdio: 'pipe',\n encoding: 'utf-8',\n });\n process.stderr.write(result);\n\n const failed =\n (result.includes('Failed/Skipped: ') && !result.includes('Failed/Skipped: 0')) ||\n result.includes('Successfully restored: 0');\n\n if (failed) throw new CLIError('Import failed');\n } catch (error: unknown) {\n if (error instanceof CLIError) throw error;\n const execError = error as { stdout?: string; stderr?: string };\n if (execError.stdout) process.stderr.write(execError.stdout);\n if (execError.stderr) process.stderr.write(execError.stderr);\n throw new CLIError('dev:restore failed');\n }\n\n stderr(`Import complete: ${workspace}`);\n}\n\nfunction findProjectRoot(): string {\n let dir = process.cwd();\n while (dir !== '/') {\n const pkgPath = join(dir, 'package.json');\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n if (pkg.workspaces) return dir;\n } catch {\n // continue\n }\n }\n dir = join(dir, '..');\n }\n return process.cwd();\n}\n","import { GravityRailClient } from '@gravity-rail/sdk';\nimport { performOAuthFlow } from '../cli-utils';\nimport type { CommandContext } from '../lib/context';\nimport { stderr } from '../lib/output';\n\nexport async function loginCommand(ctx: CommandContext): Promise<void> {\n const { accessToken } = await performOAuthFlow({\n env: ctx.env,\n envConfig: ctx.envConfig,\n credentialsManager: ctx.credentialsManager,\n });\n\n const apiClient = new GravityRailClient(accessToken, ctx.envConfig.apiUrl);\n const account = await apiClient.getUserAccount();\n stderr(`Logged in as ${account.name} (${account.email})`);\n}\n\nexport async function logoutCommand(ctx: CommandContext): Promise<void> {\n ctx.credentialsManager.clear(ctx.env);\n stderr(`Credentials cleared for ${ctx.env}`);\n}\n","import type { Chat, GravityRailClient } from '@gravity-rail/sdk';\nimport { formatTimestamp, selectFromList } from '../cli-utils';\nimport { CLIError } from '../lib/errors';\nimport { requireAuth, type AuthenticatedContext } from '../lib/context';\nimport type { CommandHandlerContext } from '../lib/types';\nimport { runChatSession, type ChatSession } from '../lib/chat-session';\n\n// ─── Entry point ─────────────────────────────────────────────────────────────\n\nexport async function manageCommand(hctx: CommandHandlerContext): Promise<void> {\n const ctx = requireAuth(hctx.ctx);\n const { workspace, args } = hctx;\n const asMember = typeof args['as-member'] === 'string' ? args['as-member'] : undefined;\n const chatIdArg = typeof args['chat-id'] === 'string' ? args['chat-id'] : undefined;\n const message = typeof args.message === 'string' ? args.message : undefined;\n\n const chat = await getOrCreateChat(ctx, workspace, chatIdArg, asMember, 'manager', !!message);\n const session = buildWorkspaceSession(ctx, workspace, chat, 'Workspace Manager');\n await runChatSession(session, args);\n}\n\nexport async function chatCommand(hctx: CommandHandlerContext): Promise<void> {\n const ctx = requireAuth(hctx.ctx);\n const { workspace, args } = hctx;\n const chatIdArg = typeof args['chat-id'] === 'string' ? args['chat-id'] : undefined;\n const workflowId = typeof args.workflow === 'string' ? args.workflow : undefined;\n const memberId = typeof args.member === 'string' ? args.member : undefined;\n\n let chat: Chat;\n if (chatIdArg) {\n const id = Number(chatIdArg);\n if (isNaN(id)) throw new CLIError('--chat-id must be a number');\n chat = await ctx.apiClient.getChat(workspace, id);\n } else if (workflowId) {\n chat = await createAssignmentChat(ctx.apiClient, workspace, Number(workflowId), memberId);\n } else if (memberId) {\n chat = await createMemberChat(ctx.apiClient, workspace, memberId);\n } else {\n throw new CLIError(\n 'Specify --workflow <id>, --member <id>, or --chat-id <id>.\\n' +\n 'Use \"gr manage\" for workspace manager chats.'\n );\n }\n\n const session = buildWorkspaceSession(ctx, workspace, chat, 'Chat');\n await runChatSession(session, args);\n}\n\n// ─── Session builder ─────────────────────────────────────────────────────────\n\nfunction buildWorkspaceSession(\n ctx: AuthenticatedContext,\n workspace: string,\n chat: Chat,\n label: string\n): ChatSession {\n const wsBase = ctx.envConfig.apiUrl.replace(/^https:/, 'wss:').replace(/^http:/, 'ws:');\n return {\n ctx,\n chatId: chat.id,\n chatUuid: chat.uuid,\n chatTitle: chat.title || chat.uuid,\n aguiEndpointUrl: `${ctx.envConfig.apiUrl}/api/v2/w/${workspace}/web-chat/${chat.id}/chat/agui`,\n wsUrl: `${wsBase}/api/v2/w/${workspace}/realtime/stream-ws`,\n loadMessages: () => ctx.apiClient.getChatMessages(workspace, chat.id, 50).catch(() => []),\n label,\n model: 'manager',\n };\n}\n\n// ─── Chat selection ──────────────────────────────────────────────────────────\n\nasync function getOrCreateChat(\n ctx: AuthenticatedContext,\n workspace: string,\n chatIdArg: string | undefined,\n asMemberId: string | undefined,\n chatType: 'manager' | 'assignment' | 'member' | 'contributor' | 'developer',\n skipSelection: boolean = false\n): Promise<Chat> {\n if (chatIdArg) {\n const chatId = Number(chatIdArg);\n if (isNaN(chatId)) throw new CLIError('--chat-id must be a number');\n return ctx.apiClient.getChat(workspace, chatId);\n }\n\n if (skipSelection) {\n return createManagerChat(ctx.apiClient, workspace, asMemberId);\n }\n\n const chatsResponse = await ctx.apiClient.getChats(workspace, {\n chatType,\n sortBy: 'updatedAt',\n sortOrder: 'desc',\n pageSize: 20,\n });\n const chats = chatsResponse.items || [];\n\n const { item: selectedChat, isNew } = await selectFromList(chats, {\n title: 'Select a chat or create a new one',\n labelFn: (chat) => chat.title || `Chat ${chat.uuid.slice(0, 8)}...`,\n detailFn: (chat) => {\n const time = formatTimestamp(chat.updatedAt);\n const msgCount = chat.messageCount || 0;\n return `${msgCount} msg${msgCount !== 1 ? 's' : ''} - ${time}`;\n },\n emptyMessage: 'No existing chats.',\n allowNew: true,\n newLabel: '+ Start new chat',\n });\n\n if (!selectedChat && !isNew) {\n throw new CLIError('No chat selected.');\n }\n\n if (isNew) {\n return createManagerChat(ctx.apiClient, workspace, asMemberId);\n }\n return selectedChat!;\n}\n\nasync function createManagerChat(\n apiClient: GravityRailClient,\n workspace: string,\n asMemberId: string | undefined\n): Promise<Chat> {\n const data: Record<string, any> = {\n chatType: 'manager',\n channel: 'web-chat',\n };\n if (asMemberId) {\n data.memberId = Number(asMemberId);\n }\n const chat = await apiClient.createChat(workspace, data as any);\n process.stderr.write(`Created chat #${chat.id}\\n`);\n return chat;\n}\n\nasync function createAssignmentChat(\n apiClient: GravityRailClient,\n workspace: string,\n workflowId: number,\n asMemberId: string | undefined\n): Promise<Chat> {\n if (isNaN(workflowId)) throw new CLIError('--workflow must be a number');\n const data: Record<string, any> = {\n chatType: 'assignment',\n channel: 'web-chat',\n workflowId,\n };\n if (asMemberId) {\n data.memberId = Number(asMemberId);\n }\n const chat = await apiClient.createChat(workspace, data as any);\n process.stderr.write(`Created assignment chat #${chat.id} (workflow ${workflowId})\\n`);\n return chat;\n}\n\nasync function createMemberChat(\n apiClient: GravityRailClient,\n workspace: string,\n memberId: string\n): Promise<Chat> {\n const id = Number(memberId);\n if (isNaN(id)) throw new CLIError('--member must be a number');\n const data: Record<string, any> = {\n chatType: 'member',\n channel: 'web-chat',\n memberId: id,\n };\n const chat = await apiClient.createChat(workspace, data as any);\n process.stderr.write(`Created DM chat #${chat.id} (member ${memberId})\\n`);\n return chat;\n}\n","import type { AuthenticatedContext } from '../lib/context';\nimport { outputData, type TableColumn } from '../lib/output';\n\n// The return type of getMyOrganizations references the admin-only\n// AdminAccountOrgMembership type, which is not re-exported from the public\n// @gravity-rail/sdk surface. We infer the element shape from the runtime\n// method signature here.\ntype OrgMembership = Awaited<\n ReturnType<AuthenticatedContext['apiClient']['getMyOrganizations']>\n>[number];\n\nconst COLUMNS: TableColumn<OrgMembership>[] = [\n { header: 'NAME', getValue: (o) => o.organizationName || '', maxWidth: 35 },\n { header: 'SLUG', getValue: (o) => o.organizationSlug || '', maxWidth: 25 },\n { header: 'UUID', getValue: (o) => o.organizationUuid },\n { header: 'ROLE', getValue: (o) => o.role || '' },\n];\n\nexport async function organizationsListCommand(ctx: AuthenticatedContext): Promise<void> {\n const organizations = await ctx.apiClient.getMyOrganizations();\n outputData(organizations, ctx, COLUMNS);\n}\n","import type { Account } from '@gravity-rail/sdk';\nimport type { AuthenticatedContext } from '../lib/context';\nimport { outputSingle, type TableColumn } from '../lib/output';\n\nconst COLUMNS: TableColumn<Account>[] = [\n { header: 'NAME', getValue: (a) => a.name || '', maxWidth: 30 },\n { header: 'EMAIL', getValue: (a) => a.email || '', maxWidth: 40 },\n { header: 'UUID', getValue: (a) => a.uuid },\n { header: 'SUPERUSER', getValue: (a) => (a.isSuperuser ? 'yes' : 'no') },\n];\n\nexport async function whoamiCommand(ctx: AuthenticatedContext): Promise<void> {\n const account = await ctx.apiClient.getUserAccount();\n outputSingle(account, ctx, COLUMNS);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAO,IAAM,WAAN,cAAuB,MAAM;AAAA,EACjC,YACG,SACO,WAAmB,GAC3B;AACC,UAAM,OAAO;AAFN;AAGP,SAAK,OAAO;AAAA,EACf;AACH;AAEO,IAAM,oBAAN,cAAgC,SAAS;AAAA,EAC7C,YAAY,UAAU,kEAAkE;AACrF,UAAM,SAAS,CAAC;AAChB,SAAK,OAAO;AAAA,EACf;AACH;AAEO,SAAS,YAAY,KAAqB;AAC9C,MAAI,eAAe,UAAU;AAC1B,YAAQ,OAAO,MAAM,UAAU,IAAI,OAAO;AAAA,CAAI;AAC9C,YAAQ,KAAK,IAAI,QAAQ;AAAA,EAC5B;AAEA,MAAI,eAAe,OAAO;AACvB,YAAQ,OAAO,MAAM,UAAU,IAAI,OAAO;AAAA,CAAI;AAC9C,QAAI,YAAY,OAAO,MAAM,QAAS,IAAY,MAAM,GAAG;AACxD,iBAAW,KAAM,IAAY,QAAQ;AAClC,gBAAQ,OAAO,MAAM,OAAO,CAAC;AAAA,CAAI;AAAA,MACpC;AAAA,IACH;AACA,QAAI,gBAAgB,OAAQ,IAAY,eAAe,KAAK;AACzD,cAAQ,OAAO;AAAA,QACZ;AAAA;AAAA;AAAA,MACH;AAAA,IACH;AACA,YAAQ,KAAK,CAAC;AAAA,EACjB;AAEA,UAAQ,OAAO,MAAM,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI;AAC9C,UAAQ,KAAK,CAAC;AACjB;;;ACbO,SAAS,aAAa,M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MAAM,2BAA2B,KAAK,KAAK;AAC/E,SAAO,qBAAqB,MAAM,mBAAmB,KAAK,KAAK;AAC/D,SAAO,4BAA4B,MAAM,0BAA0B,KAAK,KAAK;AAG7E,SAAO,eAAe,MAAM,aAAa,KAAK,KAAK;AACnD,SAAO,cAAc,MAAM,YAAY,KAAK,KAAK;AACjD,SAAO,iBAAiB,MAAM,eAAe,KAAK,KAAK;AACvD,SAAO,iBAAiB,MAAM,eAAe,KAAK,KAAK;AACvD,SAAO,sBAAsB,MAAM,oBAAoB,KAAK,KAAK;AACjE,SAAO,wBAAwB,MAAM,sBAAsB,KAAK,KAAK;AACrE,SAAO,4BAA4B,MAAM,0BAA0B,KAAK,KAAK;AAChF;ADhcO,IAAM,YAAN,cAAwB,kBAA2C;;EAEvE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA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AE,QAAQ,IAAI,UAAU,GAAG;AAAA,EAC9D,EAAE,QAAQ,SAAS,UAAU,CAAC,MAAM,EAAE,SAAS,IAAI,UAAU,GAAG;AAAA,EAChE,EAAE,QAAQ,QAAQ,UAAU,CAAC,MAAM,EAAE,KAAK;AAAA,EAC1C,EAAE,QAAQ,aAAa,UAAU,CAAC,MAAO,EAAE,cAAc,QAAQ,KAAM;AAC1E;AAEA,eAAsB,cAAc,KAA0C;AAC3E,QAAM,UAAU,MAAM,IAAI,UAAU,eAAe;AACnD,eAAa,SAAS,KAAKA,SAAO;AACrC;","names":["baseUrl","readFileSync","readFileSync","COLUMNS","MESSAGE_COLUMNS","truncate","COLUMNS","LABEL_COLUMNS","FILTER_COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","MESSAGE_COLUMNS","COLUMNS","MESSAGE_COLUMNS","COLUMNS","COLUMNS","EVENT_COLUMNS","result","page","pageSize","COLUMNS","LABEL_COLUMNS","NOTE_COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","baseUrl","MESSAGE_COLUMNS","COLUMNS","TOOL_COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","commands","COLUMNS","COLUMNS","COLUMNS","COLUMNS","RUN_COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","execFile","execFile","readline","execSync","EventEmitter","existsSync","mkdirSync","writeFileSync","readFileSync","execSync","join","join","existsSync","mkdirSync","writeFileSync","execSync","readFileSync","GravityRailClient","GravityRailClient","COLUMNS","COLUMNS"]}
1
+ {"version":3,"sources":["../src/lib/pagination.ts","../src/lib/args.ts","../../client/src/index.ts","../../client/src/api/admin.ts","../../client/src/client/client.ts","../../client/src/client/bindings/admin.ts","../src/lib/context.ts","../src/lib/output.ts","../src/lib/realm.ts","../src/lib/org-auth.ts","../src/lib/input.ts","../src/lib/crud.ts","../src/lib/registry.ts","../src/lib/types.ts","../src/domains/agent-tasks.ts","../src/domains/agents.ts","../src/domains/chats.ts","../src/domains/members.ts","../src/domains/tasks.ts","../src/domains/workflows.ts","../src/domains/workflow-versions.ts","../src/domains/workspaces.ts","../src/domains/assignments.ts","../src/domains/calendars.ts","../src/domains/data-types.ts","../src/domains/events.ts","../src/domains/files.ts","../src/domains/journeys.ts","../src/domains/personas.ts","../src/domains/qualifications.ts","../src/domains/sites.ts","../src/domains/access-grants.ts","../src/domains/ai-models.ts","../src/domains/api-keys.ts","../src/domains/apps.ts","../src/domains/auth-manage.ts","../src/domains/billing-portal.ts","../src/lib/concierge-api.ts","../src/domains/concierge.ts","../src/domains/custom-toolkits.ts","../src/domains/features.ts","../src/domains/inboxes.ts","../src/domains/mcp-servers.ts","../src/domains/member-memories.ts","../src/domains/milestones.ts","../src/domains/notification-rules.ts","../src/domains/oauth.ts","../src/domains/operator-groups.ts","../src/domains/org.ts","../src/domains/org-phone-numbers.ts","../src/domains/phone-numbers.ts","../src/lib/resolve-org.ts","../src/domains/pronunciations.ts","../src/domains/reports.ts","../src/domains/subscriptions.ts","../src/domains/prompts.ts","../src/domains/support.ts","../src/domains/supervisors.ts","../src/domains/sync.ts","../src/domains/integrations/app-connections.ts","../src/domains/integrations/confluence.ts","../src/domains/integrations/discord-bots.ts","../src/domains/integrations/fhir-connections.ts","../src/domains/integrations/hubspot.ts","../src/domains/integrations/monday.ts","../src/domains/integrations/salesforce.ts","../src/domains/integrations/slack-apps.ts","../src/domains/integrations/teams-apps.ts","../src/domains/index.ts","../src/commands/auth-browser.ts","../src/lib/cli-client-context.ts","../src/lib/cli-hitl.ts","../src/lib/local-files.ts","../src/lib/trusted-dirs.ts","../src/lib/concierge-agui-loop.ts","../src/lib/chat-session.ts","../src/lib/realtime-client.ts","../src/lib/chat-tui.ts","../src/lib/audio.ts","../src/commands/concierge.ts","../src/commands/get-started.ts","../src/commands/dev.ts","../src/commands/login.ts","../src/commands/manage.ts","../src/commands/organizations.ts","../src/commands/whoami.ts"],"sourcesContent":["import type { ArgDef, ParsedArgs } from './types';\nimport { CLIError } from './errors';\n\n// ── Response shape detection ─────────────────────────────────────────\n\n/** Metadata extracted from a paginated API response */\nexport interface PaginationMeta {\n /** Total number of items across all pages (page-based only) */\n total?: number;\n /** Current page number (page-based only) */\n page?: number;\n /** Total pages (page-based only) */\n totalPages?: number;\n /** Whether more pages exist (cursor-based only) */\n hasMore?: boolean;\n /** Cursor for next page (cursor-based only) */\n nextCursor?: string;\n}\n\n/** Explicit pagination contract passed from commands to outputData */\nexport interface ListResult {\n items: unknown[];\n meta?: PaginationMeta;\n supportsAll?: boolean;\n}\n\n/** Type guard: is the value a ListResult (explicit contract)? */\nexport function isListResult(data: unknown): data is ListResult {\n if (!data || typeof data !== 'object' || Array.isArray(data)) return false;\n const obj = data as Record<string, unknown>;\n return (\n Array.isArray(obj.items) &&\n ('supportsAll' in obj ||\n ('meta' in obj && (obj.meta === undefined || typeof obj.meta === 'object')))\n );\n}\n\n/** Check if a response looks like a page-based paginated envelope.\n * Matches both `{ items, total, totalPages, page }` (standard) and\n * `{ items, total, page, pageSize }` (legacy — e.g. InvitationListResponse,\n * InquiryListResponse). This is a pure type guard with no side effects;\n * totalPages computation for legacy shapes happens in extractPaginationMeta. */\nexport function isPagePaginatedResponse(data: unknown): data is {\n items: unknown[];\n total: number;\n page: number;\n totalPages?: number;\n pageSize?: number;\n} {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n if (!Array.isArray(obj.items) || typeof obj.page !== 'number') return false;\n\n // Standard shape: has totalPages\n if (typeof obj.totalPages === 'number') return true;\n\n // Legacy shape: has total + pageSize but no totalPages\n if (typeof obj.total === 'number' && typeof obj.pageSize === 'number') return true;\n\n return false;\n}\n\n/** Check if a response looks like a cursor-based paginated envelope */\nexport function isCursorPaginatedResponse(data: unknown): data is {\n items: unknown[];\n hasMore: boolean;\n nextCursor?: string;\n} {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n return Array.isArray(obj.items) && typeof obj.hasMore === 'boolean';\n}\n\n/** Check if a response is any paginated envelope ({ items: [...], ... }) */\nexport function isPaginatedResponse(data: unknown): boolean {\n return isPagePaginatedResponse(data) || isCursorPaginatedResponse(data);\n}\n\n/** Extract pagination metadata from a response, or return undefined for non-paginated responses.\n * For legacy shapes without totalPages, computes it from total/pageSize. */\nexport function extractPaginationMeta(data: unknown): PaginationMeta | undefined {\n if (isPagePaginatedResponse(data)) {\n const totalPages =\n data.totalPages ?? (data.pageSize ? Math.ceil(data.total / data.pageSize) : undefined);\n return {\n total: data.total,\n page: data.page,\n totalPages,\n };\n }\n if (isCursorPaginatedResponse(data)) {\n return {\n hasMore: data.hasMore,\n nextCursor: data.nextCursor,\n };\n }\n return undefined;\n}\n\n// ── Warning formatting ───────────────────────────────────────────────\n\n/** Format a pagination warning for stderr. Returns undefined if no warning needed.\n * When `supportsAll` is false, the \"Use --all\" hint is omitted because the\n * command does not actually expose the --all flag. */\nexport function formatPaginationWarning(\n meta: PaginationMeta | undefined,\n supportsAll: boolean = true\n): string | undefined {\n if (!meta) return undefined;\n\n const allHint = supportsAll ? ' Use --all to fetch all pages.' : '';\n\n // Page-based: warn when there are multiple pages\n if (meta.totalPages !== undefined && meta.totalPages > 1) {\n const pageNum = meta.page ?? 1;\n return `Showing page ${pageNum} of ${meta.totalPages} (${meta.total} total items).${allHint}`;\n }\n\n // Cursor-based: warn when more pages exist\n if (meta.hasMore === true) {\n return `More results available.${allHint}`;\n }\n\n return undefined;\n}\n\n// ── Unwrapping ───────────────────────────────────────────────────────\n\n/** Unwrap items from a paginated response or return the data as-is if it's an array */\nexport function unwrapItems(data: unknown): unknown[] {\n if (Array.isArray(data)) return data;\n if (\n data &&\n typeof data === 'object' &&\n 'items' in data &&\n Array.isArray((data as Record<string, unknown>).items)\n ) {\n return (data as Record<string, unknown>).items as unknown[];\n }\n return [data];\n}\n\n// ── Arg definitions ──────────────────────────────────────────────────\n\n/** Default pagination args for list commands (page, page-size, all). No search. */\nexport const LIST_PAGINATION_ARGS: ArgDef[] = [\n { name: 'page', description: 'Page number' },\n { name: 'page-size', description: 'Page size' },\n { name: 'all', description: 'Fetch all pages and return combined results', isFlag: true },\n];\n\n// ── Arg-to-options helpers ───────────────────────────────────────────\n\n/** Convert parsed CLI args to API pagination options */\nexport function parsePaginationArgs(args: ParsedArgs): {\n page?: number;\n pageSize?: number;\n all?: boolean;\n} {\n const result: { page?: number; pageSize?: number; all?: boolean } = {};\n\n if (args.all === true) {\n result.all = true;\n }\n\n if (args.page !== undefined) {\n const num = Number(args.page);\n if (isNaN(num) || num < 1) throw new CLIError('--page must be a positive integer');\n result.page = num;\n }\n\n if (args['page-size'] !== undefined) {\n const num = Number(args['page-size']);\n if (isNaN(num) || num < 1) throw new CLIError('--page-size must be a positive integer');\n if (num > 100) throw new CLIError('--page-size must be at most 100 (API limit)');\n result.pageSize = num;\n }\n\n return result;\n}\n\n// ── fetchAll helpers ─────────────────────────────────────────────────\n\nconst MAX_PAGE_SIZE = 100;\nconst MAX_PAGES = 200; // Safety limit to prevent infinite loops\n\n/**\n * Fetch all pages from a page-based paginated endpoint.\n * The fetcher receives { page, pageSize } and should return the raw API response.\n * Throws CLIError if MAX_PAGES is reached without exhausting all pages.\n */\nexport async function fetchAllPages(\n fetcher: (opts: { page: number; pageSize: number }) => Promise<unknown>\n): Promise<unknown[]> {\n const allItems: unknown[] = [];\n let page = 1;\n\n while (page <= MAX_PAGES) {\n const result = await fetcher({ page, pageSize: MAX_PAGE_SIZE });\n const items = unwrapItems(result);\n allItems.push(...items);\n\n // Use server metadata for termination\n const meta = extractPaginationMeta(result);\n if (meta?.totalPages !== undefined) {\n if (page >= meta.totalPages) break;\n } else if (!isPagePaginatedResponse(result)) {\n // Raw array or no metadata — single fetch is enough\n if (items.length < MAX_PAGE_SIZE) break;\n }\n\n if (page === MAX_PAGES) {\n throw new CLIError(\n `Reached maximum page limit (${MAX_PAGES}). Results may be incomplete.`\n );\n }\n\n page++;\n }\n\n return allItems;\n}\n\n/**\n * Fetch all pages from a cursor-based paginated endpoint.\n * The fetcher receives { cursor? } and should return the raw API response.\n * Throws CLIError if MAX_PAGES is reached without exhausting all pages.\n */\nexport async function fetchAllCursorPages(\n fetcher: (opts: { cursor?: string }) => Promise<unknown>\n): Promise<unknown[]> {\n const allItems: unknown[] = [];\n let cursor: string | undefined;\n let pages = 0;\n\n while (pages < MAX_PAGES) {\n const result = await fetcher({ cursor });\n const items = unwrapItems(result);\n allItems.push(...items);\n pages++;\n\n if (isCursorPaginatedResponse(result) && result.hasMore && result.nextCursor) {\n cursor = result.nextCursor;\n } else {\n break;\n }\n\n if (pages === MAX_PAGES) {\n throw new CLIError(\n `Reached maximum page limit (${MAX_PAGES}). Results may be incomplete.`\n );\n }\n }\n\n return allItems;\n}\n\n// ── ListResult factory ──────────────────────────────────────────────\n\n/**\n * Wrap a raw API response into a ListResult with explicit pagination metadata.\n * Works with both page-based and cursor-based responses, as well as plain arrays.\n *\n * @param data - Raw API response (paginated envelope or plain array)\n * @param supportsAll - Whether the calling command exposes --all\n */\nexport function listResult(data: unknown, supportsAll: boolean = false): ListResult {\n return {\n items: unwrapItems(data),\n meta: extractPaginationMeta(data),\n supportsAll,\n };\n}\n","import type { ArgDef, ParsedArgs } from './types';\nimport { CLIError } from './errors';\nimport { LIST_PAGINATION_ARGS } from './pagination';\n\nexport { LIST_PAGINATION_ARGS };\n\n/** Standard pagination args used by admin list commands (includes search).\n * @deprecated Use LIST_PAGINATION_ARGS (page/page-size/all only) plus domain-specific filter args instead. */\nexport const PAGINATION_ARGS: ArgDef[] = [\n { name: 'search', description: 'Search by name' },\n ...LIST_PAGINATION_ARGS,\n];\n\n/** Common args automatically available to all commands */\nconst COMMON_ARGS: ArgDef[] = [\n { name: 'workspace', alias: 'w', description: 'Workspace UUID' },\n { name: 'data', alias: 'd', description: 'JSON data string' },\n { name: 'file', alias: 'f', description: 'Path to JSON file' },\n { name: 'id', description: 'Entity ID' },\n { name: 'uuid', description: 'Entity UUID' },\n];\n\nexport function parseArgs(defs: ArgDef[], argv: string[]): ParsedArgs {\n // Command-specific defs first so e.g. --id maps to --chat-id when aliased, not common --id.\n const allDefs = [...defs, ...COMMON_ARGS];\n const result: ParsedArgs = {};\n\n // Apply defaults\n for (const def of allDefs) {\n if (def.default !== undefined) {\n result[def.name] = def.default;\n }\n }\n\n // Known global options that parseGlobalOptions already consumed\n const KNOWN_GLOBAL_FLAGS = new Set([\n '--env',\n '--realm',\n '--output-format',\n '-o',\n '--verbose',\n '-v',\n '--allow-write',\n '--help',\n '-h',\n '--version',\n ]);\n\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n\n // Support --flag=value and -f=value syntax\n const eqIdx = arg.indexOf('=');\n const flagPart = eqIdx !== -1 ? arg.slice(0, eqIdx) : arg;\n const inlineValue = eqIdx !== -1 ? arg.slice(eqIdx + 1) : undefined;\n\n const def = findDef(allDefs, flagPart);\n if (!def) {\n if (\n (flagPart.startsWith('--') || flagPart.startsWith('-')) &&\n !KNOWN_GLOBAL_FLAGS.has(flagPart)\n ) {\n throw new CLIError(`Unknown flag \"${flagPart}\"`);\n }\n continue;\n }\n if (def.isFlag) {\n result[def.name] = true;\n } else {\n const value = inlineValue ?? argv[++i];\n if (value === undefined) {\n throw new CLIError(`Missing value for --${def.name}`);\n }\n result[def.name] = value;\n }\n }\n\n // Validate required (including values provided via aliases)\n for (const def of allDefs) {\n if (!def.required) continue;\n if (result[def.name] !== undefined) continue;\n const aliasNames = [def.alias, ...(def.aliases ?? [])].filter(Boolean) as string[];\n if (aliasNames.some((a) => result[a] !== undefined)) continue;\n throw new CLIError(`Missing required argument: --${def.name}`);\n }\n\n return result;\n}\n\nfunction findDef(defs: ArgDef[], arg: string): ArgDef | undefined {\n for (const def of defs) {\n if (arg === `--${def.name}`) return def;\n if (def.alias && arg === `-${def.alias}`) return def;\n if (def.aliases) {\n for (const a of def.aliases) {\n if (arg === `--${a}`) return def;\n }\n }\n }\n return undefined;\n}\n","/**\n * @gravity-rail/client — Internal full-surface API client.\n *\n * Re-exports the entire public SDK surface via `@gravity-rail/sdk/internal`\n * (which includes admin TypeScript types), and adds the admin runtime classes\n * (`AdminApi`, `ApiClient`, `AdminBindings`, `bindAdminMethods`).\n *\n * Consumers in the monorepo should continue importing from `@gravity-rail/client`\n * as before — nothing externally visible has changed. The admin runtime classes\n * are physically absent from the public `@gravity-rail/sdk` package.\n */\n\nexport * from '@gravity-rail/sdk/internal';\n\n// Admin-only runtime\nexport { AdminApi } from './api/admin';\nexport { ApiClient } from './client/client';\nexport type { AdminBindings } from './client/bindings/admin';\nexport { bindAdminMethods } from './client/bindings/admin';\n","import {\n AccountLookupResponse,\n CreateCustomerRequest,\n CreateResellerRequest,\n Customer,\n DataExportResponse,\n DeletionCancelResponse,\n DeletionRequestResponse,\n CustomerAccount,\n LinkResellerAccountRequest,\n Reseller,\n ResellerAccount,\n UpdateCustomerRequest,\n UpdateResellerRequest,\n AccountSortField,\n AdminAccount,\n AdminBulkWorkflowAccessValidationResponse,\n HealthDetailRequest,\n HealthMetricsRequest,\n HealthMetricsResponse,\n WorkspaceHealthDetail,\n AdminAccountFormData,\n AdminAccountMembership,\n AdminAccountOrgMembership,\n AdminOrganization,\n AdminUpdateProductRequest,\n AdminChat,\n AdminChatDetail,\n AdminChatsOptions,\n MemberOrgView,\n AdminWorkspace,\n AdminWorkspaceFormData,\n AdminWorkspaceMemberFormData,\n UsageDashboardResponse,\n CompareWithStripeResponse,\n UsageReport,\n UsageReportRequest,\n VoiceMetricsResponse,\n AdminTemporalDetailQuery,\n AdminTemporalFailedQuery,\n AdminTemporalStuckQuery,\n AdminTemporalSummaryQuery,\n FailedWorkflowsResponse,\n StuckWorkflowsResponse,\n TemporalAdminConfig,\n TemporalSummaryResponse,\n WorkflowDetailResponse,\n CreateOrganizationRequest,\n CreateProductRequest,\n GenerateSummariesResponse,\n Inbox,\n InboxMappingDetailResponse,\n LogoUploadRequest,\n LogoUploadResponse,\n Member,\n MemberRole,\n MergeMembersRequest,\n MergeMembersResponse,\n MissingMembershipItem,\n OrgMember,\n PaginatedResponse,\n PaginatedSubscriptionsResponse,\n PhoneNumber,\n UnmappedPhoneNumber,\n Product,\n ChangeWorkspaceProductRequest,\n ChangeWorkspaceProductResponse,\n ProvisionPlanRequest,\n ProvisionPlanResponse,\n SiteMapping,\n SiteMappingFormData,\n SortOrder,\n StripeCustomer,\n StripeCustomerCreateRequest,\n StripeCustomerUpdateRequest,\n StripePaymentMethod,\n BillingPeriod,\n Invoice,\n RecordPaymentRequest,\n DirectSubscriptionCreateRequest,\n StripeSubscriptionCreateRequest,\n StripeSubscriptionUpdateRequest,\n Subscription,\n SyncProductToStripeRequest,\n SyncProductToStripeResponse,\n ThemesListResponse,\n OrgA2PStatus,\n ProviderPhoneNumber,\n UpdateOrganizationRequest,\n Workspace,\n WorkspaceHealthResponse,\n WorkspaceSortField,\n CreateSupportRequestCommentRequest,\n CreateSupportRequestNoteRequest,\n SupportRequest,\n SupportRequestListParams,\n SupportRequestListResponse,\n UpdateSupportRequestAttributesRequest,\n UpdateSupportRequestStatusRequest,\n} from '@gravity-rail/sdk/internal';\nimport { BaseApiClient } from '@gravity-rail/sdk/internal';\n\nfunction supportRequestParams(params?: SupportRequestListParams): string {\n const searchParams = new URLSearchParams();\n if (params?.page) searchParams.append('page', params.page.toString());\n if (params?.pageSize) searchParams.append('pageSize', params.pageSize.toString());\n if (params?.status) searchParams.append('status', params.status);\n if (params?.supportRequestType) {\n searchParams.append('supportRequestType', params.supportRequestType);\n }\n if (params?.severity) searchParams.append('severity', params.severity);\n if (params?.source) searchParams.append('source', params.source);\n if (params?.organizationId !== undefined) {\n searchParams.append('organizationId', params.organizationId.toString());\n }\n if (params?.workspaceId !== undefined) {\n searchParams.append('workspaceId', params.workspaceId.toString());\n }\n if (params?.linearLinked !== undefined) {\n searchParams.append('linearLinked', params.linearLinked.toString());\n }\n const query = searchParams.toString();\n return query ? `?${query}` : '';\n}\n\nexport class AdminApi extends BaseApiClient {\n // Support Requests API\n async listSupportRequestsAsAdmin(\n params?: SupportRequestListParams\n ): Promise<SupportRequestListResponse> {\n return this.fetch<SupportRequestListResponse>(\n `admin/support-requests${supportRequestParams(params)}`\n );\n }\n\n async getSupportRequestAsAdmin(uuid: string): Promise<SupportRequest> {\n return this.fetch<SupportRequest>(`admin/support-requests/${uuid}`);\n }\n\n async commentOnSupportRequestAsAdmin(\n uuid: string,\n data: CreateSupportRequestCommentRequest\n ): Promise<SupportRequest> {\n return this.fetch<SupportRequest>(`admin/support-requests/${uuid}/comments`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async noteOnSupportRequestAsAdmin(\n uuid: string,\n data: CreateSupportRequestNoteRequest\n ): Promise<SupportRequest> {\n return this.fetch<SupportRequest>(`admin/support-requests/${uuid}/notes`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateSupportRequestStatusAsAdmin(\n uuid: string,\n data: UpdateSupportRequestStatusRequest\n ): Promise<SupportRequest> {\n return this.fetch<SupportRequest>(`admin/support-requests/${uuid}/status`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateSupportRequestAttributesAsAdmin(\n uuid: string,\n data: UpdateSupportRequestAttributesRequest\n ): Promise<SupportRequest> {\n return this.fetch<SupportRequest>(`admin/support-requests/${uuid}/attributes`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async createSupportRequestLinearIssueAsAdmin(uuid: string): Promise<SupportRequest> {\n return this.fetch<SupportRequest>(`admin/support-requests/${uuid}/linear-issue`, {\n method: 'POST',\n });\n }\n\n // Admin Accounts API\n async getAccounts(options: {\n search?: string;\n createdAfter?: string;\n createdBefore?: string;\n isActive?: boolean;\n organizationId?: number;\n pendingDeletion?: boolean;\n sortBy?: AccountSortField;\n sortOrder?: SortOrder;\n page?: number;\n pageSize?: number;\n }): Promise<PaginatedResponse<AdminAccount>> {\n const params = new URLSearchParams();\n if (options.search) params.append('search', options.search);\n if (options.createdAfter) params.append('created_after', options.createdAfter);\n if (options.createdBefore) params.append('created_before', options.createdBefore);\n if (options.sortBy) params.append('sortBy', options.sortBy);\n if (options.sortOrder) params.append('sortOrder', options.sortOrder);\n if (options.page) params.append('page', options.page.toString());\n if (options.pageSize) params.append('pageSize', options.pageSize.toString());\n if (options.isActive !== undefined) params.append('isActive', options.isActive.toString());\n if (options.organizationId !== undefined)\n params.append('organizationId', options.organizationId.toString());\n if (options.pendingDeletion !== undefined)\n params.append('pendingDeletion', options.pendingDeletion.toString());\n\n return this.fetch<PaginatedResponse<AdminAccount>>(`admin/accounts?${params.toString()}`);\n }\n\n async getAccountDetails(id: string | number): Promise<AdminAccount> {\n return this.fetch<AdminAccount>(`admin/accounts/${id}`);\n }\n\n async getAccountByUuid(uuid: string): Promise<AdminAccount> {\n return this.fetch<AdminAccount>(`admin/accounts/${uuid}`);\n }\n\n async getAccountMemberships(accountId: number): Promise<AdminAccountMembership[]> {\n return this.fetch<AdminAccountMembership[]>(`admin/accounts/${accountId}/memberships`);\n }\n\n async getAccountOrgMemberships(accountId: number): Promise<AdminAccountOrgMembership[]> {\n return this.fetch<AdminAccountOrgMembership[]>(`admin/accounts/${accountId}/org-memberships`);\n }\n\n async createAccountOrgMembership(\n accountId: number,\n organizationId: number,\n role: 'member' | 'admin' | 'owner' = 'member'\n ): Promise<{\n accountId: number;\n organizationId: number;\n organizationUuid: string;\n organizationName: string;\n role: string;\n message: string;\n }> {\n return this.fetch(`admin/accounts/${accountId}/org-memberships`, {\n method: 'POST',\n body: JSON.stringify({ organizationId, role }),\n });\n }\n\n async deleteAccountOrgMembership(\n accountId: number,\n organizationId: number\n ): Promise<{\n status: string;\n message: string;\n workspaceMembershipsRemoved: number;\n }> {\n return this.fetch(`admin/accounts/${accountId}/org-memberships/${organizationId}`, {\n method: 'DELETE',\n });\n }\n\n async getAccountMembership(\n accountId: number,\n workspaceId: string\n ): Promise<AdminAccountMembership> {\n return this.fetch<AdminAccountMembership>(\n `admin/accounts/${accountId}/memberships/${workspaceId}`\n );\n }\n\n async updateAccountMembership(\n accountId: number,\n workspaceId: string,\n updates: AdminWorkspaceMemberFormData\n ): Promise<AdminAccountMembership> {\n return this.fetch<AdminAccountMembership>(\n `admin/accounts/${accountId}/memberships/${workspaceId}`,\n {\n method: 'PUT',\n body: JSON.stringify(updates),\n }\n );\n }\n\n async createAccountMembership(\n accountId: number,\n workspaceId: string,\n data: { memberRoleId: number }\n ): Promise<AdminAccountMembership> {\n return this.fetch<AdminAccountMembership>(\n `admin/accounts/${accountId}/memberships/${workspaceId}`,\n {\n method: 'POST',\n body: JSON.stringify(data),\n }\n );\n }\n\n async deleteAccountMembership(accountId: number, workspaceId: string): Promise<void> {\n return this.fetch<void>(`admin/accounts/${accountId}/memberships/${workspaceId}`, {\n method: 'DELETE',\n });\n }\n\n async updateAccountAsAdmin(\n id: string | number,\n updates: AdminAccountFormData\n ): Promise<AdminAccount> {\n return this.fetch<AdminAccount>(`admin/accounts/${id}`, {\n method: 'PUT',\n body: JSON.stringify(updates),\n });\n }\n\n async createAccountAsAdmin(data: AdminAccountFormData): Promise<AdminAccount> {\n return this.fetch<AdminAccount>('admin/accounts', {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async deleteAccountAsAdmin(id: number): Promise<void> {\n return this.fetch(`admin/accounts/${id}`, {\n method: 'DELETE',\n });\n }\n\n // GDPR Data Subject Rights (superuser only)\n\n async exportAccountData(accountId: number): Promise<DataExportResponse> {\n return this.fetch(`admin/data-rights/${accountId}/export`, {\n method: 'POST',\n });\n }\n\n async requestAccountDeletion(accountId: number): Promise<DeletionRequestResponse> {\n return this.fetch(`admin/data-rights/${accountId}/delete`, {\n method: 'POST',\n });\n }\n\n async cancelAccountDeletion(accountId: number): Promise<DeletionCancelResponse> {\n return this.fetch(`admin/data-rights/${accountId}/cancel-delete`, {\n method: 'POST',\n });\n }\n\n /**\n * Look up an account by email or phone. Returns verification status.\n * Used to check if a verified account exists before creating a new one.\n */\n async lookupAccount(options: {\n email?: string;\n phone?: string;\n }): Promise<AccountLookupResponse> {\n const params = new URLSearchParams();\n if (options.email) params.append('email', options.email);\n if (options.phone) params.append('phone', options.phone);\n\n return this.fetch<AccountLookupResponse>(`admin/accounts/lookup?${params.toString()}`);\n }\n\n // Admin Organizations API\n async getOrganizations(options?: {\n search?: string;\n page?: number;\n pageSize?: number;\n noSubscription?: boolean;\n sortBy?: string;\n sortOrder?: 'asc' | 'desc';\n }): Promise<PaginatedResponse<AdminOrganization>> {\n const params = new URLSearchParams();\n if (options?.search) params.append('search', options.search);\n if (options?.page) params.append('page', options.page.toString());\n if (options?.pageSize) params.append('pageSize', options.pageSize.toString());\n if (options?.noSubscription) params.append('no_subscription', 'true');\n if (options?.sortBy) params.append('sortBy', options.sortBy);\n if (options?.sortOrder) params.append('sortOrder', options.sortOrder);\n\n return this.fetch<PaginatedResponse<AdminOrganization>>(\n `admin/organizations?${params.toString()}`\n );\n }\n\n /**\n * Get organization by ID or UUID.\n * Returns different response based on user's role:\n * - Admins/Owners: AdminOrganization with full details\n * - Members: MemberOrgView with basic info and workspace list\n *\n * Use `viewType` field to determine the response type:\n * - 'admin': AdminOrganization\n * - 'member': MemberOrgView\n */\n async getOrganization(idOrUuid: number | string): Promise<AdminOrganization | MemberOrgView> {\n return this.fetch<AdminOrganization | MemberOrgView>(`o/${idOrUuid}`);\n }\n\n /**\n * Get organization by numeric ID or UUID via admin endpoint.\n * Does NOT require organization membership — superuser-only.\n */\n async getOrganizationAsAdmin(idOrUuid: number | string): Promise<AdminOrganization> {\n return this.fetch<AdminOrganization>(`admin/organizations/${idOrUuid}`);\n }\n\n async getOrganizationMembersAsAdmin(\n organizationId: number,\n options?: { search?: string; role?: string; page?: number; pageSize?: number }\n ): Promise<PaginatedResponse<OrgMember>> {\n const params = new URLSearchParams();\n if (options?.search) params.append('search', options.search);\n if (options?.role) params.append('role', options.role);\n if (options?.page) params.append('page', options.page.toString());\n if (options?.pageSize) params.append('pageSize', options.pageSize.toString());\n const qs = params.toString();\n return this.fetch<PaginatedResponse<OrgMember>>(\n `admin/organizations/${organizationId}/members${qs ? `?${qs}` : ''}`\n );\n }\n\n async createOrganization(data: CreateOrganizationRequest): Promise<AdminOrganization> {\n return this.fetch<AdminOrganization>('admin/organizations', {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateOrganization(\n id: number,\n data: UpdateOrganizationRequest\n ): Promise<AdminOrganization> {\n return this.fetch<AdminOrganization>(`admin/organizations/${id}`, {\n method: 'PUT',\n body: JSON.stringify(data),\n });\n }\n\n async deleteOrganization(id: number): Promise<void> {\n return this.fetch(`admin/organizations/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * Join an organization with a specified role (superuser only).\n * Creates or updates membership in the target org.\n * @param orgUuid - Organization UUID or numeric ID as string\n */\n async joinOrganization(\n orgUuid: string,\n role: 'member' | 'admin' | 'owner' = 'owner'\n ): Promise<{\n accountId: number;\n organizationId: number;\n organizationUuid: string;\n email: string | null;\n role: string;\n message: string;\n }> {\n return this.fetch(`admin/organizations/${orgUuid}/join`, {\n method: 'POST',\n body: JSON.stringify({ role }),\n });\n }\n\n /**\n * Leave an organization (superuser only).\n * @param orgUuid - Organization UUID or numeric ID as string\n */\n async leaveOrganization(orgUuid: string): Promise<{ status: string; message: string }> {\n return this.fetch(`admin/organizations/${orgUuid}/join`, {\n method: 'DELETE',\n });\n }\n\n async generateLogoUploadUrl(\n organizationUuid: string,\n data: LogoUploadRequest\n ): Promise<LogoUploadResponse> {\n return this.fetch<LogoUploadResponse>(`o/${organizationUuid}/logo-upload-url`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n // Organization Members API - moved to OrgApi at /api/v2/o/{org_uuid}/members\n // See packages/client/src/api/org.ts\n\n // Organization Invitations API - moved to OrgApi at /api/v2/o/{org_uuid}/invitations\n // See packages/client/src/api/org.ts\n\n // Admin Products API\n async importProducts(workspaceId: number): Promise<void> {\n return this.fetch('admin/import-products', {\n method: 'POST',\n body: JSON.stringify({ workspaceId }),\n });\n }\n\n // ===== Product CRUD =====\n\n async createProductAsAdmin(product: CreateProductRequest): Promise<Product> {\n return this.fetch<Product>('admin/products', {\n method: 'POST',\n body: JSON.stringify(product),\n });\n }\n\n async getProductsAsAdmin(workspaceUuid?: string, productTypes?: string[]): Promise<Product[]> {\n const params = new URLSearchParams();\n if (workspaceUuid) {\n params.append('workspace_uuid', workspaceUuid);\n }\n if (productTypes && productTypes.length > 0) {\n productTypes.forEach((type) => params.append('product_types', type));\n }\n const queryString = params.toString();\n return this.fetch<Product[]>(`admin/products${queryString ? `?${queryString}` : ''}`);\n }\n\n async getProductAsAdmin(productId: number): Promise<Product> {\n return this.fetch<Product>(`admin/products/${productId}`);\n }\n\n async updateProductAsAdmin(\n product_id: number,\n product: AdminUpdateProductRequest\n ): Promise<Product> {\n return this.fetch<Product>(`admin/products/${product_id}`, {\n method: 'PUT',\n body: JSON.stringify(product),\n });\n }\n\n async deleteProductAsAdmin(productId: number): Promise<{ message: string }> {\n return this.fetch<{ message: string }>(`admin/products/${productId}`, {\n method: 'DELETE',\n });\n }\n\n // Admin Workspace API\n async getWorkspacesAsAdmin(\n options: {\n page?: number;\n pageSize?: number;\n sortBy?: WorkspaceSortField;\n sortOrder?: SortOrder;\n search?: string;\n isReseller?: boolean;\n organizationId?: number;\n noActiveSubscription?: boolean;\n } = {}\n ): Promise<PaginatedResponse<AdminWorkspace>> {\n const params = new URLSearchParams();\n if (options.page !== undefined) params.append('page', options.page.toString());\n if (options.pageSize !== undefined) params.append('pageSize', options.pageSize.toString());\n if (options.sortBy) params.append('sortBy', options.sortBy);\n if (options.sortOrder) params.append('sortOrder', options.sortOrder);\n if (options.search) params.append('search', options.search);\n if (options.isReseller !== undefined)\n params.append('isReseller', options.isReseller.toString());\n if (options.organizationId !== undefined)\n params.append('organizationId', options.organizationId.toString());\n if (options.noActiveSubscription) params.append('noActiveSubscription', 'true');\n\n return this.fetch<PaginatedResponse<AdminWorkspace>>(`admin/workspaces?${params.toString()}`);\n }\n\n async getWorkspaceAsAdmin(wid: string): Promise<AdminWorkspace> {\n return this.fetch<AdminWorkspace>(`admin/workspaces/${wid}`);\n }\n\n async getWorkspaceByNumericIdAsAdmin(workspace_id: number): Promise<AdminWorkspace> {\n return this.fetch<AdminWorkspace>(`admin/workspaces/id/${workspace_id}`);\n }\n\n async createWorkspaceAsAdmin(ws: AdminWorkspaceFormData): Promise<Workspace> {\n return this.fetch<Workspace>('admin/workspaces', {\n method: 'POST',\n body: JSON.stringify(ws),\n });\n }\n\n async updateWorkspaceAsAdmin(wid: string, ws: AdminWorkspaceFormData): Promise<Workspace> {\n return this.fetch<Workspace>(`admin/workspaces/${wid}`, {\n method: 'PUT',\n body: JSON.stringify(ws),\n });\n }\n\n async deleteWorkspaceAsAdmin(wid: string): Promise<void> {\n return this.fetch(`admin/workspaces/${wid}`, {\n method: 'DELETE',\n });\n }\n\n async createSchemaAsAdmin(wid: string): Promise<AdminWorkspace> {\n return this.fetch(`admin/workspaces/${wid}/provision/create`, {\n method: 'POST',\n });\n }\n\n async migrateSchemaAsAdmin(wid: string): Promise<AdminWorkspace> {\n return this.fetch(`admin/workspaces/${wid}/provision/migrate`, {\n method: 'POST',\n });\n }\n\n async provisionWorkspaceAsAdmin(wid: string): Promise<AdminWorkspace> {\n return this.fetch(`admin/workspaces/${wid}/provision`, {\n method: 'POST',\n });\n }\n\n async refreshProvisionStatusAsAdmin(wid: string): Promise<AdminWorkspace> {\n return this.fetch(`admin/workspaces/${wid}/provision/refresh`, {\n method: 'POST',\n });\n }\n\n async enableMaintenanceMode(wid: string): Promise<AdminWorkspace> {\n return this.fetch(`admin/workspaces/${wid}/maintenance`, {\n method: 'PUT',\n });\n }\n\n async disableMaintenanceMode(wid: string): Promise<AdminWorkspace> {\n return this.fetch(`admin/workspaces/${wid}/maintenance`, {\n method: 'DELETE',\n });\n }\n\n // ===== Workspace Health Check =====\n\n async getWorkspaceHealth(workspaceUuid: string): Promise<WorkspaceHealthResponse> {\n return this.fetch<WorkspaceHealthResponse>(`admin/workspaces/${workspaceUuid}/health`);\n }\n\n async provisionPlanFeatures(\n workspaceUuid: string,\n request?: ProvisionPlanRequest\n ): Promise<ProvisionPlanResponse> {\n return this.fetch<ProvisionPlanResponse>(`admin/workspaces/${workspaceUuid}/provision-plan`, {\n method: 'POST',\n body: JSON.stringify(request || {}),\n });\n }\n\n /**\n * Switch a workspace's plan product on its active SubscriptionItem.\n *\n * Superuser only. Re-syncs ``workspace.features`` from the new product\n * and emits a ``WORKSPACE_PRODUCT_CHANGED`` audit event identifying the\n * actor, target workspace, prior and new product, and feature diff.\n *\n * Stripe is not touched here; price-id changes belong to the dedicated\n * Stripe sync surface (``syncProductToStripe``).\n */\n async changeWorkspaceProduct(\n workspaceUuid: string,\n productId: number\n ): Promise<ChangeWorkspaceProductResponse> {\n const body: ChangeWorkspaceProductRequest = { productId };\n return this.fetch<ChangeWorkspaceProductResponse>(\n `admin/workspaces/${workspaceUuid}/product`,\n {\n method: 'POST',\n body: JSON.stringify(body),\n }\n );\n }\n\n // ===== Workflow Access Validation =====\n\n async validateWorkflowAccessAsAdmin(\n workspaceUuid?: string\n ): Promise<AdminBulkWorkflowAccessValidationResponse> {\n const params = new URLSearchParams();\n if (workspaceUuid) params.append('workspace_uuid', workspaceUuid);\n const qs = params.toString();\n return this.fetch<AdminBulkWorkflowAccessValidationResponse>(\n `admin/workspaces/validate-workflow-access${qs ? `?${qs}` : ''}`\n );\n }\n\n async mergeMembers(wid: string, request: MergeMembersRequest): Promise<MergeMembersResponse> {\n return this.fetch<MergeMembersResponse>(`admin/workspaces/${wid}/merge-members`, {\n method: 'POST',\n body: JSON.stringify(request),\n });\n }\n\n async getAdminWorkspaceMember(wid: string): Promise<Member> {\n return this.fetch(`admin/workspaces/${wid}/me`, {\n method: 'GET',\n });\n }\n\n async createAdminWorkspaceMember(\n wid: string,\n data: AdminWorkspaceMemberFormData\n ): Promise<void> {\n return this.fetch(`admin/workspaces/${wid}/me`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateAdminWorkspaceMember(\n wid: string,\n data: AdminWorkspaceMemberFormData\n ): Promise<void> {\n return this.fetch(`admin/workspaces/${wid}/me`, {\n method: 'PUT',\n body: JSON.stringify(data),\n });\n }\n\n async unarchiveAdminWorkspaceMember(wid: string): Promise<Member> {\n return this.fetch(`admin/workspaces/${wid}/me/unarchive`, {\n method: 'POST',\n });\n }\n\n async getAdminWorkspaceMemberRoles(wid: string): Promise<MemberRole[]> {\n return this.fetch<MemberRole[]>(`admin/workspaces/${wid}/member-roles`);\n }\n\n async getUnmappedPhoneNumbers(): Promise<UnmappedPhoneNumber[]> {\n return this.fetch<UnmappedPhoneNumber[]>(`admin/phone-numbers/unmapped`);\n }\n\n async getWorkspaceUnmappedPhoneNumbers(workspaceId: number): Promise<UnmappedPhoneNumber[]> {\n return this.fetch<UnmappedPhoneNumber[]>(\n `admin/phone-numbers/workspace/${workspaceId}/unmapped`\n );\n }\n\n async getWorkspacePhoneNumbersAsAdmin(workspaceRef: string): Promise<PhoneNumber[]> {\n return this.fetch<PhoneNumber[]>(`admin/workspaces/${workspaceRef}/phone-numbers`);\n }\n\n // Phone Numbers API (Provider phone numbers from Twilio, AWS, etc.)\n async getProviderPhoneNumbers(\n options: {\n search?: string;\n isAssigned?: boolean;\n provider?: string;\n organizationId?: number;\n sortBy?: string;\n sortOrder?: string;\n page?: number;\n pageSize?: number;\n } = {}\n ): Promise<PaginatedResponse<ProviderPhoneNumber>> {\n const params = new URLSearchParams();\n if (options.page) params.append('page', options.page.toString());\n if (options.pageSize) params.append('pageSize', options.pageSize.toString());\n if (options.search) params.append('search', options.search);\n if (options.isAssigned !== undefined)\n params.append('is_assigned', String(options.isAssigned));\n if (options.provider) params.append('provider', options.provider);\n if (options.organizationId !== undefined)\n params.append('organizationId', options.organizationId.toString());\n if (options.sortBy) params.append('sortBy', options.sortBy);\n if (options.sortOrder) params.append('sortOrder', options.sortOrder);\n\n return this.fetch<PaginatedResponse<ProviderPhoneNumber>>(\n `admin/phone-numbers${params.toString() ? `?${params.toString()}` : ''}`\n );\n }\n\n async getProviderPhoneNumber(id: number): Promise<ProviderPhoneNumber> {\n return this.fetch<ProviderPhoneNumber>(`admin/phone-numbers/${id}`);\n }\n\n async updateProviderPhoneNumber(\n id: number,\n data: { organizationId: number | null }\n ): Promise<ProviderPhoneNumber> {\n return this.fetch<ProviderPhoneNumber>(`admin/phone-numbers/${id}`, {\n method: 'PATCH',\n body: JSON.stringify(data),\n });\n }\n\n async mapMainAccountPhone(data: {\n phoneNumber: string;\n workspaceUuid: string;\n name?: string;\n }): Promise<ProviderPhoneNumber> {\n return this.fetch<ProviderPhoneNumber>(`admin/phone-numbers/map-from-main-account`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async unmapPhoneNumber(data: {\n phoneNumber: string;\n }): Promise<{ status: string; phoneNumber: string }> {\n return this.fetch<{ status: string; phoneNumber: string }>(`admin/phone-numbers/unmap`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async searchAvailablePhoneNumbersAsAdmin(data: {\n organizationId: number;\n country?: string;\n numberType?: string;\n areaCode?: string;\n contains?: string;\n limit?: number;\n }): Promise<\n Array<{\n phoneNumber: string;\n friendlyName: string;\n locality: string | null;\n region: string | null;\n isoCountry: string;\n voiceEnabled: boolean;\n smsEnabled: boolean;\n }>\n > {\n return this.fetch(`admin/phone-numbers/search`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async purchasePhoneNumberAsAdmin(data: {\n organizationId: number;\n phoneNumber: string;\n numberType?: string;\n }): Promise<ProviderPhoneNumber> {\n return this.fetch<ProviderPhoneNumber>(`admin/phone-numbers/purchase`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async getOrgA2PStatusAsAdmin(organizationId: number): Promise<OrgA2PStatus> {\n return this.fetch<OrgA2PStatus>(`admin/organizations/${organizationId}/a2p-status`);\n }\n\n async resetOrgA2PStatusAsAdmin(organizationId: number): Promise<{ status: string }> {\n return this.fetch(`admin/organizations/${organizationId}/a2p-status`, {\n method: 'DELETE',\n });\n }\n\n // Site Mappings API\n async getSiteMappings(options?: {\n search?: string;\n page?: number;\n pageSize?: number;\n }): Promise<PaginatedResponse<SiteMapping>> {\n const queryParams = new URLSearchParams();\n if (options?.search) queryParams.append('search', options.search);\n if (options?.page) queryParams.append('page', options.page.toString());\n if (options?.pageSize) queryParams.append('pageSize', options.pageSize.toString());\n\n const queryString = queryParams.toString();\n const url = `admin/site-mappings${queryString ? `?${queryString}` : ''}`;\n\n return this.fetch<PaginatedResponse<SiteMapping>>(url);\n }\n\n async getSiteMapping(siteId: number): Promise<SiteMapping> {\n return this.fetch<SiteMapping>(`admin/site-mappings/${siteId}`);\n }\n\n async updateSiteMapping(siteId: number, data: SiteMappingFormData): Promise<SiteMapping> {\n return this.fetch<SiteMapping>(`admin/site-mappings/${siteId}`, {\n method: 'PUT',\n body: JSON.stringify(data),\n });\n }\n\n async updateSiteMappingWorkspace(siteId: number, workspaceId: number): Promise<SiteMapping> {\n return this.updateSiteMapping(siteId, {\n workspaceId,\n siteUuid: '', // These fields are required by the type but will be ignored on the server\n });\n }\n\n async adminDeleteSiteMapping(siteId: number): Promise<void> {\n return this.fetch<void>(`admin/site-mappings/${siteId}`, {\n method: 'DELETE',\n });\n }\n\n async createSiteMapping(mapping: SiteMappingFormData): Promise<SiteMapping> {\n return this.fetch<SiteMapping>(`admin/site-mappings`, {\n method: 'POST',\n body: JSON.stringify(mapping),\n });\n }\n\n // Keep for backward compatibility\n async createOrUpdateSiteMapping(\n wid: string,\n mapping: SiteMappingFormData\n ): Promise<SiteMapping> {\n return this.fetch<SiteMapping>(`admin/workspaces/${wid}/site-mappings`, {\n method: 'POST',\n body: JSON.stringify(mapping),\n });\n }\n\n async deleteSiteMapping(wid: string, siteUuid: string): Promise<void> {\n return this.fetch(`admin/workspaces/${wid}/site-mappings/${siteUuid}`, {\n method: 'DELETE',\n });\n }\n\n async getWorkspaceInboxesAsAdmin(\n workspaceUuid: string\n ): Promise<{ items: Inbox[]; total: number }> {\n return this.fetch<{ items: Inbox[]; total: number }>(\n `admin/workspaces/${workspaceUuid}/inboxes`\n );\n }\n\n // Admin Inbox Mappings API\n async getInboxMappings(\n options: {\n page?: number;\n pageSize?: number;\n search?: string;\n workspaceId?: number;\n } = {}\n ): Promise<PaginatedResponse<InboxMappingDetailResponse>> {\n const params = new URLSearchParams();\n if (options.page) params.append('page', options.page.toString());\n if (options.pageSize) params.append('pageSize', options.pageSize.toString());\n if (options.search) params.append('search', options.search);\n if (options.workspaceId) params.append('workspaceId', options.workspaceId.toString());\n\n return this.fetch<PaginatedResponse<InboxMappingDetailResponse>>(\n `admin/inbox-mappings${params.toString() ? `?${params.toString()}` : ''}`\n );\n }\n\n async getInboxMapping(id: number): Promise<InboxMappingDetailResponse> {\n return this.fetch<InboxMappingDetailResponse>(`admin/inbox-mappings/${id}`);\n }\n\n async updateInboxMapping(id: number, workspaceId: number): Promise<InboxMappingDetailResponse> {\n return this.fetch<InboxMappingDetailResponse>(`admin/inbox-mappings/${id}`, {\n method: 'PUT',\n body: JSON.stringify({ workspaceId }),\n });\n }\n\n async deleteAdminInboxMapping(id: number): Promise<void> {\n return this.fetch(`admin/inbox-mappings/${id}`, {\n method: 'DELETE',\n });\n }\n\n // Evaluation API\n async generateChatSummaries(options: {\n afterDate?: Date;\n onlyWithoutSummaries?: boolean;\n }): Promise<GenerateSummariesResponse> {\n return this.fetch<GenerateSummariesResponse>('admin/generate-summaries', {\n method: 'POST',\n body: JSON.stringify({\n after_date: options.afterDate\n ? options.afterDate.toISOString().split('T')[0] +\n 'T' +\n options.afterDate.toTimeString().split(' ')[0]\n : undefined,\n only_without_summaries: options.onlyWithoutSummaries ?? true,\n }),\n });\n }\n\n async executeQuery(options: { query: string; workspaceUuid?: string }): Promise<{\n columns: string[];\n rows: any[][];\n rowCount: number;\n }> {\n return this.fetch<{\n columns: string[];\n rows: any[][];\n rowCount: number;\n }>('admin/execute-query', {\n method: 'POST',\n body: JSON.stringify({\n query: options.query,\n workspace_uuid: options.workspaceUuid,\n }),\n });\n }\n\n /**\n * Resolve a Langfuse trace UI URL from a trace ID, chat ID, or message ID.\n *\n * URL-only: never fetches Langfuse payloads, Message content, or\n * tool arguments. Exactly one of ``traceId``, ``chatId``, or\n * ``messageId`` must be set; chat/message forms require a\n * workspaceUuid. See\n * docs/development/observability/llm-call-investigation.md.\n */\n async getTraceUrl(options: {\n traceId?: string;\n chatId?: number;\n messageId?: string;\n workspaceUuid?: string;\n }): Promise<{\n trace_id: string | null;\n observation_id: string | null;\n langfuse_url: string | null;\n }> {\n return this.fetch<{\n trace_id: string | null;\n observation_id: string | null;\n langfuse_url: string | null;\n }>('admin/trace/url', {\n method: 'POST',\n body: JSON.stringify({\n trace_id: options.traceId,\n chat_id: options.chatId,\n message_id: options.messageId,\n workspace_uuid: options.workspaceUuid,\n }),\n });\n }\n\n // Admin Themes API\n async listAllThemes(): Promise<ThemesListResponse> {\n return this.fetch<ThemesListResponse>('admin/themes/list');\n }\n\n // Missing Memberships API\n async getMissingMemberships(workspaceId: string): Promise<MissingMembershipItem[]> {\n return this.fetch<MissingMembershipItem[]>(\n `admin/workspaces/${workspaceId}/missing-memberships`\n );\n }\n\n async linkMissingMembership(\n workspaceId: string,\n memberId: number,\n accountId: number\n ): Promise<{ success: boolean; message: string }> {\n return this.fetch<{ success: boolean; message: string }>(\n `admin/workspaces/${workspaceId}/link-membership?member_id=${memberId}&account_id=${accountId}`,\n {\n method: 'POST',\n }\n );\n }\n\n // Bulk Phone Classification API\n async startBulkPhoneClassification(\n workspaceUuid: string,\n includeUnknown: boolean = false\n ): Promise<{\n success: boolean;\n message: string;\n job_id: string;\n workspace_uuid: string;\n include_unknown: boolean;\n }> {\n const params = new URLSearchParams();\n params.append('include_unknown', includeUnknown.toString());\n\n return this.fetch<{\n success: boolean;\n message: string;\n job_id: string;\n workspace_uuid: string;\n include_unknown: boolean;\n }>(`admin/workspaces/${workspaceUuid}/bulk-classify-phones?${params.toString()}`, {\n method: 'POST',\n });\n }\n\n // Bulk TOS Acceptance API\n async startBulkTOSAcceptance(workspaceUuid: string): Promise<{\n success: boolean;\n message: string;\n updated_count: number;\n workspace_uuid: string;\n }> {\n return this.fetch<{\n success: boolean;\n message: string;\n updated_count: number;\n workspace_uuid: string;\n }>(`admin/workspaces/${workspaceUuid}/bulk-accept-tos`, {\n method: 'POST',\n });\n }\n\n // Token Usage Backfill API\n async startTokenUsageBackfill(workspaceUuid: string): Promise<{\n success: boolean;\n message: string;\n job_id: string;\n workspace_uuid: string;\n }> {\n return this.fetch<{\n success: boolean;\n message: string;\n job_id: string;\n workspace_uuid: string;\n }>(`admin/workspaces/${workspaceUuid}/backfill-token-usage`, {\n method: 'POST',\n });\n }\n\n // ===== Admin Chat Endpoints =====\n\n async listWorkspaceChats(\n workspaceUuid: string,\n options?: AdminChatsOptions\n ): Promise<PaginatedResponse<AdminChat>> {\n const params = new URLSearchParams();\n if (options?.page) params.set('page', String(options.page));\n if (options?.pageSize) params.set('pageSize', String(options.pageSize));\n if (options?.search) params.set('search', options.search);\n if (options?.chatType) params.set('chatType', options.chatType);\n if (options?.channel) params.set('channel', options.channel);\n if (options?.archived !== undefined) params.set('archived', String(options.archived));\n const qs = params.toString();\n return this.fetch<PaginatedResponse<AdminChat>>(\n `admin/workspaces/${workspaceUuid}/chats${qs ? `?${qs}` : ''}`\n );\n }\n\n async getWorkspaceChat(\n workspaceUuid: string,\n chatId: number,\n options?: { page?: number; pageSize?: number }\n ): Promise<AdminChatDetail> {\n const params = new URLSearchParams();\n if (options?.page) params.set('page', String(options.page));\n if (options?.pageSize) params.set('pageSize', String(options.pageSize));\n const qs = params.toString();\n return this.fetch<AdminChatDetail>(\n `admin/workspaces/${workspaceUuid}/chats/${chatId}${qs ? `?${qs}` : ''}`\n );\n }\n\n // Update chat message content\n async updateChatMessage(\n workspaceUuid: string,\n chatId: number,\n messageId: string,\n content: string\n ): Promise<{\n success: boolean;\n message: string;\n messageId: string;\n chatId: number;\n workspaceUuid: string;\n }> {\n return this.fetch<{\n success: boolean;\n message: string;\n messageId: string;\n chatId: number;\n workspaceUuid: string;\n }>(`admin/workspaces/${workspaceUuid}/chats/${chatId}/messages/${messageId}`, {\n method: 'POST',\n body: JSON.stringify({ content }),\n });\n }\n\n async rateWorkspaceChatMessage(\n workspaceUuid: string,\n chatId: number,\n messageId: string,\n rating: number,\n comment?: string\n ): Promise<{ status: string; detail?: string }> {\n return this.fetch<{ status: string; detail?: string }>(\n `admin/workspaces/${workspaceUuid}/chats/${chatId}/messages/${messageId}/rate`,\n {\n method: 'POST',\n body: JSON.stringify({ rating, comment }),\n }\n );\n }\n\n // ===== Stripe Customer Management =====\n\n async getStripeCustomer(accountId: number): Promise<StripeCustomer> {\n return this.fetch<StripeCustomer>(`admin/accounts/${accountId}/stripe/customer`);\n }\n\n async createStripeCustomer(\n accountId: number,\n data: StripeCustomerCreateRequest\n ): Promise<StripeCustomer> {\n return this.fetch<StripeCustomer>(`admin/accounts/${accountId}/stripe/customer`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateStripeCustomer(\n accountId: number,\n data: StripeCustomerUpdateRequest\n ): Promise<StripeCustomer> {\n return this.fetch<StripeCustomer>(`admin/accounts/${accountId}/stripe/customer`, {\n method: 'PUT',\n body: JSON.stringify(data),\n });\n }\n\n // ===== Customer Management =====\n\n async createCustomerFromAccount(accountId: number): Promise<Customer> {\n return this.fetch<Customer>(`admin/accounts/${accountId}/customer`, {\n method: 'POST',\n });\n }\n\n async getCustomers(options?: {\n search?: string;\n page?: number;\n pageSize?: number;\n }): Promise<PaginatedResponse<Customer>> {\n const params = new URLSearchParams();\n if (options?.search) params.set('search', options.search);\n if (options?.page) params.set('page', String(options.page));\n if (options?.pageSize) params.set('page_size', String(options.pageSize));\n const qs = params.toString();\n return this.fetch<PaginatedResponse<Customer>>(`admin/customers${qs ? `?${qs}` : ''}`);\n }\n\n async getCustomer(customerId: number): Promise<Customer> {\n return this.fetch<Customer>(`admin/customers/${customerId}`);\n }\n\n async createCustomer(data: CreateCustomerRequest): Promise<Customer> {\n return this.fetch<Customer>('admin/customers', {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateCustomer(customerId: number, data: UpdateCustomerRequest): Promise<Customer> {\n return this.fetch<Customer>(`admin/customers/${customerId}`, {\n method: 'PUT',\n body: JSON.stringify(data),\n });\n }\n\n async syncCustomerToStripe(customerId: number): Promise<Customer> {\n return this.fetch<Customer>(`admin/customers/${customerId}/stripe/sync`, {\n method: 'POST',\n });\n }\n\n async getCustomerAccounts(customerId: number): Promise<CustomerAccount[]> {\n return this.fetch<CustomerAccount[]>(`admin/customers/${customerId}/accounts`);\n }\n\n async linkCustomerToAccount(\n customerId: number,\n accountId: number,\n role?: string\n ): Promise<CustomerAccount> {\n return this.fetch<CustomerAccount>(`admin/customers/${customerId}/accounts`, {\n method: 'POST',\n body: JSON.stringify({ accountId, role }),\n });\n }\n\n async unlinkCustomerFromAccount(customerId: number, accountId: number): Promise<void> {\n await this.fetch<void>(`admin/customers/${customerId}/accounts/${accountId}`, {\n method: 'DELETE',\n });\n }\n\n // ===== Stripe Subscription Management =====\n\n async getStripeSubscriptions(accountId: number): Promise<Subscription[]> {\n return this.fetch<Subscription[]>(`admin/accounts/${accountId}/stripe/subscriptions`);\n }\n\n async createStripeSubscription(\n customerId: number,\n data: StripeSubscriptionCreateRequest\n ): Promise<Subscription> {\n return this.fetch<Subscription>(`admin/customers/${customerId}/stripe/subscriptions`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async createDirectSubscription(\n customerId: number,\n data: DirectSubscriptionCreateRequest\n ): Promise<Subscription> {\n return this.fetch<Subscription>(`admin/customers/${customerId}/direct/subscriptions`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateStripeSubscription(\n accountId: number,\n subscriptionId: string,\n data: StripeSubscriptionUpdateRequest\n ): Promise<Subscription> {\n return this.fetch<Subscription>(\n `admin/accounts/${accountId}/stripe/subscriptions/${subscriptionId}`,\n {\n method: 'PUT',\n body: JSON.stringify(data),\n }\n );\n }\n\n async cancelStripeSubscription(\n accountId: number,\n subscriptionId: string\n ): Promise<{ message: string; status: string }> {\n return this.fetch<{ message: string; status: string }>(\n `admin/accounts/${accountId}/stripe/subscriptions/${subscriptionId}`,\n {\n method: 'DELETE',\n }\n );\n }\n\n async provisionWorkspaceForSubscription(\n accountId: number,\n subscriptionId: string\n ): Promise<AdminWorkspace> {\n return this.fetch<AdminWorkspace>(\n `admin/accounts/${accountId}/stripe/subscriptions/${subscriptionId}/provision`,\n {\n method: 'POST',\n }\n );\n }\n\n async associateWorkspaceWithSubscription(\n accountId: number,\n subscriptionId: string,\n workspaceId: string | number\n ): Promise<Subscription> {\n return this.fetch<Subscription>(\n `admin/accounts/${accountId}/stripe/subscriptions/${subscriptionId}/associate?workspace_id=${workspaceId}`,\n {\n method: 'POST',\n }\n );\n }\n\n async createSubscriptionPaymentLink(\n accountId: number,\n subscriptionId: string\n ): Promise<{\n needsPayment: boolean;\n paymentUrl?: string;\n amountDue?: number;\n currency?: string;\n status: string;\n invoiceId?: string;\n invoiceStatus?: string;\n dueDate?: number;\n message?: string;\n }> {\n return this.fetch<{\n needsPayment: boolean;\n paymentUrl?: string;\n amountDue?: number;\n currency?: string;\n status: string;\n invoiceId?: string;\n invoiceStatus?: string;\n dueDate?: number;\n message?: string;\n }>(`admin/accounts/${accountId}/stripe/subscriptions/${subscriptionId}/payment-link`, {\n method: 'POST',\n });\n }\n\n // ===== Stripe Payment Methods Management =====\n\n async createSetupIntent(accountId: number): Promise<{\n clientSecret: string;\n setupIntentId: string;\n status: string;\n }> {\n return this.fetch<{\n clientSecret: string;\n setupIntentId: string;\n status: string;\n }>(`admin/accounts/${accountId}/stripe/setup-intent`, {\n method: 'POST',\n });\n }\n\n async getStripePaymentMethods(accountId: number): Promise<StripePaymentMethod[]> {\n return this.fetch<StripePaymentMethod[]>(\n `admin/accounts/${accountId}/stripe/payment-methods`\n );\n }\n\n async attachStripePaymentMethod(\n accountId: number,\n paymentMethodId: string,\n setAsDefault: boolean = false\n ): Promise<{\n success: boolean;\n message: string;\n paymentMethodId: string;\n type: string;\n }> {\n return this.fetch<{\n success: boolean;\n message: string;\n paymentMethodId: string;\n type: string;\n }>(`admin/accounts/${accountId}/stripe/payment-methods/${paymentMethodId}/attach`, {\n method: 'POST',\n body: JSON.stringify({ setAsDefault }),\n });\n }\n\n async detachStripePaymentMethod(\n accountId: number,\n paymentMethodId: string\n ): Promise<{ success: string; message: string }> {\n return this.fetch<{ success: string; message: string }>(\n `admin/accounts/${accountId}/stripe/payment-methods/${paymentMethodId}`,\n {\n method: 'DELETE',\n }\n );\n }\n\n async setDefaultStripePaymentMethod(\n accountId: number,\n paymentMethodId: string\n ): Promise<{ success: string; message: string }> {\n return this.fetch<{ success: string; message: string }>(\n `admin/accounts/${accountId}/stripe/payment-methods/${paymentMethodId}/set-default`,\n {\n method: 'PUT',\n }\n );\n }\n\n // ===== Convert Direct Subscription to Stripe =====\n\n async convertSubscriptionToStripe(\n customerId: number,\n subscriptionId: number\n ): Promise<Subscription> {\n return this.fetch<Subscription>(\n `admin/customers/${customerId}/subscriptions/${subscriptionId}/convert-to-stripe`,\n { method: 'POST' }\n );\n }\n\n // ===== Customer-Level Stripe Payment Methods =====\n\n async createCustomerSetupIntent(customerId: number): Promise<{\n clientSecret: string;\n setupIntentId: string;\n status: string;\n }> {\n return this.fetch<{\n clientSecret: string;\n setupIntentId: string;\n status: string;\n }>(`admin/customers/${customerId}/stripe/setup-intent`, {\n method: 'POST',\n });\n }\n\n async getCustomerPaymentMethods(customerId: number): Promise<StripePaymentMethod[]> {\n return this.fetch<StripePaymentMethod[]>(\n `admin/customers/${customerId}/stripe/payment-methods`\n );\n }\n\n async attachCustomerPaymentMethod(\n customerId: number,\n paymentMethodId: string,\n setAsDefault: boolean = false\n ): Promise<{\n success: boolean;\n message: string;\n paymentMethodId: string;\n type: string;\n }> {\n return this.fetch<{\n success: boolean;\n message: string;\n paymentMethodId: string;\n type: string;\n }>(`admin/customers/${customerId}/stripe/payment-methods/${paymentMethodId}/attach`, {\n method: 'POST',\n body: JSON.stringify({ setAsDefault }),\n });\n }\n\n async detachCustomerPaymentMethod(\n customerId: number,\n paymentMethodId: string\n ): Promise<{ success: string; message: string }> {\n return this.fetch<{ success: string; message: string }>(\n `admin/customers/${customerId}/stripe/payment-methods/${paymentMethodId}`,\n {\n method: 'DELETE',\n }\n );\n }\n\n async setDefaultCustomerPaymentMethod(\n customerId: number,\n paymentMethodId: string\n ): Promise<{ success: string; message: string }> {\n return this.fetch<{ success: string; message: string }>(\n `admin/customers/${customerId}/stripe/payment-methods/${paymentMethodId}/set-default`,\n {\n method: 'PUT',\n }\n );\n }\n\n // ===== Workspace Organization Migration =====\n\n async previewWorkspaceOrganizationChange(\n workspaceUuid: string,\n targetOrganizationId: number,\n newCreatorId: number\n ): Promise<{\n targetOrganization: { id: number; name: string };\n newCreator: { id: number; name: string; email: string };\n currentOrganization: { id: number | null; name: string | null };\n impact: {\n accountsToMove: number;\n accountsToDuplicate: number;\n accountsToRemap: number;\n totalMembers: number;\n };\n details: {\n movableAccounts: Array<{\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n }>;\n duplicateAccounts: Array<{\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n }>;\n remappableAccounts: Array<{\n currentAccount: {\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n };\n targetAccount: {\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n };\n }>;\n };\n }> {\n return this.fetch<{\n targetOrganization: { id: number; name: string };\n newCreator: { id: number; name: string; email: string };\n currentOrganization: { id: number | null; name: string | null };\n impact: {\n accountsToMove: number;\n accountsToDuplicate: number;\n accountsToRemap: number;\n totalMembers: number;\n };\n details: {\n movableAccounts: Array<{\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n }>;\n duplicateAccounts: Array<{\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n }>;\n remappableAccounts: Array<{\n currentAccount: {\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n };\n targetAccount: {\n id: number;\n uuid: string;\n name: string;\n email: string | null;\n phone: string | null;\n };\n }>;\n };\n }>(`admin/workspaces/${workspaceUuid}/change-org/preview`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n targetOrganizationId,\n newCreatorId,\n }),\n });\n }\n\n async changeWorkspaceOrganization(\n workspaceUuid: string,\n targetOrganizationId: number,\n newCreatorId: number\n ): Promise<{\n success: boolean;\n workspace: {\n uuid: string;\n name: string;\n organizationId: number;\n creatorId: number;\n };\n migration: {\n accountsMoved: number;\n accountsCreated: number;\n accountsRemapped: number;\n };\n }> {\n return this.fetch<{\n success: boolean;\n workspace: {\n uuid: string;\n name: string;\n organizationId: number;\n creatorId: number;\n };\n migration: {\n accountsMoved: number;\n accountsCreated: number;\n accountsRemapped: number;\n };\n }>(`admin/workspaces/${workspaceUuid}/change-org`, {\n method: 'POST',\n body: JSON.stringify({\n targetOrganizationId,\n newCreatorId,\n }),\n });\n }\n\n // ===== Stripe Invoice Management =====\n\n async createStripeInvoice(\n accountId: number,\n data: {\n customer: string;\n description?: string;\n collectionMethod: 'charge_automatically' | 'send_invoice';\n daysUntilDue?: number;\n autoAdvance?: boolean;\n metadata?: Record<string, string>;\n }\n ): Promise<{\n id: string;\n number: string;\n status: string;\n collectionMethod: string;\n amountDue: number;\n amountPaid: number;\n amountRemaining: number;\n currency: string;\n created: number;\n dueDate: number | null;\n paid: boolean;\n hostedInvoiceUrl: string | null;\n invoicePdf: string | null;\n customerEmail: string | null;\n description: string | null;\n }> {\n return this.fetch<{\n id: string;\n number: string;\n status: string;\n collectionMethod: string;\n amountDue: number;\n amountPaid: number;\n amountRemaining: number;\n currency: string;\n created: number;\n dueDate: number | null;\n paid: boolean;\n hostedInvoiceUrl: string | null;\n invoicePdf: string | null;\n customerEmail: string | null;\n description: string | null;\n }>(`admin/accounts/${accountId}/stripe/invoices`, {\n method: 'POST',\n body: JSON.stringify({\n customer: data.customer,\n description: data.description,\n collection_method: data.collectionMethod,\n days_until_due: data.daysUntilDue,\n auto_advance: data.autoAdvance,\n metadata: data.metadata,\n }),\n });\n }\n\n async getStripeInvoices(\n accountId: number,\n options?: { limit?: number; startingAfter?: string }\n ): Promise<\n Array<{\n id: string;\n number: string;\n status: string;\n collectionMethod: string;\n amountDue: number;\n amountPaid: number;\n amountRemaining: number;\n currency: string;\n created: number;\n dueDate: number | null;\n paid: boolean;\n hostedInvoiceUrl: string | null;\n invoicePdf: string | null;\n description: string | null;\n periodStart: number | null;\n periodEnd: number | null;\n }>\n > {\n const params = new URLSearchParams();\n if (options?.limit) params.append('limit', options.limit.toString());\n if (options?.startingAfter) params.append('starting_after', options.startingAfter);\n\n return this.fetch<\n Array<{\n id: string;\n number: string;\n status: string;\n collectionMethod: string;\n amountDue: number;\n amountPaid: number;\n amountRemaining: number;\n currency: string;\n created: number;\n dueDate: number | null;\n paid: boolean;\n hostedInvoiceUrl: string | null;\n invoicePdf: string | null;\n description: string | null;\n periodStart: number | null;\n periodEnd: number | null;\n }>\n >(`admin/accounts/${accountId}/stripe/invoices?${params.toString()}`);\n }\n\n async getStripeUpcomingInvoice(\n accountId: number,\n subscriptionId?: string\n ): Promise<{\n amountDue: number;\n amountPaid: number;\n amountRemaining: number;\n currency: string;\n periodStart: number;\n periodEnd: number;\n subtotal: number;\n tax: number;\n total: number;\n lineItems: Array<{\n id: string;\n description: string | null;\n amount: number;\n currency: string;\n quantity: number;\n unitAmount: number;\n productName: string | null;\n productDescription: string | null;\n period: {\n start: number;\n end: number;\n };\n }>;\n customer: string;\n subscription: string | null;\n }> {\n const params = new URLSearchParams();\n if (subscriptionId) params.append('subscription_id', subscriptionId);\n\n return this.fetch<{\n amountDue: number;\n amountPaid: number;\n amountRemaining: number;\n currency: string;\n periodStart: number;\n periodEnd: number;\n subtotal: number;\n tax: number;\n total: number;\n lineItems: Array<{\n id: string;\n description: string | null;\n amount: number;\n currency: string;\n quantity: number;\n unitAmount: number;\n productName: string | null;\n productDescription: string | null;\n period: {\n start: number;\n end: number;\n };\n }>;\n customer: string;\n subscription: string | null;\n }>(`admin/accounts/${accountId}/stripe/upcoming-invoice?${params.toString()}`);\n }\n\n // Billing Dashboard API\n async getWorkspaceUsageDashboard(workspaceUuid: string): Promise<UsageDashboardResponse> {\n return this.fetch<UsageDashboardResponse>(\n `admin/workspaces/${workspaceUuid}/usage-dashboard`\n );\n }\n\n // Product Stripe Sync API\n async compareProductsWithStripe(workspaceUuid?: string): Promise<CompareWithStripeResponse> {\n const params = workspaceUuid ? `?workspace_uuid=${encodeURIComponent(workspaceUuid)}` : '';\n return this.fetch<CompareWithStripeResponse>(`admin/products/compare-stripe${params}`);\n }\n\n async syncProductToStripe(\n productId: number,\n request?: SyncProductToStripeRequest\n ): Promise<SyncProductToStripeResponse> {\n return this.fetch<SyncProductToStripeResponse>(`admin/products/${productId}/sync-stripe`, {\n method: 'POST',\n body: JSON.stringify({ ...request, productId }),\n });\n }\n\n // Search Stripe products\n async searchStripeProducts(\n query: string,\n limit: number = 10\n ): Promise<\n Array<{\n id: string;\n name: string;\n description: string | null;\n active: boolean;\n created: number;\n metadata: Record<string, string>;\n }>\n > {\n const params = new URLSearchParams({ query, limit: limit.toString() });\n return this.fetch<\n Array<{\n id: string;\n name: string;\n description: string | null;\n active: boolean;\n created: number;\n metadata: Record<string, string>;\n }>\n >(`admin/products/stripe/search?${params.toString()}`);\n }\n\n // ===== Subscriptions API =====\n\n async getSubscriptionsAsAdmin(options?: {\n productId?: number;\n productType?: string;\n customerId?: number;\n organizationId?: number;\n accountId?: number;\n isDirect?: boolean;\n status?: string;\n page?: number;\n pageSize?: number;\n }): Promise<PaginatedSubscriptionsResponse> {\n const params = new URLSearchParams();\n if (options?.productId) params.append('product_id', options.productId.toString());\n if (options?.productType) params.append('product_type', options.productType);\n if (options?.customerId) params.append('customer_id', options.customerId.toString());\n if (options?.organizationId)\n params.append('organization_id', options.organizationId.toString());\n if (options?.accountId) params.append('account_id', options.accountId.toString());\n if (options?.isDirect !== undefined) params.append('is_direct', options.isDirect.toString());\n if (options?.status) params.append('status', options.status);\n if (options?.page) params.append('page', options.page.toString());\n if (options?.pageSize) params.append('page_size', options.pageSize.toString());\n const queryString = params.toString();\n return this.fetch<PaginatedSubscriptionsResponse>(\n `admin/subscriptions${queryString ? `?${queryString}` : ''}`\n );\n }\n\n async getSubscriptionAsAdmin(subscriptionId: number): Promise<Subscription> {\n return this.fetch<Subscription>(`admin/subscriptions/${subscriptionId}`);\n }\n\n async updateSubscriptionStatusAsAdmin(\n subscriptionId: number,\n subscriptionStatus: string\n ): Promise<Subscription> {\n return this.fetch<Subscription>(`admin/subscriptions/${subscriptionId}`, {\n method: 'PUT',\n body: JSON.stringify({ subscription_status: subscriptionStatus }),\n });\n }\n\n async updateSubscriptionCreditSettingsAsAdmin(\n subscriptionId: number,\n settings: {\n extra_usage_enabled?: boolean;\n reload_amount_cents?: number | null;\n reload_threshold_cents?: number | null;\n monthly_reload_limit_cents?: number | null;\n }\n ): Promise<Subscription> {\n return this.fetch<Subscription>(`admin/subscriptions/${subscriptionId}`, {\n method: 'PUT',\n body: JSON.stringify(settings),\n });\n }\n\n /** Grant credits to a subscription (superuser only). */\n async grantCreditsAsAdmin(\n subscriptionId: number,\n creditUnits: number,\n grantType: string,\n reason: string\n ): Promise<{\n success: boolean;\n grantId: number;\n creditUnits: number;\n grantedBy: string;\n reason: string;\n }> {\n return this.fetch(`admin/subscriptions/${subscriptionId}/grant-credits`, {\n method: 'POST',\n body: JSON.stringify({ credit_units: creditUnits, grant_type: grantType, reason }),\n });\n }\n\n /** List credit grants for a subscription (superuser only). */\n async listCreditGrantsAsAdmin(subscriptionId: number): Promise<\n {\n id: number;\n uuid: string;\n grantType: string;\n creditUnits: number;\n remainingUnits: number;\n amountCents: number;\n status: string;\n effectiveAt: string | null;\n expiresAt: string | null;\n createdAt: string | null;\n createdBy: string | null;\n reason: string | null;\n }[]\n > {\n return this.fetch(`admin/subscriptions/${subscriptionId}/credit-grants`);\n }\n\n // ===== Usage API =====\n\n async getUsageReport(request: UsageReportRequest): Promise<UsageReport> {\n return this.fetch<UsageReport>('admin/usage', {\n method: 'POST',\n body: JSON.stringify(request),\n });\n }\n\n // Voice Metrics API\n async getVoiceMetrics(options?: {\n hours?: number;\n period?: number;\n workspace_uuid?: string;\n organization_id?: number;\n engine?: string;\n channel?: string;\n }): Promise<VoiceMetricsResponse> {\n const params = new URLSearchParams();\n if (options?.hours) params.append('hours', options.hours.toString());\n if (options?.period) params.append('period', options.period.toString());\n if (options?.workspace_uuid) params.append('workspace_uuid', options.workspace_uuid);\n if (options?.organization_id != null)\n params.append('organization_id', options.organization_id.toString());\n if (options?.engine) params.append('engine', options.engine);\n if (options?.channel) params.append('channel', options.channel);\n const qs = params.toString();\n return this.fetch<VoiceMetricsResponse>(`admin/voice-metrics${qs ? `?${qs}` : ''}`);\n }\n\n // Health Dashboard API\n async getHealthMetrics(request: HealthMetricsRequest): Promise<HealthMetricsResponse> {\n return this.fetch<HealthMetricsResponse>('admin/health/metrics', {\n method: 'POST',\n body: JSON.stringify(request),\n });\n }\n\n async getHealthDetail(\n workspaceUuid: string,\n request: HealthDetailRequest\n ): Promise<WorkspaceHealthDetail> {\n return this.fetch<WorkspaceHealthDetail>(`admin/health/detail/${workspaceUuid}`, {\n method: 'POST',\n body: JSON.stringify(request),\n });\n }\n\n // ===== Reseller Management =====\n\n async getResellers(options?: {\n search?: string;\n page?: number;\n pageSize?: number;\n }): Promise<PaginatedResponse<Reseller>> {\n const params = new URLSearchParams();\n if (options?.search) params.set('search', options.search);\n if (options?.page) params.set('page', String(options.page));\n if (options?.pageSize) params.set('page_size', String(options.pageSize));\n const qs = params.toString();\n return this.fetch<PaginatedResponse<Reseller>>(`admin/resellers${qs ? `?${qs}` : ''}`);\n }\n\n async getReseller(resellerId: number): Promise<Reseller> {\n return this.fetch<Reseller>(`admin/resellers/${resellerId}`);\n }\n\n async createReseller(data: CreateResellerRequest): Promise<Reseller> {\n return this.fetch<Reseller>('admin/resellers', {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async updateReseller(resellerId: number, data: UpdateResellerRequest): Promise<Reseller> {\n return this.fetch<Reseller>(`admin/resellers/${resellerId}`, {\n method: 'PUT',\n body: JSON.stringify(data),\n });\n }\n\n async getResellerAccounts(resellerId: number): Promise<ResellerAccount[]> {\n return this.fetch<ResellerAccount[]>(`admin/resellers/${resellerId}/accounts`);\n }\n\n async linkResellerToAccount(\n resellerId: number,\n data: LinkResellerAccountRequest\n ): Promise<ResellerAccount> {\n return this.fetch<ResellerAccount>(`admin/resellers/${resellerId}/accounts`, {\n method: 'POST',\n body: JSON.stringify({ account_id: data.accountId, role: data.role }),\n });\n }\n\n async unlinkResellerFromAccount(resellerId: number, accountId: number): Promise<void> {\n await this.fetch<void>(`admin/resellers/${resellerId}/accounts/${accountId}`, {\n method: 'DELETE',\n });\n }\n\n // ===== Invoice Management =====\n\n async generateInvoice(data: {\n subscriptionId: number;\n periodStart: string;\n periodEnd: string;\n regenerate?: boolean;\n }): Promise<Invoice> {\n return this.fetch<Invoice>('admin/invoices/generate', {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n async getInvoices(\n subscriptionId?: number,\n pageOpts?: { page?: number; pageSize?: number }\n ): Promise<PaginatedResponse<Invoice>> {\n const params = new URLSearchParams();\n if (subscriptionId !== undefined) params.set('subscription_id', String(subscriptionId));\n if (pageOpts?.page !== undefined) params.set('page', String(pageOpts.page));\n if (pageOpts?.pageSize !== undefined) params.set('pageSize', String(pageOpts.pageSize));\n const qs = params.toString();\n return this.fetch<PaginatedResponse<Invoice>>(`admin/invoices${qs ? `?${qs}` : ''}`);\n }\n\n async getBillingPeriods(subscriptionId: number): Promise<BillingPeriod[]> {\n return this.fetch<BillingPeriod[]>(\n `admin/invoices/periods?subscription_id=${subscriptionId}`\n );\n }\n\n async getInvoiceDownloadUrl(\n invoiceId: number\n ): Promise<{ downloadUrl: string; invoiceNumber: string }> {\n return this.fetch<{ downloadUrl: string; invoiceNumber: string }>(\n `admin/invoices/${invoiceId}/download`\n );\n }\n\n async getReceiptDownloadUrl(\n invoiceId: number\n ): Promise<{ downloadUrl: string; invoiceNumber: string }> {\n return this.fetch<{ downloadUrl: string; invoiceNumber: string }>(\n `admin/invoices/${invoiceId}/receipt`\n );\n }\n\n async recordInvoicePayment(invoiceId: number, data: RecordPaymentRequest): Promise<Invoice> {\n return this.fetch<Invoice>(`admin/invoices/${invoiceId}/record-payment`, {\n method: 'POST',\n body: JSON.stringify(data),\n });\n }\n\n // ===== Admin Temporal Inspection (PHI-safe, read-only) =====\n\n /**\n * Server-enforced bounds for admin Temporal queries (lookback, thresholds,\n * page sizes, history event cap). Superuser only.\n */\n async getTemporalAdminConfig(): Promise<TemporalAdminConfig> {\n return this.fetch<TemporalAdminConfig>('admin/temporal/config');\n }\n\n /**\n * List recent Temporal workflows in FAILED, TIMED_OUT, or TERMINATED\n * status. Returns only PHI-safe operational metadata. Superuser only.\n *\n * Pass `options.status` to filter to a single status and enable\n * deep pagination via `nextPageToken`. Merged mode (no status) returns\n * the first page only and always emits `nextPageToken: null`.\n */\n async listFailedTemporalWorkflows(\n options: AdminTemporalFailedQuery = {}\n ): Promise<FailedWorkflowsResponse> {\n const params = new URLSearchParams();\n if (options.lookbackHours !== undefined)\n params.set('lookback_hours', String(options.lookbackHours));\n if (options.pageSize !== undefined) params.set('page_size', String(options.pageSize));\n if (options.status) params.set('status', String(options.status));\n if (options.nextPageToken) params.set('next_page_token', options.nextPageToken);\n appendTemporalWorkspaceParams(params, options);\n const qs = params.toString();\n return this.fetch<FailedWorkflowsResponse>(\n `admin/temporal/workflows/failed${qs ? `?${qs}` : ''}`\n );\n }\n\n /**\n * List open Temporal workflows older than the stuck threshold.\n * Superuser only.\n */\n async listStuckTemporalWorkflows(\n options: AdminTemporalStuckQuery = {}\n ): Promise<StuckWorkflowsResponse> {\n const params = new URLSearchParams();\n if (options.thresholdMinutes !== undefined)\n params.set('threshold_minutes', String(options.thresholdMinutes));\n if (options.pageSize !== undefined) params.set('page_size', String(options.pageSize));\n if (options.nextPageToken) params.set('next_page_token', options.nextPageToken);\n appendTemporalWorkspaceParams(params, options);\n const qs = params.toString();\n return this.fetch<StuckWorkflowsResponse>(\n `admin/temporal/workflows/stuck${qs ? `?${qs}` : ''}`\n );\n }\n\n /**\n * Return grouped counts for recent Temporal executions. Superuser only.\n */\n async getTemporalSummary(\n options: AdminTemporalSummaryQuery = {}\n ): Promise<TemporalSummaryResponse> {\n const params = new URLSearchParams();\n if (options.lookbackHours !== undefined)\n params.set('lookback_hours', String(options.lookbackHours));\n appendTemporalWorkspaceParams(params, options);\n const qs = params.toString();\n return this.fetch<TemporalSummaryResponse>(\n `admin/temporal/workflows/summary${qs ? `?${qs}` : ''}`\n );\n }\n\n /**\n * Fetch metadata + bounded sanitized history summary for one Temporal\n * workflow. Superuser only. Does not return raw events or payloads.\n */\n async getTemporalWorkflowDetail(\n workflowId: string,\n options: AdminTemporalDetailQuery = {}\n ): Promise<WorkflowDetailResponse> {\n const params = new URLSearchParams();\n if (options.runId) params.set('run_id', options.runId);\n appendTemporalWorkspaceParams(params, options);\n const qs = params.toString();\n const encoded = encodeURIComponent(workflowId);\n return this.fetch<WorkflowDetailResponse>(\n `admin/temporal/workflows/${encoded}${qs ? `?${qs}` : ''}`\n );\n }\n}\n\n/**\n * Append the workspace filter params for admin Temporal endpoints.\n *\n * The server accepts a repeated `workspace_uuid` query parameter. For\n * backward compatibility with callers (including `gr admin temporal`)\n * that still pass a single `workspaceUuid`, we normalize both inputs\n * into the same repeated-parameter wire shape: a single value is\n * appended once; explicit `workspaceUuids` entries are appended in\n * order. Duplicates and blanks are dropped client-side so the final\n * URL stays compact.\n */\nfunction appendTemporalWorkspaceParams(\n params: URLSearchParams,\n options: {\n workspaceUuid?: string;\n workspaceUuids?: string[];\n }\n): void {\n const seen = new Set<string>();\n const push = (raw: string | undefined) => {\n if (!raw) return;\n const trimmed = raw.trim();\n if (!trimmed || seen.has(trimmed)) return;\n seen.add(trimmed);\n params.append('workspace_uuid', trimmed);\n };\n if (options.workspaceUuids) {\n for (const value of options.workspaceUuids) push(value);\n }\n push(options.workspaceUuid);\n}\n","import { GravityRailClient } from '@gravity-rail/sdk';\nimport { AdminApi } from '../api/admin';\nimport { AdminBindings, bindAdminMethods } from './bindings/admin';\n\n/**\n * ApiClient extends GravityRailClient with admin/superuser methods.\n *\n * This is the full-featured client used internally. For the public SDK,\n * use {@link GravityRailClient} from @gravity-rail/sdk which excludes\n * admin functionality.\n */\nexport class ApiClient extends GravityRailClient implements AdminBindings {\n // Admin API\n listSupportRequestsAsAdmin!: AdminBindings['listSupportRequestsAsAdmin'];\n getSupportRequestAsAdmin!: AdminBindings['getSupportRequestAsAdmin'];\n commentOnSupportRequestAsAdmin!: AdminBindings['commentOnSupportRequestAsAdmin'];\n noteOnSupportRequestAsAdmin!: AdminBindings['noteOnSupportRequestAsAdmin'];\n updateSupportRequestStatusAsAdmin!: AdminBindings['updateSupportRequestStatusAsAdmin'];\n updateSupportRequestAttributesAsAdmin!: AdminBindings['updateSupportRequestAttributesAsAdmin'];\n createSupportRequestLinearIssueAsAdmin!: AdminBindings['createSupportRequestLinearIssueAsAdmin'];\n getAccounts!: AdminBindings['getAccounts'];\n getAccountDetails!: AdminBindings['getAccountDetails'];\n getAccountByUuid!: AdminBindings['getAccountByUuid'];\n getAccountMemberships!: AdminBindings['getAccountMemberships'];\n getAccountOrgMemberships!: AdminBindings['getAccountOrgMemberships'];\n createAccountOrgMembership!: AdminBindings['createAccountOrgMembership'];\n deleteAccountOrgMembership!: AdminBindings['deleteAccountOrgMembership'];\n getAccountMembership!: AdminBindings['getAccountMembership'];\n updateAccountMembership!: AdminBindings['updateAccountMembership'];\n createAccountMembership!: AdminBindings['createAccountMembership'];\n deleteAccountMembership!: AdminBindings['deleteAccountMembership'];\n updateAccountAsAdmin!: AdminBindings['updateAccountAsAdmin'];\n createAccountAsAdmin!: AdminBindings['createAccountAsAdmin'];\n deleteAccountAsAdmin!: AdminBindings['deleteAccountAsAdmin'];\n lookupAccount!: AdminBindings['lookupAccount'];\n exportAccountData!: AdminBindings['exportAccountData'];\n requestAccountDeletion!: AdminBindings['requestAccountDeletion'];\n cancelAccountDeletion!: AdminBindings['cancelAccountDeletion'];\n getOrganizations!: AdminBindings['getOrganizations'];\n getOrganization!: AdminBindings['getOrganization'];\n getOrganizationAsAdmin!: AdminBindings['getOrganizationAsAdmin'];\n getOrganizationMembersAsAdmin!: AdminBindings['getOrganizationMembersAsAdmin'];\n createOrganization!: AdminBindings['createOrganization'];\n updateOrganization!: AdminBindings['updateOrganization'];\n deleteOrganization!: AdminBindings['deleteOrganization'];\n joinOrganization!: AdminBindings['joinOrganization'];\n leaveOrganization!: AdminBindings['leaveOrganization'];\n generateLogoUploadUrl!: AdminBindings['generateLogoUploadUrl'];\n importProducts!: AdminBindings['importProducts'];\n createProductAsAdmin!: AdminBindings['createProductAsAdmin'];\n getProductsAsAdmin!: AdminBindings['getProductsAsAdmin'];\n getProductAsAdmin!: AdminBindings['getProductAsAdmin'];\n updateProductAsAdmin!: AdminBindings['updateProductAsAdmin'];\n deleteProductAsAdmin!: AdminBindings['deleteProductAsAdmin'];\n getWorkspacesAsAdmin!: AdminBindings['getWorkspacesAsAdmin'];\n getWorkspaceAsAdmin!: AdminBindings['getWorkspaceAsAdmin'];\n getWorkspaceByNumericIdAsAdmin!: AdminBindings['getWorkspaceByNumericIdAsAdmin'];\n createWorkspaceAsAdmin!: AdminBindings['createWorkspaceAsAdmin'];\n updateWorkspaceAsAdmin!: AdminBindings['updateWorkspaceAsAdmin'];\n deleteWorkspaceAsAdmin!: AdminBindings['deleteWorkspaceAsAdmin'];\n createSchemaAsAdmin!: AdminBindings['createSchemaAsAdmin'];\n migrateSchemaAsAdmin!: AdminBindings['migrateSchemaAsAdmin'];\n provisionWorkspaceAsAdmin!: AdminBindings['provisionWorkspaceAsAdmin'];\n refreshProvisionStatusAsAdmin!: AdminBindings['refreshProvisionStatusAsAdmin'];\n enableMaintenanceMode!: AdminBindings['enableMaintenanceMode'];\n disableMaintenanceMode!: AdminBindings['disableMaintenanceMode'];\n getWorkspaceHealth!: AdminBindings['getWorkspaceHealth'];\n provisionPlanFeatures!: AdminBindings['provisionPlanFeatures'];\n changeWorkspaceProduct!: AdminBindings['changeWorkspaceProduct'];\n validateWorkflowAccessAsAdmin!: AdminBindings['validateWorkflowAccessAsAdmin'];\n mergeMembers!: AdminBindings['mergeMembers'];\n getAdminWorkspaceMember!: AdminBindings['getAdminWorkspaceMember'];\n createAdminWorkspaceMember!: AdminBindings['createAdminWorkspaceMember'];\n updateAdminWorkspaceMember!: AdminBindings['updateAdminWorkspaceMember'];\n unarchiveAdminWorkspaceMember!: AdminBindings['unarchiveAdminWorkspaceMember'];\n getAdminWorkspaceMemberRoles!: AdminBindings['getAdminWorkspaceMemberRoles'];\n getMissingMemberships!: AdminBindings['getMissingMemberships'];\n linkMissingMembership!: AdminBindings['linkMissingMembership'];\n getUnmappedPhoneNumbers!: AdminBindings['getUnmappedPhoneNumbers'];\n getWorkspaceUnmappedPhoneNumbers!: AdminBindings['getWorkspaceUnmappedPhoneNumbers'];\n getWorkspacePhoneNumbersAsAdmin!: AdminBindings['getWorkspacePhoneNumbersAsAdmin'];\n getProviderPhoneNumbers!: AdminBindings['getProviderPhoneNumbers'];\n getProviderPhoneNumber!: AdminBindings['getProviderPhoneNumber'];\n updateProviderPhoneNumber!: AdminBindings['updateProviderPhoneNumber'];\n mapMainAccountPhone!: AdminBindings['mapMainAccountPhone'];\n unmapPhoneNumber!: AdminBindings['unmapPhoneNumber'];\n searchAvailablePhoneNumbersAsAdmin!: AdminBindings['searchAvailablePhoneNumbersAsAdmin'];\n purchasePhoneNumberAsAdmin!: AdminBindings['purchasePhoneNumberAsAdmin'];\n startBulkPhoneClassification!: AdminBindings['startBulkPhoneClassification'];\n getOrgA2PStatusAsAdmin!: AdminBindings['getOrgA2PStatusAsAdmin'];\n resetOrgA2PStatusAsAdmin!: AdminBindings['resetOrgA2PStatusAsAdmin'];\n getSiteMappings!: AdminBindings['getSiteMappings'];\n getSiteMapping!: AdminBindings['getSiteMapping'];\n updateSiteMapping!: AdminBindings['updateSiteMapping'];\n updateSiteMappingWorkspace!: AdminBindings['updateSiteMappingWorkspace'];\n adminDeleteSiteMapping!: AdminBindings['adminDeleteSiteMapping'];\n createSiteMapping!: AdminBindings['createSiteMapping'];\n createOrUpdateSiteMapping!: AdminBindings['createOrUpdateSiteMapping'];\n deleteSiteMapping!: AdminBindings['deleteSiteMapping'];\n getInboxMappings!: AdminBindings['getInboxMappings'];\n getInboxMapping!: AdminBindings['getInboxMapping'];\n updateInboxMapping!: AdminBindings['updateInboxMapping'];\n deleteAdminInboxMapping!: AdminBindings['deleteAdminInboxMapping'];\n generateChatSummaries!: AdminBindings['generateChatSummaries'];\n executeQuery!: AdminBindings['executeQuery'];\n getTraceUrl!: AdminBindings['getTraceUrl'];\n listAllThemes!: AdminBindings['listAllThemes'];\n startBulkTOSAcceptance!: AdminBindings['startBulkTOSAcceptance'];\n startTokenUsageBackfill!: AdminBindings['startTokenUsageBackfill'];\n updateChatMessage!: AdminBindings['updateChatMessage'];\n createCustomerFromAccount!: AdminBindings['createCustomerFromAccount'];\n getCustomers!: AdminBindings['getCustomers'];\n getCustomer!: AdminBindings['getCustomer'];\n createCustomer!: AdminBindings['createCustomer'];\n updateCustomer!: AdminBindings['updateCustomer'];\n getCustomerAccounts!: AdminBindings['getCustomerAccounts'];\n linkCustomerToAccount!: AdminBindings['linkCustomerToAccount'];\n unlinkCustomerFromAccount!: AdminBindings['unlinkCustomerFromAccount'];\n syncCustomerToStripe!: AdminBindings['syncCustomerToStripe'];\n getStripeCustomer!: AdminBindings['getStripeCustomer'];\n createStripeCustomer!: AdminBindings['createStripeCustomer'];\n updateStripeCustomer!: AdminBindings['updateStripeCustomer'];\n getStripeSubscriptions!: AdminBindings['getStripeSubscriptions'];\n createStripeSubscription!: AdminBindings['createStripeSubscription'];\n createDirectSubscription!: AdminBindings['createDirectSubscription'];\n updateStripeSubscription!: AdminBindings['updateStripeSubscription'];\n cancelStripeSubscription!: AdminBindings['cancelStripeSubscription'];\n provisionWorkspaceForSubscription!: AdminBindings['provisionWorkspaceForSubscription'];\n associateWorkspaceWithSubscription!: AdminBindings['associateWorkspaceWithSubscription'];\n createSubscriptionPaymentLink!: AdminBindings['createSubscriptionPaymentLink'];\n createSetupIntent!: AdminBindings['createSetupIntent'];\n getStripePaymentMethods!: AdminBindings['getStripePaymentMethods'];\n attachStripePaymentMethod!: AdminBindings['attachStripePaymentMethod'];\n detachStripePaymentMethod!: AdminBindings['detachStripePaymentMethod'];\n setDefaultStripePaymentMethod!: AdminBindings['setDefaultStripePaymentMethod'];\n createCustomerSetupIntent!: AdminBindings['createCustomerSetupIntent'];\n getCustomerPaymentMethods!: AdminBindings['getCustomerPaymentMethods'];\n attachCustomerPaymentMethod!: AdminBindings['attachCustomerPaymentMethod'];\n detachCustomerPaymentMethod!: AdminBindings['detachCustomerPaymentMethod'];\n setDefaultCustomerPaymentMethod!: AdminBindings['setDefaultCustomerPaymentMethod'];\n convertSubscriptionToStripe!: AdminBindings['convertSubscriptionToStripe'];\n previewWorkspaceOrganizationChange!: AdminBindings['previewWorkspaceOrganizationChange'];\n changeWorkspaceOrganization!: AdminBindings['changeWorkspaceOrganization'];\n createStripeInvoice!: AdminBindings['createStripeInvoice'];\n getStripeInvoices!: AdminBindings['getStripeInvoices'];\n getStripeUpcomingInvoice!: AdminBindings['getStripeUpcomingInvoice'];\n getWorkspaceUsageDashboard!: AdminBindings['getWorkspaceUsageDashboard'];\n compareProductsWithStripe!: AdminBindings['compareProductsWithStripe'];\n syncProductToStripe!: AdminBindings['syncProductToStripe'];\n searchStripeProducts!: AdminBindings['searchStripeProducts'];\n getUsageReport!: AdminBindings['getUsageReport'];\n getSubscriptionsAsAdmin!: AdminBindings['getSubscriptionsAsAdmin'];\n getSubscriptionAsAdmin!: AdminBindings['getSubscriptionAsAdmin'];\n updateSubscriptionStatusAsAdmin!: AdminBindings['updateSubscriptionStatusAsAdmin'];\n updateSubscriptionCreditSettingsAsAdmin!: AdminBindings['updateSubscriptionCreditSettingsAsAdmin'];\n grantCreditsAsAdmin!: AdminBindings['grantCreditsAsAdmin'];\n listCreditGrantsAsAdmin!: AdminBindings['listCreditGrantsAsAdmin'];\n getVoiceMetrics!: AdminBindings['getVoiceMetrics'];\n getHealthMetrics!: AdminBindings['getHealthMetrics'];\n getHealthDetail!: AdminBindings['getHealthDetail'];\n getWorkspaceInboxesAsAdmin!: AdminBindings['getWorkspaceInboxesAsAdmin'];\n listWorkspaceChats!: AdminBindings['listWorkspaceChats'];\n getWorkspaceChat!: AdminBindings['getWorkspaceChat'];\n rateWorkspaceChatMessage!: AdminBindings['rateWorkspaceChatMessage'];\n getTemporalAdminConfig!: AdminBindings['getTemporalAdminConfig'];\n listFailedTemporalWorkflows!: AdminBindings['listFailedTemporalWorkflows'];\n listStuckTemporalWorkflows!: AdminBindings['listStuckTemporalWorkflows'];\n getTemporalSummary!: AdminBindings['getTemporalSummary'];\n getTemporalWorkflowDetail!: AdminBindings['getTemporalWorkflowDetail'];\n getResellers!: AdminBindings['getResellers'];\n getReseller!: AdminBindings['getReseller'];\n createReseller!: AdminBindings['createReseller'];\n updateReseller!: AdminBindings['updateReseller'];\n getResellerAccounts!: AdminBindings['getResellerAccounts'];\n linkResellerToAccount!: AdminBindings['linkResellerToAccount'];\n unlinkResellerFromAccount!: AdminBindings['unlinkResellerFromAccount'];\n getBillingPeriods!: AdminBindings['getBillingPeriods'];\n generateInvoice!: AdminBindings['generateInvoice'];\n getInvoices!: AdminBindings['getInvoices'];\n getInvoiceDownloadUrl!: AdminBindings['getInvoiceDownloadUrl'];\n getReceiptDownloadUrl!: AdminBindings['getReceiptDownloadUrl'];\n recordInvoicePayment!: AdminBindings['recordInvoicePayment'];\n\n protected adminApi: AdminApi;\n\n constructor(apiKey: string | undefined, baseUrl: string, customFetch?: typeof fetch) {\n super(apiKey, baseUrl, customFetch);\n this.adminApi = new AdminApi(apiKey, baseUrl, customFetch);\n bindAdminMethods(this, this.adminApi);\n }\n\n /**\n * Propagates acting member switches to the admin API module as well.\n */\n override setActingMember(memberUuid: string | undefined) {\n super.setActingMember(memberUuid);\n if (typeof this.adminApi.setActingMember === 'function') {\n this.adminApi.setActingMember(memberUuid);\n }\n }\n\n // setOrgToken is intentionally NOT overridden here. Admin routes\n // (/api/v2/admin/*) are protected by the bearer token's superuser claim and\n // ignore X-Org-Token entirely, so propagating an org token to adminApi is\n // dead code that would only obscure auth flow if admin route logic changes.\n}\n","import { AdminApi } from '../../api';\n\nexport interface AdminBindings {\n // Support Requests\n listSupportRequestsAsAdmin: AdminApi['listSupportRequestsAsAdmin'];\n getSupportRequestAsAdmin: AdminApi['getSupportRequestAsAdmin'];\n commentOnSupportRequestAsAdmin: AdminApi['commentOnSupportRequestAsAdmin'];\n noteOnSupportRequestAsAdmin: AdminApi['noteOnSupportRequestAsAdmin'];\n updateSupportRequestStatusAsAdmin: AdminApi['updateSupportRequestStatusAsAdmin'];\n updateSupportRequestAttributesAsAdmin: AdminApi['updateSupportRequestAttributesAsAdmin'];\n createSupportRequestLinearIssueAsAdmin: AdminApi['createSupportRequestLinearIssueAsAdmin'];\n\n // Accounts\n getAccounts: AdminApi['getAccounts'];\n getAccountDetails: AdminApi['getAccountDetails'];\n getAccountByUuid: AdminApi['getAccountByUuid'];\n getAccountMemberships: AdminApi['getAccountMemberships'];\n getAccountOrgMemberships: AdminApi['getAccountOrgMemberships'];\n createAccountOrgMembership: AdminApi['createAccountOrgMembership'];\n deleteAccountOrgMembership: AdminApi['deleteAccountOrgMembership'];\n getAccountMembership: AdminApi['getAccountMembership'];\n updateAccountMembership: AdminApi['updateAccountMembership'];\n createAccountMembership: AdminApi['createAccountMembership'];\n deleteAccountMembership: AdminApi['deleteAccountMembership'];\n updateAccountAsAdmin: AdminApi['updateAccountAsAdmin'];\n createAccountAsAdmin: AdminApi['createAccountAsAdmin'];\n deleteAccountAsAdmin: AdminApi['deleteAccountAsAdmin'];\n lookupAccount: AdminApi['lookupAccount'];\n exportAccountData: AdminApi['exportAccountData'];\n requestAccountDeletion: AdminApi['requestAccountDeletion'];\n cancelAccountDeletion: AdminApi['cancelAccountDeletion'];\n\n // Organizations\n getOrganizations: AdminApi['getOrganizations'];\n getOrganization: AdminApi['getOrganization'];\n getOrganizationAsAdmin: AdminApi['getOrganizationAsAdmin'];\n getOrganizationMembersAsAdmin: AdminApi['getOrganizationMembersAsAdmin'];\n createOrganization: AdminApi['createOrganization'];\n updateOrganization: AdminApi['updateOrganization'];\n deleteOrganization: AdminApi['deleteOrganization'];\n joinOrganization: AdminApi['joinOrganization'];\n leaveOrganization: AdminApi['leaveOrganization'];\n generateLogoUploadUrl: AdminApi['generateLogoUploadUrl'];\n\n // Products\n importProducts: AdminApi['importProducts'];\n createProductAsAdmin: AdminApi['createProductAsAdmin'];\n getProductsAsAdmin: AdminApi['getProductsAsAdmin'];\n getProductAsAdmin: AdminApi['getProductAsAdmin'];\n updateProductAsAdmin: AdminApi['updateProductAsAdmin'];\n deleteProductAsAdmin: AdminApi['deleteProductAsAdmin'];\n\n // Workspaces\n getWorkspacesAsAdmin: AdminApi['getWorkspacesAsAdmin'];\n getWorkspaceAsAdmin: AdminApi['getWorkspaceAsAdmin'];\n getWorkspaceByNumericIdAsAdmin: AdminApi['getWorkspaceByNumericIdAsAdmin'];\n createWorkspaceAsAdmin: AdminApi['createWorkspaceAsAdmin'];\n updateWorkspaceAsAdmin: AdminApi['updateWorkspaceAsAdmin'];\n deleteWorkspaceAsAdmin: AdminApi['deleteWorkspaceAsAdmin'];\n createSchemaAsAdmin: AdminApi['createSchemaAsAdmin'];\n migrateSchemaAsAdmin: AdminApi['migrateSchemaAsAdmin'];\n provisionWorkspaceAsAdmin: AdminApi['provisionWorkspaceAsAdmin'];\n refreshProvisionStatusAsAdmin: AdminApi['refreshProvisionStatusAsAdmin'];\n enableMaintenanceMode: AdminApi['enableMaintenanceMode'];\n disableMaintenanceMode: AdminApi['disableMaintenanceMode'];\n getWorkspaceHealth: AdminApi['getWorkspaceHealth'];\n provisionPlanFeatures: AdminApi['provisionPlanFeatures'];\n changeWorkspaceProduct: AdminApi['changeWorkspaceProduct'];\n validateWorkflowAccessAsAdmin: AdminApi['validateWorkflowAccessAsAdmin'];\n\n // Members\n mergeMembers: AdminApi['mergeMembers'];\n getAdminWorkspaceMember: AdminApi['getAdminWorkspaceMember'];\n createAdminWorkspaceMember: AdminApi['createAdminWorkspaceMember'];\n updateAdminWorkspaceMember: AdminApi['updateAdminWorkspaceMember'];\n unarchiveAdminWorkspaceMember: AdminApi['unarchiveAdminWorkspaceMember'];\n getAdminWorkspaceMemberRoles: AdminApi['getAdminWorkspaceMemberRoles'];\n getMissingMemberships: AdminApi['getMissingMemberships'];\n linkMissingMembership: AdminApi['linkMissingMembership'];\n\n // Phone Numbers\n getUnmappedPhoneNumbers: AdminApi['getUnmappedPhoneNumbers'];\n getWorkspaceUnmappedPhoneNumbers: AdminApi['getWorkspaceUnmappedPhoneNumbers'];\n getWorkspacePhoneNumbersAsAdmin: AdminApi['getWorkspacePhoneNumbersAsAdmin'];\n getProviderPhoneNumbers: AdminApi['getProviderPhoneNumbers'];\n getProviderPhoneNumber: AdminApi['getProviderPhoneNumber'];\n updateProviderPhoneNumber: AdminApi['updateProviderPhoneNumber'];\n mapMainAccountPhone: AdminApi['mapMainAccountPhone'];\n unmapPhoneNumber: AdminApi['unmapPhoneNumber'];\n searchAvailablePhoneNumbersAsAdmin: AdminApi['searchAvailablePhoneNumbersAsAdmin'];\n purchasePhoneNumberAsAdmin: AdminApi['purchasePhoneNumberAsAdmin'];\n startBulkPhoneClassification: AdminApi['startBulkPhoneClassification'];\n getOrgA2PStatusAsAdmin: AdminApi['getOrgA2PStatusAsAdmin'];\n resetOrgA2PStatusAsAdmin: AdminApi['resetOrgA2PStatusAsAdmin'];\n\n // Site Mappings\n getSiteMappings: AdminApi['getSiteMappings'];\n getSiteMapping: AdminApi['getSiteMapping'];\n updateSiteMapping: AdminApi['updateSiteMapping'];\n updateSiteMappingWorkspace: AdminApi['updateSiteMappingWorkspace'];\n adminDeleteSiteMapping: AdminApi['adminDeleteSiteMapping'];\n createSiteMapping: AdminApi['createSiteMapping'];\n createOrUpdateSiteMapping: AdminApi['createOrUpdateSiteMapping'];\n deleteSiteMapping: AdminApi['deleteSiteMapping'];\n\n // Admin Workspace Inboxes\n getWorkspaceInboxesAsAdmin: AdminApi['getWorkspaceInboxesAsAdmin'];\n\n // Inbox Mappings\n getInboxMappings: AdminApi['getInboxMappings'];\n getInboxMapping: AdminApi['getInboxMapping'];\n updateInboxMapping: AdminApi['updateInboxMapping'];\n deleteAdminInboxMapping: AdminApi['deleteAdminInboxMapping'];\n\n // Utilities\n generateChatSummaries: AdminApi['generateChatSummaries'];\n executeQuery: AdminApi['executeQuery'];\n getTraceUrl: AdminApi['getTraceUrl'];\n listAllThemes: AdminApi['listAllThemes'];\n startBulkTOSAcceptance: AdminApi['startBulkTOSAcceptance'];\n startTokenUsageBackfill: AdminApi['startTokenUsageBackfill'];\n updateChatMessage: AdminApi['updateChatMessage'];\n\n // Customer Management\n createCustomerFromAccount: AdminApi['createCustomerFromAccount'];\n getCustomers: AdminApi['getCustomers'];\n getCustomer: AdminApi['getCustomer'];\n createCustomer: AdminApi['createCustomer'];\n updateCustomer: AdminApi['updateCustomer'];\n getCustomerAccounts: AdminApi['getCustomerAccounts'];\n linkCustomerToAccount: AdminApi['linkCustomerToAccount'];\n unlinkCustomerFromAccount: AdminApi['unlinkCustomerFromAccount'];\n syncCustomerToStripe: AdminApi['syncCustomerToStripe'];\n\n // Stripe Customer Management\n getStripeCustomer: AdminApi['getStripeCustomer'];\n createStripeCustomer: AdminApi['createStripeCustomer'];\n updateStripeCustomer: AdminApi['updateStripeCustomer'];\n\n // Stripe Subscription Management\n getStripeSubscriptions: AdminApi['getStripeSubscriptions'];\n createStripeSubscription: AdminApi['createStripeSubscription'];\n createDirectSubscription: AdminApi['createDirectSubscription'];\n updateStripeSubscription: AdminApi['updateStripeSubscription'];\n cancelStripeSubscription: AdminApi['cancelStripeSubscription'];\n provisionWorkspaceForSubscription: AdminApi['provisionWorkspaceForSubscription'];\n associateWorkspaceWithSubscription: AdminApi['associateWorkspaceWithSubscription'];\n createSubscriptionPaymentLink: AdminApi['createSubscriptionPaymentLink'];\n\n // Stripe Payment Methods (account-level — deprecated, use customer-level)\n createSetupIntent: AdminApi['createSetupIntent'];\n getStripePaymentMethods: AdminApi['getStripePaymentMethods'];\n attachStripePaymentMethod: AdminApi['attachStripePaymentMethod'];\n detachStripePaymentMethod: AdminApi['detachStripePaymentMethod'];\n setDefaultStripePaymentMethod: AdminApi['setDefaultStripePaymentMethod'];\n\n // Convert direct subscription to Stripe\n convertSubscriptionToStripe: AdminApi['convertSubscriptionToStripe'];\n\n // Stripe Payment Methods (customer-level)\n createCustomerSetupIntent: AdminApi['createCustomerSetupIntent'];\n getCustomerPaymentMethods: AdminApi['getCustomerPaymentMethods'];\n attachCustomerPaymentMethod: AdminApi['attachCustomerPaymentMethod'];\n detachCustomerPaymentMethod: AdminApi['detachCustomerPaymentMethod'];\n setDefaultCustomerPaymentMethod: AdminApi['setDefaultCustomerPaymentMethod'];\n\n previewWorkspaceOrganizationChange: AdminApi['previewWorkspaceOrganizationChange'];\n changeWorkspaceOrganization: AdminApi['changeWorkspaceOrganization'];\n\n // Stripe Invoices\n createStripeInvoice: AdminApi['createStripeInvoice'];\n getStripeInvoices: AdminApi['getStripeInvoices'];\n getStripeUpcomingInvoice: AdminApi['getStripeUpcomingInvoice'];\n\n // Invoices\n getBillingPeriods: AdminApi['getBillingPeriods'];\n generateInvoice: AdminApi['generateInvoice'];\n getInvoices: AdminApi['getInvoices'];\n getInvoiceDownloadUrl: AdminApi['getInvoiceDownloadUrl'];\n getReceiptDownloadUrl: AdminApi['getReceiptDownloadUrl'];\n recordInvoicePayment: AdminApi['recordInvoicePayment'];\n\n // Billing Dashboard\n getWorkspaceUsageDashboard: AdminApi['getWorkspaceUsageDashboard'];\n\n // Product Stripe Sync\n compareProductsWithStripe: AdminApi['compareProductsWithStripe'];\n syncProductToStripe: AdminApi['syncProductToStripe'];\n searchStripeProducts: AdminApi['searchStripeProducts'];\n\n // Usage API\n getUsageReport: AdminApi['getUsageReport'];\n\n // Subscriptions Admin API\n getSubscriptionsAsAdmin: AdminApi['getSubscriptionsAsAdmin'];\n getSubscriptionAsAdmin: AdminApi['getSubscriptionAsAdmin'];\n updateSubscriptionStatusAsAdmin: AdminApi['updateSubscriptionStatusAsAdmin'];\n updateSubscriptionCreditSettingsAsAdmin: AdminApi['updateSubscriptionCreditSettingsAsAdmin'];\n grantCreditsAsAdmin: AdminApi['grantCreditsAsAdmin'];\n listCreditGrantsAsAdmin: AdminApi['listCreditGrantsAsAdmin'];\n\n // Voice Metrics API\n getVoiceMetrics: AdminApi['getVoiceMetrics'];\n\n // Health Dashboard API\n getHealthMetrics: AdminApi['getHealthMetrics'];\n getHealthDetail: AdminApi['getHealthDetail'];\n\n // Admin Chat Endpoints\n listWorkspaceChats: AdminApi['listWorkspaceChats'];\n getWorkspaceChat: AdminApi['getWorkspaceChat'];\n rateWorkspaceChatMessage: AdminApi['rateWorkspaceChatMessage'];\n\n // Admin Temporal Inspection\n getTemporalAdminConfig: AdminApi['getTemporalAdminConfig'];\n listFailedTemporalWorkflows: AdminApi['listFailedTemporalWorkflows'];\n listStuckTemporalWorkflows: AdminApi['listStuckTemporalWorkflows'];\n getTemporalSummary: AdminApi['getTemporalSummary'];\n getTemporalWorkflowDetail: AdminApi['getTemporalWorkflowDetail'];\n\n // Reseller Management\n getResellers: AdminApi['getResellers'];\n getReseller: AdminApi['getReseller'];\n createReseller: AdminApi['createReseller'];\n updateReseller: AdminApi['updateReseller'];\n getResellerAccounts: AdminApi['getResellerAccounts'];\n linkResellerToAccount: AdminApi['linkResellerToAccount'];\n unlinkResellerFromAccount: AdminApi['unlinkResellerFromAccount'];\n}\n\nexport function bindAdminMethods(target: AdminBindings, admin: AdminApi): void {\n // Support Requests\n target.listSupportRequestsAsAdmin = admin.listSupportRequestsAsAdmin.bind(admin);\n target.getSupportRequestAsAdmin = admin.getSupportRequestAsAdmin.bind(admin);\n target.commentOnSupportRequestAsAdmin = admin.commentOnSupportRequestAsAdmin.bind(admin);\n target.noteOnSupportRequestAsAdmin = admin.noteOnSupportRequestAsAdmin.bind(admin);\n target.updateSupportRequestStatusAsAdmin = admin.updateSupportRequestStatusAsAdmin.bind(admin);\n target.updateSupportRequestAttributesAsAdmin =\n admin.updateSupportRequestAttributesAsAdmin.bind(admin);\n target.createSupportRequestLinearIssueAsAdmin =\n admin.createSupportRequestLinearIssueAsAdmin.bind(admin);\n\n // Accounts\n target.getAccounts = admin.getAccounts.bind(admin);\n target.getAccountDetails = admin.getAccountDetails.bind(admin);\n target.getAccountByUuid = admin.getAccountByUuid.bind(admin);\n target.getAccountMemberships = admin.getAccountMemberships.bind(admin);\n target.getAccountOrgMemberships = admin.getAccountOrgMemberships.bind(admin);\n target.createAccountOrgMembership = admin.createAccountOrgMembership.bind(admin);\n target.deleteAccountOrgMembership = admin.deleteAccountOrgMembership.bind(admin);\n target.getAccountMembership = admin.getAccountMembership.bind(admin);\n target.updateAccountMembership = admin.updateAccountMembership.bind(admin);\n target.createAccountMembership = admin.createAccountMembership.bind(admin);\n target.deleteAccountMembership = admin.deleteAccountMembership.bind(admin);\n target.updateAccountAsAdmin = admin.updateAccountAsAdmin.bind(admin);\n target.createAccountAsAdmin = admin.createAccountAsAdmin.bind(admin);\n target.deleteAccountAsAdmin = admin.deleteAccountAsAdmin.bind(admin);\n target.lookupAccount = admin.lookupAccount.bind(admin);\n target.exportAccountData = admin.exportAccountData.bind(admin);\n target.requestAccountDeletion = admin.requestAccountDeletion.bind(admin);\n target.cancelAccountDeletion = admin.cancelAccountDeletion.bind(admin);\n\n // Organizations\n target.getOrganizations = admin.getOrganizations.bind(admin);\n target.getOrganization = admin.getOrganization.bind(admin);\n target.getOrganizationAsAdmin = admin.getOrganizationAsAdmin.bind(admin);\n target.getOrganizationMembersAsAdmin = admin.getOrganizationMembersAsAdmin.bind(admin);\n target.createOrganization = admin.createOrganization.bind(admin);\n target.updateOrganization = admin.updateOrganization.bind(admin);\n target.deleteOrganization = admin.deleteOrganization.bind(admin);\n target.joinOrganization = admin.joinOrganization.bind(admin);\n target.leaveOrganization = admin.leaveOrganization.bind(admin);\n target.generateLogoUploadUrl = admin.generateLogoUploadUrl.bind(admin);\n\n // Products\n target.importProducts = admin.importProducts.bind(admin);\n target.createProductAsAdmin = admin.createProductAsAdmin.bind(admin);\n target.getProductsAsAdmin = admin.getProductsAsAdmin.bind(admin);\n target.getProductAsAdmin = admin.getProductAsAdmin.bind(admin);\n target.updateProductAsAdmin = admin.updateProductAsAdmin.bind(admin);\n target.deleteProductAsAdmin = admin.deleteProductAsAdmin.bind(admin);\n\n // Workspaces\n target.getWorkspacesAsAdmin = admin.getWorkspacesAsAdmin.bind(admin);\n target.getWorkspaceAsAdmin = admin.getWorkspaceAsAdmin.bind(admin);\n target.getWorkspaceByNumericIdAsAdmin = admin.getWorkspaceByNumericIdAsAdmin.bind(admin);\n target.createWorkspaceAsAdmin = admin.createWorkspaceAsAdmin.bind(admin);\n target.updateWorkspaceAsAdmin = admin.updateWorkspaceAsAdmin.bind(admin);\n target.deleteWorkspaceAsAdmin = admin.deleteWorkspaceAsAdmin.bind(admin);\n target.createSchemaAsAdmin = admin.createSchemaAsAdmin.bind(admin);\n target.migrateSchemaAsAdmin = admin.migrateSchemaAsAdmin.bind(admin);\n target.provisionWorkspaceAsAdmin = admin.provisionWorkspaceAsAdmin.bind(admin);\n target.refreshProvisionStatusAsAdmin = admin.refreshProvisionStatusAsAdmin.bind(admin);\n target.enableMaintenanceMode = admin.enableMaintenanceMode.bind(admin);\n target.disableMaintenanceMode = admin.disableMaintenanceMode.bind(admin);\n target.getWorkspaceHealth = admin.getWorkspaceHealth.bind(admin);\n target.provisionPlanFeatures = admin.provisionPlanFeatures.bind(admin);\n target.changeWorkspaceProduct = admin.changeWorkspaceProduct.bind(admin);\n target.validateWorkflowAccessAsAdmin = admin.validateWorkflowAccessAsAdmin.bind(admin);\n\n // Members\n target.mergeMembers = admin.mergeMembers.bind(admin);\n target.getAdminWorkspaceMember = admin.getAdminWorkspaceMember.bind(admin);\n target.createAdminWorkspaceMember = admin.createAdminWorkspaceMember.bind(admin);\n target.updateAdminWorkspaceMember = admin.updateAdminWorkspaceMember.bind(admin);\n target.unarchiveAdminWorkspaceMember = admin.unarchiveAdminWorkspaceMember.bind(admin);\n target.getAdminWorkspaceMemberRoles = admin.getAdminWorkspaceMemberRoles.bind(admin);\n target.getMissingMemberships = admin.getMissingMemberships.bind(admin);\n target.linkMissingMembership = admin.linkMissingMembership.bind(admin);\n\n // Phone Numbers\n target.getUnmappedPhoneNumbers = admin.getUnmappedPhoneNumbers.bind(admin);\n target.getWorkspaceUnmappedPhoneNumbers = admin.getWorkspaceUnmappedPhoneNumbers.bind(admin);\n target.getWorkspacePhoneNumbersAsAdmin = admin.getWorkspacePhoneNumbersAsAdmin.bind(admin);\n target.getProviderPhoneNumbers = admin.getProviderPhoneNumbers.bind(admin);\n target.getProviderPhoneNumber = admin.getProviderPhoneNumber.bind(admin);\n target.updateProviderPhoneNumber = admin.updateProviderPhoneNumber.bind(admin);\n target.mapMainAccountPhone = admin.mapMainAccountPhone.bind(admin);\n target.unmapPhoneNumber = admin.unmapPhoneNumber.bind(admin);\n target.searchAvailablePhoneNumbersAsAdmin = admin.searchAvailablePhoneNumbersAsAdmin.bind(admin);\n target.purchasePhoneNumberAsAdmin = admin.purchasePhoneNumberAsAdmin.bind(admin);\n target.startBulkPhoneClassification = admin.startBulkPhoneClassification.bind(admin);\n target.getOrgA2PStatusAsAdmin = admin.getOrgA2PStatusAsAdmin.bind(admin);\n target.resetOrgA2PStatusAsAdmin = admin.resetOrgA2PStatusAsAdmin.bind(admin);\n\n // Site Mappings\n target.getSiteMappings = admin.getSiteMappings.bind(admin);\n target.getSiteMapping = admin.getSiteMapping.bind(admin);\n target.updateSiteMapping = admin.updateSiteMapping.bind(admin);\n target.updateSiteMappingWorkspace = admin.updateSiteMappingWorkspace.bind(admin);\n target.adminDeleteSiteMapping = admin.adminDeleteSiteMapping.bind(admin);\n target.createSiteMapping = admin.createSiteMapping.bind(admin);\n target.createOrUpdateSiteMapping = admin.createOrUpdateSiteMapping.bind(admin);\n target.deleteSiteMapping = admin.deleteSiteMapping.bind(admin);\n\n // Inbox Mappings\n target.getInboxMappings = admin.getInboxMappings.bind(admin);\n target.getInboxMapping = admin.getInboxMapping.bind(admin);\n target.updateInboxMapping = admin.updateInboxMapping.bind(admin);\n target.deleteAdminInboxMapping = admin.deleteAdminInboxMapping.bind(admin);\n\n // Utilities\n target.generateChatSummaries = admin.generateChatSummaries.bind(admin);\n target.executeQuery = admin.executeQuery.bind(admin);\n target.getTraceUrl = admin.getTraceUrl.bind(admin);\n target.listAllThemes = admin.listAllThemes.bind(admin);\n target.startBulkTOSAcceptance = admin.startBulkTOSAcceptance.bind(admin);\n target.startTokenUsageBackfill = admin.startTokenUsageBackfill.bind(admin);\n target.updateChatMessage = admin.updateChatMessage.bind(admin);\n\n // Customer Management\n target.createCustomerFromAccount = admin.createCustomerFromAccount.bind(admin);\n target.getCustomers = admin.getCustomers.bind(admin);\n target.getCustomer = admin.getCustomer.bind(admin);\n target.createCustomer = admin.createCustomer.bind(admin);\n target.updateCustomer = admin.updateCustomer.bind(admin);\n target.getCustomerAccounts = admin.getCustomerAccounts.bind(admin);\n target.linkCustomerToAccount = admin.linkCustomerToAccount.bind(admin);\n target.unlinkCustomerFromAccount = admin.unlinkCustomerFromAccount.bind(admin);\n target.syncCustomerToStripe = admin.syncCustomerToStripe.bind(admin);\n\n // Stripe Customer Management\n target.getStripeCustomer = admin.getStripeCustomer.bind(admin);\n target.createStripeCustomer = admin.createStripeCustomer.bind(admin);\n target.updateStripeCustomer = admin.updateStripeCustomer.bind(admin);\n\n // Stripe Subscription Management\n target.getStripeSubscriptions = admin.getStripeSubscriptions.bind(admin);\n target.createStripeSubscription = admin.createStripeSubscription.bind(admin);\n target.createDirectSubscription = admin.createDirectSubscription.bind(admin);\n target.updateStripeSubscription = admin.updateStripeSubscription.bind(admin);\n target.cancelStripeSubscription = admin.cancelStripeSubscription.bind(admin);\n target.provisionWorkspaceForSubscription = admin.provisionWorkspaceForSubscription.bind(admin);\n target.associateWorkspaceWithSubscription = admin.associateWorkspaceWithSubscription.bind(admin);\n target.createSubscriptionPaymentLink = admin.createSubscriptionPaymentLink.bind(admin);\n\n // Stripe Payment Methods (account-level — deprecated)\n target.createSetupIntent = admin.createSetupIntent.bind(admin);\n target.getStripePaymentMethods = admin.getStripePaymentMethods.bind(admin);\n target.attachStripePaymentMethod = admin.attachStripePaymentMethod.bind(admin);\n target.detachStripePaymentMethod = admin.detachStripePaymentMethod.bind(admin);\n target.setDefaultStripePaymentMethod = admin.setDefaultStripePaymentMethod.bind(admin);\n\n // Convert direct subscription to Stripe\n target.convertSubscriptionToStripe = admin.convertSubscriptionToStripe.bind(admin);\n\n // Stripe Payment Methods (customer-level)\n target.createCustomerSetupIntent = admin.createCustomerSetupIntent.bind(admin);\n target.getCustomerPaymentMethods = admin.getCustomerPaymentMethods.bind(admin);\n target.attachCustomerPaymentMethod = admin.attachCustomerPaymentMethod.bind(admin);\n target.detachCustomerPaymentMethod = admin.detachCustomerPaymentMethod.bind(admin);\n target.setDefaultCustomerPaymentMethod = admin.setDefaultCustomerPaymentMethod.bind(admin);\n\n target.previewWorkspaceOrganizationChange = admin.previewWorkspaceOrganizationChange.bind(admin);\n target.changeWorkspaceOrganization = admin.changeWorkspaceOrganization.bind(admin);\n\n // Stripe Invoices\n target.createStripeInvoice = admin.createStripeInvoice.bind(admin);\n target.getStripeInvoices = admin.getStripeInvoices.bind(admin);\n target.getStripeUpcomingInvoice = admin.getStripeUpcomingInvoice.bind(admin);\n\n // Invoices\n target.getBillingPeriods = admin.getBillingPeriods.bind(admin);\n target.generateInvoice = admin.generateInvoice.bind(admin);\n target.getInvoices = admin.getInvoices.bind(admin);\n target.getInvoiceDownloadUrl = admin.getInvoiceDownloadUrl.bind(admin);\n target.getReceiptDownloadUrl = admin.getReceiptDownloadUrl.bind(admin);\n target.recordInvoicePayment = admin.recordInvoicePayment.bind(admin);\n\n // Billing Dashboard\n target.getWorkspaceUsageDashboard = admin.getWorkspaceUsageDashboard.bind(admin);\n\n // Product Stripe Sync\n target.compareProductsWithStripe = admin.compareProductsWithStripe.bind(admin);\n target.syncProductToStripe = admin.syncProductToStripe.bind(admin);\n target.searchStripeProducts = admin.searchStripeProducts.bind(admin);\n\n // Usage API\n target.getUsageReport = admin.getUsageReport.bind(admin);\n\n // Subscriptions Admin API\n target.getSubscriptionsAsAdmin = admin.getSubscriptionsAsAdmin.bind(admin);\n target.getSubscriptionAsAdmin = admin.getSubscriptionAsAdmin.bind(admin);\n target.updateSubscriptionStatusAsAdmin = admin.updateSubscriptionStatusAsAdmin.bind(admin);\n target.updateSubscriptionCreditSettingsAsAdmin =\n admin.updateSubscriptionCreditSettingsAsAdmin.bind(admin);\n target.grantCreditsAsAdmin = admin.grantCreditsAsAdmin.bind(admin);\n target.listCreditGrantsAsAdmin = admin.listCreditGrantsAsAdmin.bind(admin);\n\n // Voice Metrics API\n target.getVoiceMetrics = admin.getVoiceMetrics.bind(admin);\n\n // Health Dashboard API\n target.getHealthMetrics = admin.getHealthMetrics.bind(admin);\n target.getHealthDetail = admin.getHealthDetail.bind(admin);\n\n // Admin Workspace Inboxes\n target.getWorkspaceInboxesAsAdmin = admin.getWorkspaceInboxesAsAdmin.bind(admin);\n\n // Admin Chat Endpoints\n target.listWorkspaceChats = admin.listWorkspaceChats.bind(admin);\n target.getWorkspaceChat = admin.getWorkspaceChat.bind(admin);\n target.rateWorkspaceChatMessage = admin.rateWorkspaceChatMessage.bind(admin);\n\n // Admin Temporal Inspection\n target.getTemporalAdminConfig = admin.getTemporalAdminConfig.bind(admin);\n target.listFailedTemporalWorkflows = admin.listFailedTemporalWorkflows.bind(admin);\n target.listStuckTemporalWorkflows = admin.listStuckTemporalWorkflows.bind(admin);\n target.getTemporalSummary = admin.getTemporalSummary.bind(admin);\n target.getTemporalWorkflowDetail = admin.getTemporalWorkflowDetail.bind(admin);\n\n // Reseller Management\n target.getResellers = admin.getResellers.bind(admin);\n target.getReseller = admin.getReseller.bind(admin);\n target.createReseller = admin.createReseller.bind(admin);\n target.updateReseller = admin.updateReseller.bind(admin);\n target.getResellerAccounts = admin.getResellerAccounts.bind(admin);\n target.linkResellerToAccount = admin.linkResellerToAccount.bind(admin);\n target.unlinkResellerFromAccount = admin.unlinkResellerFromAccount.bind(admin);\n}\n","import { ApiClient as GravityRailClient } from '@gravity-rail/client';\nimport {\n CredentialsManager,\n getEnvironmentConfig,\n refreshAccessToken,\n type CLICredentials,\n type EnvironmentConfig,\n} from '../cli-utils';\nimport { homedir } from 'os';\nimport { detectOutputFormat, type OutputFormat } from './output';\nimport { loadDevCloudRealmFile, loadRealmCredentials } from './realm';\nimport { AuthRequiredError } from './errors';\nimport { registerOrgAuthHandler } from './org-auth';\n\n/** Build an authenticated API client with the CLI org-auth handler registered. */\nfunction makeApiClient(accessToken: string, apiUrl: string): GravityRailClient {\n const apiClient = new GravityRailClient(accessToken, apiUrl);\n registerOrgAuthHandler(apiClient, apiUrl, accessToken);\n return apiClient;\n}\n\n/** Try to silently refresh an expired access token. Returns an AuthenticatedContext or null. */\nasync function tryTokenRefresh(\n ctx: CommandContext,\n creds: CLICredentials\n): Promise<AuthenticatedContext | null> {\n if (!creds.refreshToken) return null;\n const refreshed = await refreshAccessToken(\n ctx.envConfig,\n creds,\n ctx.credentialsManager,\n ctx.env\n );\n if (!refreshed?.accessToken) return null;\n const apiClient = makeApiClient(refreshed.accessToken, ctx.envConfig.apiUrl);\n return { ...ctx, accessToken: refreshed.accessToken, apiClient };\n}\n\nexport interface GlobalOptions {\n env: string;\n realm?: string;\n outputFormat?: string;\n verbose?: boolean;\n allowWrite?: boolean;\n}\n\nexport interface PublicGlobalOptions {\n env?: string;\n apiUrl?: string;\n frontendUrl?: string;\n outputFormat?: string;\n verbose?: boolean;\n allowWrite?: boolean;\n}\n\nexport interface CommandContext {\n env: string;\n envConfig: EnvironmentConfig;\n outputFormat: OutputFormat;\n verbose: boolean;\n allowWrite: boolean;\n credentialsManager: CredentialsManager;\n}\n\nexport interface AuthenticatedContext extends CommandContext {\n accessToken: string;\n apiClient: GravityRailClient;\n realmWorkspace?: string;\n}\n\n/** Create a base command context (no auth required) */\nexport function createContext(opts: GlobalOptions): CommandContext {\n const envConfig = getEnvironmentConfig(opts.env);\n const credentialsManager = new CredentialsManager(homedir(), envConfig.apiUrl);\n return {\n env: opts.env,\n envConfig,\n outputFormat: detectOutputFormat(opts.outputFormat),\n verbose: opts.verbose ?? false,\n allowWrite: opts.allowWrite ?? false,\n credentialsManager,\n };\n}\n\n/** Create an authenticated command context. Tries realm, env var, then cached token. Never auto-triggers OAuth. */\nexport async function createAuthenticatedContext(\n opts: GlobalOptions\n): Promise<AuthenticatedContext> {\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- CLI handler context, not React\n const ctx = createContext(opts);\n\n // Try --realm first (dev-only shortcut using dev-realms.json)\n if (opts.realm) {\n let devRealmsPath: string | undefined;\n if (opts.env.startsWith('dev-cloud:')) {\n const namespace = opts.env.slice('dev-cloud:'.length);\n devRealmsPath = loadDevCloudRealmFile(namespace);\n }\n const { token, workspaceUuid } = loadRealmCredentials(opts.realm, devRealmsPath);\n const apiClient = makeApiClient(token, ctx.envConfig.apiUrl);\n return { ...ctx, accessToken: token, apiClient, realmWorkspace: workspaceUuid };\n }\n\n // Try GRAVITY_RAIL_API_KEY first\n const apiKey = process.env.GRAVITY_RAIL_API_KEY;\n if (apiKey) {\n const apiClient = makeApiClient(apiKey, ctx.envConfig.apiUrl);\n return { ...ctx, accessToken: apiKey, apiClient };\n }\n\n // Try cached credentials (from `gr login`)\n const creds = ctx.credentialsManager.load(ctx.env);\n if (creds?.accessToken) {\n const buffer = 5 * 60 * 1000;\n const notExpired =\n !creds.expiresAt || new Date(creds.expiresAt) > new Date(Date.now() + buffer);\n if (notExpired) {\n const apiClient = makeApiClient(creds.accessToken, ctx.envConfig.apiUrl);\n return { ...ctx, accessToken: creds.accessToken, apiClient };\n }\n\n // Token expired — try refresh\n const refreshed = await tryTokenRefresh(ctx, creds);\n if (refreshed) return refreshed;\n }\n\n throw new AuthRequiredError();\n}\n\n/**\n * Narrow a handler context to `AuthenticatedContext`.\n *\n * Handler `ctx` is typed as `AuthenticatedContext | CommandContext` so that\n * `requiresAuth: false` handlers can also share the type. At runtime, every\n * handler that did not opt out of auth will receive an `AuthenticatedContext`,\n * but TypeScript cannot verify this — call this helper before accessing\n * `apiClient` / `accessToken`.\n *\n * Throws if called from a handler that did not declare `requiresAuth`.\n */\nexport function requireAuth(ctx: AuthenticatedContext | CommandContext): AuthenticatedContext {\n if (!('apiClient' in ctx)) {\n throw new Error('Command handler accessed apiClient without declaring requiresAuth');\n }\n return ctx;\n}\n\n/** Create a base command context for the public CLI (defaults to prod) */\nexport function createPublicContext(opts: PublicGlobalOptions): CommandContext {\n const env = opts.env ?? 'prod';\n const envConfig = opts.apiUrl\n ? {\n apiUrl: opts.apiUrl,\n frontendUrl:\n opts.frontendUrl ||\n process.env.GRAVITY_RAIL_FRONTEND_URL ||\n 'https://app.gravityrail.com',\n }\n : getEnvironmentConfig(env);\n const credentialsManager = new CredentialsManager(homedir(), envConfig.apiUrl);\n return {\n env,\n envConfig,\n outputFormat: detectOutputFormat(opts.outputFormat),\n verbose: opts.verbose ?? false,\n allowWrite: opts.allowWrite ?? false,\n credentialsManager,\n };\n}\n\n/** Create an authenticated context for the public CLI. Tries env var, then cached token. */\nexport async function createPublicAuthenticatedContext(\n opts: PublicGlobalOptions\n): Promise<AuthenticatedContext> {\n const ctx = createPublicContext(opts);\n\n const apiKey = process.env.GRAVITY_RAIL_API_KEY;\n if (apiKey) {\n const apiClient = makeApiClient(apiKey, ctx.envConfig.apiUrl);\n return { ...ctx, accessToken: apiKey, apiClient };\n }\n\n const creds = ctx.credentialsManager.load(ctx.env);\n if (creds?.accessToken) {\n const buffer = 5 * 60 * 1000;\n const notExpired =\n !creds.expiresAt || new Date(creds.expiresAt) > new Date(Date.now() + buffer);\n if (notExpired) {\n const apiClient = makeApiClient(creds.accessToken, ctx.envConfig.apiUrl);\n return { ...ctx, accessToken: creds.accessToken, apiClient };\n }\n\n // Token expired — try refresh\n const refreshed = await tryTokenRefresh(ctx, creds);\n if (refreshed) return refreshed;\n }\n\n throw new AuthRequiredError();\n}\n","import { printTable } from '../cli-utils';\nimport {\n type PaginationMeta,\n isListResult,\n extractPaginationMeta,\n formatPaginationWarning,\n unwrapItems,\n} from './pagination';\n\nexport type OutputFormat = 'json' | 'jsonl' | 'table';\n\nexport interface OutputOptions {\n outputFormat: OutputFormat;\n}\n\nexport interface TableColumn<T> {\n header: string;\n getValue: (item: T) => string;\n maxWidth?: number;\n}\n\n/** Detect default output format based on whether stdout is a TTY */\nexport function detectOutputFormat(explicit?: string): OutputFormat {\n if (explicit) return explicit as OutputFormat;\n return process.stdout.isTTY ? 'table' : 'json';\n}\n\n/**\n * Write a list of items to stdout in the requested format.\n *\n * Accepts:\n * - A `ListResult` (explicit contract with items, meta, supportsAll) — preferred.\n * - Raw arrays, paginated responses ({ items: [...] }), or any object — legacy.\n *\n * When a `ListResult` is passed, its explicit `meta` and `supportsAll` are used.\n * When raw data is passed, pagination metadata is auto-detected with\n * `supportsAll: false` as the safe default.\n *\n * The optional `paginationMeta` and `supportsAll` parameters are kept for\n * backward compatibility but are ignored when a `ListResult` is passed.\n */\nexport function outputData(\n data: unknown,\n opts: OutputOptions,\n columns?: TableColumn<any>[],\n paginationMeta?: PaginationMeta,\n supportsAll?: boolean\n): void {\n let items: unknown[];\n let meta: PaginationMeta | undefined;\n let allSupported: boolean;\n\n if (isListResult(data)) {\n // Explicit contract: use ListResult fields directly\n items = data.items;\n meta = data.meta;\n allSupported = data.supportsAll ?? false;\n } else {\n // Legacy path: auto-detect from raw data\n items = unwrapItems(data);\n meta = paginationMeta ?? extractPaginationMeta(data);\n allSupported = supportsAll ?? false;\n }\n\n const warning = formatPaginationWarning(meta, allSupported);\n if (warning) {\n process.stderr.write(warning + '\\n');\n }\n\n switch (opts.outputFormat) {\n case 'json':\n process.stdout.write(JSON.stringify(items, null, 2) + '\\n');\n break;\n case 'jsonl':\n for (const item of items) {\n process.stdout.write(JSON.stringify(item) + '\\n');\n }\n break;\n case 'table':\n if (columns) {\n printTable(items, columns);\n } else {\n process.stdout.write(JSON.stringify(items, null, 2) + '\\n');\n }\n break;\n }\n}\n\n/** Write a single object to stdout in the requested format */\nexport function outputSingle<T>(data: T, opts: OutputOptions, columns?: TableColumn<T>[]): void {\n switch (opts.outputFormat) {\n case 'json':\n process.stdout.write(JSON.stringify(data, null, 2) + '\\n');\n break;\n case 'jsonl':\n process.stdout.write(JSON.stringify(data) + '\\n');\n break;\n case 'table':\n if (columns) {\n printTable([data], columns);\n } else {\n process.stdout.write(JSON.stringify(data, null, 2) + '\\n');\n }\n break;\n }\n}\n\n/** Common column factory helpers for domain files */\nexport const COL = {\n id: (): TableColumn<any> => ({ header: 'ID', getValue: (item) => String(item.id ?? '') }),\n uuid: (): TableColumn<any> => ({ header: 'UUID', getValue: (item) => item.uuid ?? '' }),\n name: (): TableColumn<any> => ({ header: 'NAME', getValue: (item) => item.name ?? '' }),\n status: (): TableColumn<any> => ({ header: 'STATUS', getValue: (item) => item.status ?? '' }),\n created: (): TableColumn<any> => ({\n header: 'CREATED',\n getValue: (item) => item.created_at ?? '',\n }),\n updated: (): TableColumn<any> => ({\n header: 'UPDATED',\n getValue: (item) => item.updated_at ?? '',\n }),\n description: (): TableColumn<any> => ({\n header: 'DESCRIPTION',\n getValue: (item) => item.description ?? '',\n }),\n enabled: (): TableColumn<any> => ({\n header: 'ENABLED',\n getValue: (item) => String(item.enabled ?? ''),\n }),\n};\n\n/** Write a status/progress message to stderr (never pollutes stdout) */\nexport function stderr(msg: string): void {\n process.stderr.write(msg + '\\n');\n}\n","import { execSync } from 'child_process';\nimport { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'fs';\nimport { dirname, join } from 'path';\n\nexport interface RealmCredentials {\n token: string;\n workspaceUuid?: string;\n}\n\n/** Walk up from cwd looking for dev-realms.json (like finding package.json) */\nfunction findDevRealmsFile(): string {\n let dir = process.cwd();\n while (dir !== dirname(dir)) {\n const candidate = join(dir, 'dev-realms.json');\n if (existsSync(candidate)) return candidate;\n dir = dirname(dir);\n }\n throw new Error('Cannot find dev-realms.json in any parent directory');\n}\n\nconst DEV_CLOUD_CACHE_DIR = '.dev-cloud';\nconst CACHE_MAX_AGE_MS = 60 * 60 * 1000; // 1 hour\n\nfunction findRepoRoot(): string | undefined {\n let dir = process.cwd();\n while (dir !== dirname(dir)) {\n if (existsSync(join(dir, '.git'))) {\n return dir;\n }\n dir = dirname(dir);\n }\n return undefined;\n}\n\nfunction getDevCloudCacheDir(namespace: string): string {\n const repoRoot = findRepoRoot();\n const base = repoRoot ?? process.cwd();\n return join(base, DEV_CLOUD_CACHE_DIR, namespace);\n}\n\nfunction fetchDevCloudRealms(namespace: string): string {\n const k8sNamespace = `dev-cloud-${namespace}`;\n const cmd = `kubectl exec -n ${k8sNamespace} deploy/env -c devbox -- cat /workspace/dev-realms.json`;\n try {\n return execSync(cmd, { encoding: 'utf-8', timeout: 30000 });\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n throw new Error(\n `Failed to fetch dev-realms.json from dev-cloud pod \"${namespace}\": ${message}`\n );\n }\n}\n\n/**\n * Load (and cache) the dev-realms.json file from a dev-cloud pod.\n * Returns the path to the cached file.\n */\nexport function loadDevCloudRealmFile(namespace: string): string {\n const cacheDir = getDevCloudCacheDir(namespace);\n const cachePath = join(cacheDir, 'dev-realms.json');\n\n // Check cache freshness\n if (existsSync(cachePath)) {\n const stat = statSync(cachePath);\n const age = Date.now() - stat.mtimeMs;\n if (age < CACHE_MAX_AGE_MS) {\n return cachePath;\n }\n }\n\n // Fetch from pod\n const content = fetchDevCloudRealms(namespace);\n mkdirSync(cacheDir, { recursive: true });\n writeFileSync(cachePath, content, 'utf-8');\n return cachePath;\n}\n\nexport function loadRealmCredentials(realm: string, devRealmsPath?: string): RealmCredentials {\n const filePath = devRealmsPath ?? findDevRealmsFile();\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(readFileSync(filePath, 'utf-8'));\n } catch {\n throw new Error(`Cannot read dev-realms.json at ${filePath}`);\n }\n\n const parts = realm.split('/');\n if (parts.length === 1) {\n // Account-level: --realm dr-chen\n const accounts = data._accounts as Record<string, { token?: string }> | undefined;\n const account = accounts?.[parts[0]!];\n if (!account?.token) {\n throw new Error(`Realm account \"${parts[0]}\" not found in dev-realms.json`);\n }\n return { token: account.token };\n } else {\n // Workspace/member: --realm boston-nephrology-clinic/dr-chen\n const [wsName, memberName] = parts;\n const ws = data[wsName!] as\n | { workspaceUuid?: string; members?: Record<string, { token?: string }> }\n | undefined;\n if (!ws) {\n throw new Error(`Realm workspace \"${wsName}\" not found in dev-realms.json`);\n }\n const member = ws.members?.[memberName!];\n if (!member?.token) {\n throw new Error(`Realm member \"${memberName}\" not found in workspace \"${wsName}\"`);\n }\n return { token: member.token, workspaceUuid: ws.workspaceUuid };\n }\n}\n","/**\n * CLI handler for organization-level authentication challenges.\n *\n * When a workspace API call returns a 401 with WWW-Authenticate: Bearer realm=\"org\",\n * the SDK calls this handler. The CLI attempts to satisfy the challenge by:\n *\n * 1. POSTing to /api/v2/o/{org_uuid}/join with the existing bearer token.\n * This works for organizations that allow internal (non-SSO) authentication.\n * The response Set-Cookie header contains the org JWE token.\n *\n * 2. If the org requires SSO, falls back to opening the auth URL in the browser\n * and prompting the user to complete authentication manually, then errors.\n */\n\nimport { execFile } from 'child_process';\nimport type { ApiClient } from '@gravity-rail/client';\nimport type { OrgAuthInfo } from '@gravity-rail/sdk';\nimport { stderr } from './output';\n\nconst ORG_AUTH_TIMEOUT_MS = 5 * 60 * 1000;\n\n/** Parse an org token value from Set-Cookie header strings. */\nfunction extractOrgTokenFromSetCookies(\n setCookieValues: string[],\n preferredCookieName: string\n): string | undefined {\n let fallback: string | undefined;\n\n for (const value of setCookieValues) {\n const nameValue = value.split(';')[0]?.trim() ?? '';\n const eqIdx = nameValue.indexOf('=');\n if (eqIdx === -1) continue;\n\n const name = nameValue.slice(0, eqIdx).trim();\n const tokenValue = nameValue.slice(eqIdx + 1).trim() || undefined;\n if (!tokenValue) continue;\n\n if (name === preferredCookieName) return tokenValue;\n // Accept any orgToken... or orgSession... cookie as a fallback\n if (!fallback && (name.startsWith('orgToken') || name.startsWith('orgSession'))) {\n fallback = tokenValue;\n }\n }\n\n return fallback;\n}\n\n/**\n * Attempt to satisfy an org auth challenge via the direct join endpoint.\n * Returns the org token string on success, null when SSO is required.\n * Throws on unexpected network / server errors.\n */\nasync function tryDirectJoin(\n apiUrl: string,\n accessToken: string,\n orgAuthInfo: OrgAuthInfo\n): Promise<string | null> {\n const response = await fetch(`${apiUrl}/api/v2/o/${orgAuthInfo.orgUuid}/join`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: '{}',\n });\n\n if (response.status === 400) {\n // Org requires SSO — direct join is not permitted for this account\n return null;\n }\n\n if (!response.ok) {\n // Don't include the response body — the backend currently returns safe\n // JSON, but a future change could put PHI or other sensitive data there.\n // Status code is sufficient to disambiguate the failure mode.\n throw new Error(`Org join failed (HTTP ${response.status})`);\n }\n\n // Read Set-Cookie headers to extract the org token value.\n // Node ≥18 exposes getSetCookie() on Headers; fall back to get() for older runtimes.\n const rawHeaders = response.headers as Headers & {\n getSetCookie?: () => string[];\n };\n const setCookies: string[] =\n rawHeaders.getSetCookie?.() ??\n (rawHeaders.get('set-cookie') ? [rawHeaders.get('set-cookie')!] : []);\n\n if (setCookies.length === 0) {\n throw new Error('Org join succeeded but no Set-Cookie header returned');\n }\n\n const orgToken = extractOrgTokenFromSetCookies(setCookies, orgAuthInfo.cookieName);\n if (!orgToken) {\n throw new Error('Org join succeeded but org token cookie not found in Set-Cookie');\n }\n\n return orgToken;\n}\n\n/**\n * Validate that an auth URL is safe to hand to the OS URL opener.\n *\n * `open` / `xdg-open` / `cmd.exe start` will follow any URI scheme the OS\n * registers — including `file://`, `javascript:`, and custom app handlers —\n * so a compromised/MITMed server returning an attacker-controlled `authUrl`\n * could trigger arbitrary URI execution. Restrict to http(s) and require\n * the same parent domain as the configured API host (e.g. SSO login on\n * `app.gravityrail.com` is allowed when the API is `api.gravityrail.com`,\n * but `attacker.example` against `api.gravityrail.com` is rejected).\n *\n * \"Same parent domain\" is a last-2-labels match. This is a heuristic — it\n * does not consult the Public Suffix List, so `foo.co.uk` and `bar.co.uk`\n * would falsely match — but Gravity Rail's auth hosts do not live under\n * those ccTLDs, and the alternative (vendoring `psl`) is overkill for a CLI\n * gating check. The configured `apiUrl` is itself a trust anchor controlled\n * by the user; the threat is a hostile *response* from that API (or a MITM)\n * pivoting the URL opener.\n */\nfunction isAllowedAuthUrl(url: string, apiUrl: string): boolean {\n try {\n const parsed = new URL(url);\n const api = new URL(apiUrl);\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return false;\n if (parsed.hostname === api.hostname) return true;\n\n const lastTwo = (host: string): string => {\n const parts = host.split('.').filter(Boolean);\n return parts.length >= 2 ? parts.slice(-2).join('.') : host;\n };\n // Reject IP-literal hosts from the parent-domain heuristic — last-2\n // labels of \"1.2.3.4\" would naively match \"3.4\" and admit anything.\n const isIp = /^[0-9.]+$|^\\[.*\\]$/.test(parsed.hostname);\n if (isIp) return false;\n\n return lastTwo(parsed.hostname) === lastTwo(api.hostname);\n } catch {\n return false;\n }\n}\n\n/** Open a URL in the system browser (cross-platform). */\nfunction openBrowser(url: string): void {\n let command: string;\n let args: string[];\n\n if (process.platform === 'darwin') {\n command = 'open';\n args = [url];\n } else if (process.platform === 'win32') {\n command = 'cmd.exe';\n args = ['/c', 'start', '', url];\n } else {\n command = 'xdg-open';\n args = [url];\n }\n\n execFile(command, args, (_err) => {\n // Failure is non-fatal — the URL is printed to stderr so the user can open it manually.\n });\n}\n\n/**\n * Register a CLI org-auth handler on the given client.\n *\n * The handler satisfies org-auth 401 challenges without relying on browser\n * cookies (which are not available in Node.js):\n *\n * - Non-SSO orgs: calls the join endpoint directly and reads the org token\n * from the Set-Cookie response header, then sets it via client.setOrgToken().\n * The SDK retries the original request with X-Org-Token on the next call.\n *\n * - SSO orgs: opens the browser at the authUrl and returns a timeout error\n * after ORG_AUTH_TIMEOUT_MS, because the SSO token is only ever set as a\n * browser cookie that the CLI cannot intercept.\n */\nexport function registerOrgAuthHandler(\n apiClient: ApiClient,\n apiUrl: string,\n accessToken: string\n): void {\n apiClient.setOrgAuthHandler(async (orgAuthInfo: OrgAuthInfo): Promise<void> => {\n // Fast path: non-SSO org — join directly and extract the token.\n try {\n const orgToken = await tryDirectJoin(apiUrl, accessToken, orgAuthInfo);\n if (orgToken !== null) {\n // Set the token on the client so the SDK's fallback check (this.orgToken)\n // picks it up after the handler resolves (Node.js has no document.cookie).\n // Pass the org_uuid so the SDK can detect a stale token if the next\n // request targets a different org.\n apiClient.setOrgToken(orgToken, orgAuthInfo.orgUuid);\n return;\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n stderr(`Warning: org direct-join failed (${msg}); trying browser auth`);\n }\n\n // Slow path: SSO org — the browser must complete the flow. Reject the\n // auth URL up-front if it doesn't match the configured API origin so a\n // hostile server can't pivot the OS URL opener to a `javascript:` /\n // `file://` / custom-scheme handler.\n if (!isAllowedAuthUrl(orgAuthInfo.authUrl, apiUrl)) {\n throw new Error(\n `Refusing to open organization auth URL: scheme/host does not match the configured API host. ` +\n `Re-run with the expected --api-url, or contact support.`\n );\n }\n\n stderr(`\\nThis workspace requires organization SSO authentication.`);\n stderr(`Opening browser to complete authentication...`);\n stderr(` ${orgAuthInfo.authUrl}\\n`);\n stderr(`If the browser does not open, visit the URL above manually.`);\n stderr(\n `After signing in, re-run the command — the CLI cannot receive the SSO token directly.`\n );\n openBrowser(orgAuthInfo.authUrl);\n\n // Reject after timeout so the CLI doesn't hang indefinitely.\n await new Promise<void>((_, reject) => {\n const t = setTimeout(\n () =>\n reject(\n new Error(\n 'Organization authentication timed out.\\n' +\n 'Please complete authentication in the browser, then re-run the command.'\n )\n ),\n ORG_AUTH_TIMEOUT_MS\n );\n // Unref so the timeout doesn't keep the Node.js event loop alive\n // if the parent process is otherwise done.\n t.unref?.();\n });\n });\n}\n","import { readFileSync } from 'fs';\nimport type { ParsedArgs } from './types';\nimport { CLIError } from './errors';\n\n/** Read JSON input from --data string, --file path, or stdin (if piped) */\nexport async function readJsonInput(args: ParsedArgs): Promise<unknown | undefined> {\n const dataStr = args.data as string | undefined;\n const filePath = args.file as string | undefined;\n\n if (dataStr) {\n try {\n return JSON.parse(dataStr);\n } catch {\n throw new CLIError('Invalid JSON in --data argument');\n }\n }\n\n if (filePath) {\n try {\n const content = readFileSync(filePath, 'utf-8');\n return JSON.parse(content);\n } catch (err) {\n if (err instanceof SyntaxError) {\n throw new CLIError(`Invalid JSON in file: ${filePath}`);\n }\n throw new CLIError(`Cannot read file: ${filePath}`);\n }\n }\n\n // Only consume stdin when the operator explicitly pipes JSON (e.g.\n // `echo '{}' | gr tasks create …`). Do not block on an inherited open stdin\n // fd — common in CI and agent shells where isTTY is false/undefined but no\n // data is written (causes whoami/concierge/etc. to hang until EOF).\n if (process.stdin.isTTY === true) {\n return undefined;\n }\n\n return readStdinIfPiped();\n}\n\n/** Read stdin when JSON is actually piped; return undefined if stdin is idle. */\nfunction readStdinIfPiped(): Promise<unknown | undefined> {\n return new Promise((resolve, reject) => {\n let data = '';\n let settled = false;\n\n const finish = (value: unknown) => {\n if (settled) return;\n settled = true;\n resolve(value);\n };\n\n const flush = () => {\n if (!data.trim()) {\n finish(undefined);\n return;\n }\n try {\n finish(JSON.parse(data));\n } catch {\n reject(new CLIError('Invalid JSON from stdin'));\n }\n };\n\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (chunk: string) => {\n data += chunk;\n });\n process.stdin.on('end', flush);\n process.stdin.on('error', (err: Error) => {\n reject(new CLIError(`Error reading stdin: ${err.message}`));\n });\n process.stdin.resume();\n\n // No writer connected: resolve immediately instead of waiting for EOF.\n setImmediate(() => {\n if (data) return;\n if (process.stdin.readableEnded) {\n flush();\n return;\n }\n finish(undefined);\n });\n });\n}\n","import type { ApiClient } from '@gravity-rail/client';\nimport { requireAuth } from './context';\nimport type { ArgDef, CommandDef, CommandHandlerContext } from './types';\nimport type { TableColumn } from './output';\nimport { outputData, outputSingle } from './output';\nimport { CLIError } from './errors';\nimport { LIST_PAGINATION_ARGS, fetchAllPages, listResult, unwrapItems } from './pagination';\n\n/**\n * @deprecated Use `SimpleCrudConfig` with `simpleCrudCommands()` for new code.\n *\n * This interface uses string method names that are resolved at runtime via\n * dynamic dispatch, which prevents TypeScript from validating call signatures.\n * It is safe for simple top-level CRUD resources but must NOT be used for\n * nested resources that require parent IDs.\n */\nexport interface CrudConfig<T = unknown> {\n prefix: string[];\n entityName: string;\n listMethod?: string;\n getMethod?: string;\n createMethod?: string;\n updateMethod?: string;\n deleteMethod?: string;\n archiveMethod?: string;\n unarchiveMethod?: string;\n /** When true, adds a --cascade flag to the delete command. Only enable for entities whose backend endpoint accepts a cascade parameter. */\n supportsCascade?: boolean;\n columns?: TableColumn<T>[];\n requiresWorkspace?: boolean;\n listArgs?: ArgDef[];\n extra?: CommandDef[];\n /** Example lines shown in help for the create command */\n createExamples?: string[];\n /**\n * Controls how the CRUD list handler interacts with pagination.\n *\n * - `'full'` — The client method accepts an options object with page/pageSize.\n * Pagination args (--page, --page-size, --all) are injected and\n * forwarded to the API method via `callApiWithOptions`.\n * - `'client-only'` — Pagination args are injected for --all support (client-side\n * page-walking), but options are NOT forwarded to the API method.\n * Use for raw-array endpoints that don't accept page/pageSize.\n * - `false` — No pagination args are injected. The list method is called with\n * `callApi` (workspace-only) or `callApiWithOptions` for domain\n * listArgs only. Use for legacy/positional signatures where passing\n * an options object would be misinterpreted.\n *\n * Default: `false` (safe — never forwards pagination options unless opted in).\n */\n paginationSupport?: 'full' | 'client-only' | false;\n}\n\n/**\n * @deprecated Use `simpleCrudCommands()` for new code — it provides compile-time\n * safety via typed callables instead of string method names.\n *\n * Existing usages are safe for simple top-level CRUD resources. Do NOT use this\n * for nested resources that require parent IDs (workflowId, memberId, toolkitId, etc.).\n */\nexport function crudCommands<T>(config: CrudConfig<T>): CommandDef[] {\n const {\n prefix,\n entityName,\n columns,\n requiresWorkspace = true,\n listArgs = [],\n extra = [],\n } = config;\n\n // Default: false (safe — never forwards pagination options unless explicitly opted in)\n const paginationSupport = config.paginationSupport ?? false;\n\n const cmds: CommandDef[] = [];\n\n if (config.listMethod) {\n // Determine which args to expose on this list command.\n // 'full' and 'client-only' inject pagination args; false does not.\n const injectPaginationArgs = paginationSupport !== false;\n const seenArgNames = new Set(listArgs.map((a) => a.name));\n const mergedArgs = injectPaginationArgs\n ? [...listArgs, ...LIST_PAGINATION_ARGS.filter((a) => !seenArgNames.has(a.name))]\n : [...listArgs];\n\n cmds.push({\n path: [...prefix, 'list'],\n description: `List ${entityName}s`,\n args: mergedArgs,\n requiresWorkspace,\n columns: columns as TableColumn<unknown>[] | undefined,\n handler: async (hctx: CommandHandlerContext) => {\n // Track whether the domain defines custom list args (domain filters or pagination).\n // When true, always pass an options object to the API method for compatibility.\n const domainHasListArgs = listArgs.length > 0;\n\n if (injectPaginationArgs && hctx.args['all']) {\n let allItems: unknown[];\n if (paginationSupport === 'full') {\n // Fetch all pages using server-side pagination\n allItems = await fetchAllPages(async ({ page, pageSize }) => {\n const opts = buildListOptions(hctx, listArgs);\n opts['page'] = page;\n opts['pageSize'] = pageSize;\n return callApiWithOptions(hctx, config.listMethod!, requiresWorkspace, opts);\n });\n } else {\n // client-only: single fetch, return whatever the API gives us\n const result = await callApi(hctx, config.listMethod!, requiresWorkspace);\n allItems = unwrapItems(result);\n }\n outputData(allItems, hctx.ctx, columns as TableColumn<T>[] | undefined);\n } else if (paginationSupport === 'full') {\n // Build options from domain-specific + pagination args\n const opts = buildListOptions(hctx, mergedArgs);\n const result =\n domainHasListArgs || Object.keys(opts).length > 0\n ? await callApiWithOptions(hctx, config.listMethod!, requiresWorkspace, opts)\n : await callApi(hctx, config.listMethod!, requiresWorkspace);\n // Explicit contract: supportsAll=true because this path exposes --all\n outputData(\n listResult(result, true),\n hctx.ctx,\n columns as TableColumn<T>[] | undefined\n );\n } else {\n // paginationSupport is false or 'client-only': never forward options to the API.\n // Only pass domain listArgs if the domain defines custom args and the method\n // is options-compatible (domainHasListArgs implies the method accepts an object).\n if (domainHasListArgs) {\n const opts = buildListOptions(hctx, listArgs);\n const result =\n Object.keys(opts).length > 0\n ? await callApiWithOptions(\n hctx,\n config.listMethod!,\n requiresWorkspace,\n opts\n )\n : await callApi(hctx, config.listMethod!, requiresWorkspace);\n outputData(\n listResult(result, false),\n hctx.ctx,\n columns as TableColumn<T>[] | undefined\n );\n } else {\n const result = await callApi(hctx, config.listMethod!, requiresWorkspace);\n outputData(\n listResult(result, false),\n hctx.ctx,\n columns as TableColumn<T>[] | undefined\n );\n }\n }\n },\n });\n }\n\n if (config.getMethod) {\n cmds.push({\n path: [...prefix, 'get'],\n description: `Get a ${entityName} by ID`,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n columns: columns as TableColumn<unknown>[] | undefined,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const result = await callApiWithId(hctx, config.getMethod!, id, requiresWorkspace);\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.createMethod) {\n cmds.push({\n path: [...prefix, 'create'],\n description: `Create a ${entityName}`,\n mutates: true,\n requiresWorkspace,\n ...(config.createExamples ? { examples: config.createExamples } : {}),\n handler: async (hctx: CommandHandlerContext) => {\n if (!hctx.data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await callApiWithData(hctx, config.createMethod!, requiresWorkspace);\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.updateMethod) {\n cmds.push({\n path: [...prefix, 'update'],\n description: `Update a ${entityName}`,\n mutates: true,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n if (!hctx.data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = resolveId(hctx);\n const result = await callApiWithIdAndData(\n hctx,\n config.updateMethod!,\n id,\n requiresWorkspace\n );\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.deleteMethod) {\n const deleteArgs: ArgDef[] = [\n { name: 'id', description: `${entityName} ID`, required: true },\n ];\n if (config.supportsCascade) {\n deleteArgs.push({\n name: 'cascade',\n description: 'Also delete dependent child entities',\n required: false,\n isFlag: true,\n });\n }\n cmds.push({\n path: [...prefix, 'delete'],\n description: `Delete a ${entityName}`,\n mutates: true,\n args: deleteArgs,\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n if (config.supportsCascade) {\n const cascade = hctx.args.cascade === true;\n const result = await callMethod(\n hctx,\n config.deleteMethod!,\n requiresWorkspace ? [hctx.workspace, id, cascade] : [id, cascade]\n );\n const suffix =\n result &&\n typeof result === 'object' &&\n 'deletedTaskCount' in result &&\n result.deletedTaskCount\n ? ` and ${result.deletedTaskCount} child entities`\n : '';\n process.stdout.write(`Deleted ${entityName} ${id}${suffix}\\n`);\n } else {\n await callApiWithId(hctx, config.deleteMethod!, id, requiresWorkspace);\n process.stdout.write(`Deleted ${entityName} ${id}\\n`);\n }\n },\n });\n }\n\n if (config.archiveMethod) {\n cmds.push({\n path: [...prefix, 'archive'],\n description: `Archive a ${entityName}`,\n mutates: true,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const result = await callApiWithId(hctx, config.archiveMethod!, id, requiresWorkspace);\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.unarchiveMethod) {\n cmds.push({\n path: [...prefix, 'unarchive'],\n description: `Unarchive a ${entityName}`,\n mutates: true,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const result = await callApiWithId(\n hctx,\n config.unarchiveMethod!,\n id,\n requiresWorkspace\n );\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n return [...cmds, ...extra];\n}\n\nfunction resolveId(hctx: CommandHandlerContext): string {\n const id = (hctx.args.id ?? hctx.args.uuid) as string | undefined;\n if (!id) throw new CLIError('--id is required');\n return id;\n}\n\n/**\n * Encapsulates the dynamic dispatch used by the legacy stringly-typed\n * `crudCommands()` factory. The `ApiClient` is structurally typed —\n * we deliberately erase that type here to allow string-key lookup, but the\n * scope of the unsafe access is contained in this single helper instead of\n * leaking into every call site.\n */\nfunction callMethod(\n hctx: CommandHandlerContext,\n method: string,\n args: unknown[]\n): Promise<unknown> {\n const client = requireAuth(hctx.ctx).apiClient as unknown as Record<\n string,\n (...a: unknown[]) => Promise<unknown>\n >;\n const fn = client[method];\n if (typeof fn !== 'function') {\n throw new CLIError(`API method not found: ${method}`);\n }\n return fn.apply(client, args);\n}\n\nasync function callApi(\n hctx: CommandHandlerContext,\n method: string,\n requiresWorkspace: boolean\n): Promise<unknown> {\n return callMethod(hctx, method, requiresWorkspace ? [hctx.workspace] : []);\n}\n\nasync function callApiWithId(\n hctx: CommandHandlerContext,\n method: string,\n id: string,\n requiresWorkspace: boolean\n): Promise<unknown> {\n return callMethod(hctx, method, requiresWorkspace ? [hctx.workspace, id] : [id]);\n}\n\nasync function callApiWithData(\n hctx: CommandHandlerContext,\n method: string,\n requiresWorkspace: boolean\n): Promise<unknown> {\n return callMethod(hctx, method, requiresWorkspace ? [hctx.workspace, hctx.data] : [hctx.data]);\n}\n\nasync function callApiWithIdAndData(\n hctx: CommandHandlerContext,\n method: string,\n id: string,\n requiresWorkspace: boolean\n): Promise<unknown> {\n return callMethod(\n hctx,\n method,\n requiresWorkspace ? [hctx.workspace, id, hctx.data] : [id, hctx.data]\n );\n}\n\nfunction buildListOptions(\n hctx: CommandHandlerContext,\n listArgs: ArgDef[]\n): Record<string, unknown> {\n const opts: Record<string, unknown> = {};\n for (const arg of listArgs) {\n if (arg.name === 'all') continue; // handled by caller, not sent to API\n const key = arg.name.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());\n const val = hctx.args[arg.name];\n if (val !== undefined) {\n if (key === 'page' || key === 'pageSize') {\n const num = Number(val);\n if (isNaN(num) || num < 1)\n throw new CLIError(`--${arg.name} must be a positive integer`);\n if (key === 'pageSize' && num > 100)\n throw new CLIError(`--${arg.name} must be at most 100 (API limit)`);\n opts[key] = num;\n } else {\n opts[key] = val;\n }\n }\n }\n return opts;\n}\n\nasync function callApiWithOptions(\n hctx: CommandHandlerContext,\n method: string,\n requiresWorkspace: boolean,\n opts: Record<string, unknown>\n): Promise<unknown> {\n return callMethod(hctx, method, requiresWorkspace ? [hctx.workspace, opts] : [opts]);\n}\n\n// ---------------------------------------------------------------------------\n// SimpleCrudConfig — typed-callable variant of CrudConfig\n// ---------------------------------------------------------------------------\n\n/**\n * Typed CRUD config for simple, top-level resources.\n *\n * Unlike the stringly-typed `CrudConfig`, operations are typed functions that\n * receive the real `ApiClient`. TypeScript validates the call at the definition\n * site, eliminating the string-dispatch + positional-argument blind spot.\n *\n * Use this for resources that fit the simple CRUD contract:\n * - optional workspace scope\n * - single resource ID (no parent IDs)\n * - optional list-options object\n *\n * For nested resources that need parent IDs, use explicit handlers.\n *\n * @example\n * ```ts\n * simpleCrudCommands({\n * prefix: ['tasks'],\n * entityName: 'task',\n * list: (client, wid) => client.getTasks(wid),\n * get: (client, wid, id) => client.getTask(wid, id),\n * create: (client, wid, data) => client.createTask(wid, data),\n * update: (client, wid, id, data) => client.updateTask(wid, id, data),\n * delete: (client, wid, id) => client.deleteTask(wid, id),\n * })\n * ```\n */\nexport interface SimpleCrudConfig<T = unknown> {\n prefix: string[];\n entityName: string;\n columns?: TableColumn<T>[];\n requiresWorkspace?: boolean;\n listArgs?: ArgDef[];\n extra?: CommandDef[];\n createExamples?: string[];\n paginationSupport?: 'full' | 'client-only' | false;\n\n // Typed operations — each receives the real ApiClient and typed positional args\n list?: (\n client: ApiClient,\n workspace: string,\n opts?: Record<string, unknown>\n ) => Promise<unknown>;\n get?: (client: ApiClient, workspace: string, id: string) => Promise<unknown>;\n create?: (client: ApiClient, workspace: string, data: unknown) => Promise<unknown>;\n update?: (client: ApiClient, workspace: string, id: string, data: unknown) => Promise<unknown>;\n delete?: (client: ApiClient, workspace: string, id: string) => Promise<unknown>;\n archive?: (client: ApiClient, workspace: string, id: string) => Promise<unknown>;\n unarchive?: (client: ApiClient, workspace: string, id: string) => Promise<unknown>;\n\n /** When true, adds a --cascade flag to the delete command. */\n supportsCascade?: boolean;\n deleteFn?: (\n client: ApiClient,\n workspace: string,\n id: string,\n cascade: boolean\n ) => Promise<unknown>;\n}\n\n/**\n * Generate CRUD commands from typed callable functions.\n *\n * This is the recommended path for new simple CRUD domains. It provides\n * compile-time safety by accepting typed callables instead of string method names.\n */\nexport function simpleCrudCommands<T>(config: SimpleCrudConfig<T>): CommandDef[] {\n const {\n prefix,\n entityName,\n columns,\n requiresWorkspace = true,\n listArgs = [],\n extra = [],\n } = config;\n\n const paginationSupport = config.paginationSupport ?? false;\n const cmds: CommandDef[] = [];\n\n if (config.list) {\n const listFn = config.list;\n const injectPaginationArgs = paginationSupport !== false;\n const seenArgNames = new Set(listArgs.map((a) => a.name));\n const mergedArgs = injectPaginationArgs\n ? [...listArgs, ...LIST_PAGINATION_ARGS.filter((a) => !seenArgNames.has(a.name))]\n : [...listArgs];\n\n cmds.push({\n path: [...prefix, 'list'],\n description: `List ${entityName}s`,\n args: mergedArgs,\n requiresWorkspace,\n columns: columns as TableColumn<unknown>[] | undefined,\n handler: async (hctx: CommandHandlerContext) => {\n const client = requireAuth(hctx.ctx).apiClient;\n const domainHasListArgs = listArgs.length > 0;\n\n if (injectPaginationArgs && hctx.args['all']) {\n let allItems: unknown[];\n if (paginationSupport === 'full') {\n allItems = await fetchAllPages(async ({ page, pageSize }) => {\n const opts = buildListOptions(hctx, listArgs);\n opts['page'] = page;\n opts['pageSize'] = pageSize;\n return listFn(client, hctx.workspace, opts);\n });\n } else {\n const result = await listFn(client, hctx.workspace);\n allItems = unwrapItems(result);\n }\n outputData(allItems, hctx.ctx, columns as TableColumn<T>[] | undefined);\n } else if (paginationSupport === 'full') {\n const opts = buildListOptions(hctx, mergedArgs);\n const result =\n domainHasListArgs || Object.keys(opts).length > 0\n ? await listFn(client, hctx.workspace, opts)\n : await listFn(client, hctx.workspace);\n outputData(\n listResult(result, true),\n hctx.ctx,\n columns as TableColumn<T>[] | undefined\n );\n } else {\n if (domainHasListArgs) {\n const opts = buildListOptions(hctx, listArgs);\n const result =\n Object.keys(opts).length > 0\n ? await listFn(client, hctx.workspace, opts)\n : await listFn(client, hctx.workspace);\n outputData(\n listResult(result, false),\n hctx.ctx,\n columns as TableColumn<T>[] | undefined\n );\n } else {\n const result = await listFn(client, hctx.workspace);\n outputData(\n listResult(result, false),\n hctx.ctx,\n columns as TableColumn<T>[] | undefined\n );\n }\n }\n },\n });\n }\n\n if (config.get) {\n const getFn = config.get;\n cmds.push({\n path: [...prefix, 'get'],\n description: `Get a ${entityName} by ID`,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n columns: columns as TableColumn<unknown>[] | undefined,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const result = await getFn(requireAuth(hctx.ctx).apiClient, hctx.workspace, id);\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.create) {\n const createFn = config.create;\n cmds.push({\n path: [...prefix, 'create'],\n description: `Create a ${entityName}`,\n mutates: true,\n requiresWorkspace,\n ...(config.createExamples ? { examples: config.createExamples } : {}),\n handler: async (hctx: CommandHandlerContext) => {\n if (!hctx.data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await createFn(\n requireAuth(hctx.ctx).apiClient,\n hctx.workspace,\n hctx.data\n );\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.update) {\n const updateFn = config.update;\n cmds.push({\n path: [...prefix, 'update'],\n description: `Update a ${entityName}`,\n mutates: true,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n if (!hctx.data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = resolveId(hctx);\n const result = await updateFn(\n requireAuth(hctx.ctx).apiClient,\n hctx.workspace,\n id,\n hctx.data\n );\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.delete || config.deleteFn) {\n const deleteArgs: ArgDef[] = [\n { name: 'id', description: `${entityName} ID`, required: true },\n ];\n if (config.supportsCascade) {\n deleteArgs.push({\n name: 'cascade',\n description: 'Also delete dependent child entities',\n required: false,\n isFlag: true,\n });\n }\n cmds.push({\n path: [...prefix, 'delete'],\n description: `Delete a ${entityName}`,\n mutates: true,\n args: deleteArgs,\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const client = requireAuth(hctx.ctx).apiClient;\n if (config.deleteFn) {\n const cascade = config.supportsCascade ? hctx.args.cascade === true : false;\n const result = await config.deleteFn(client, hctx.workspace, id, cascade);\n const suffix =\n result &&\n typeof result === 'object' &&\n 'deletedTaskCount' in result &&\n result.deletedTaskCount\n ? ` and ${result.deletedTaskCount} child entities`\n : '';\n process.stdout.write(`Deleted ${entityName} ${id}${suffix}\\n`);\n } else if (config.delete) {\n await config.delete(client, hctx.workspace, id);\n process.stdout.write(`Deleted ${entityName} ${id}\\n`);\n }\n },\n });\n }\n\n if (config.archive) {\n const archiveFn = config.archive;\n cmds.push({\n path: [...prefix, 'archive'],\n description: `Archive a ${entityName}`,\n mutates: true,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const result = await archiveFn(requireAuth(hctx.ctx).apiClient, hctx.workspace, id);\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n if (config.unarchive) {\n const unarchiveFn = config.unarchive;\n cmds.push({\n path: [...prefix, 'unarchive'],\n description: `Unarchive a ${entityName}`,\n mutates: true,\n args: [{ name: 'id', description: `${entityName} ID`, required: true }],\n requiresWorkspace,\n handler: async (hctx: CommandHandlerContext) => {\n const id = resolveId(hctx);\n const result = await unarchiveFn(requireAuth(hctx.ctx).apiClient, hctx.workspace, id);\n outputSingle(result as T, hctx.ctx, columns as TableColumn<T>[] | undefined);\n },\n });\n }\n\n return [...cmds, ...extra];\n}\n","import type { CommandDef, DomainDef } from './types';\n\nexport class CommandRegistry {\n private commands = new Map<string, CommandDef>();\n private domains: DomainDef[] = [];\n\n register(domain: DomainDef): void {\n this.domains.push(domain);\n for (const cmd of domain.commands) {\n const key = cmd.path.join(' ');\n this.commands.set(key, cmd);\n }\n }\n\n registerCommand(cmd: CommandDef): void {\n const key = cmd.path.join(' ');\n this.commands.set(key, cmd);\n }\n\n /** Resolve command words to a CommandDef using longest-match.\n * Supports {param} path segments that match any word and extract as pathParams. */\n resolve(\n words: string[]\n ): { cmd: CommandDef; rest: string[]; pathParams: Record<string, string> } | undefined {\n // Try exact match first (4-word, 3-word, 2-word, 1-word)\n for (let len = Math.min(words.length, 4); len >= 1; len--) {\n const key = words.slice(0, len).join(' ');\n const cmd = this.commands.get(key);\n if (cmd) {\n return { cmd, rest: words.slice(len), pathParams: {} };\n }\n }\n // Try pattern match ({param} segments)\n for (const [, cmd] of this.commands) {\n if (cmd.path.length > words.length) continue;\n const params: Record<string, string> = {};\n let matched = true;\n for (let i = 0; i < cmd.path.length; i++) {\n const segment = cmd.path[i]!;\n const word = words[i]!;\n if (segment.startsWith('{') && segment.endsWith('}')) {\n params[segment.slice(1, -1)] = word;\n } else if (segment !== word) {\n matched = false;\n break;\n }\n }\n if (matched) {\n return { cmd, rest: words.slice(cmd.path.length), pathParams: params };\n }\n }\n return undefined;\n }\n\n /** Generate help text. If prefix given, show commands under that prefix. */\n getHelp(prefix?: string[]): string {\n if (!prefix || prefix.length === 0) {\n return this.getTopLevelHelp();\n }\n\n const prefixStr = prefix.join(' ');\n const matching: CommandDef[] = [];\n for (const [key, cmd] of this.commands) {\n if (key.startsWith(prefixStr + ' ') || key === prefixStr) {\n matching.push(cmd);\n }\n }\n\n // Also match commands with {param} segments in the prefix position\n for (const [, cmd] of this.commands) {\n if (matching.includes(cmd)) continue;\n if (cmd.path.length <= prefix.length) continue;\n let prefixMatches = true;\n for (let i = 0; i < prefix.length; i++) {\n const seg = cmd.path[i]!;\n if (seg !== prefix[i] && !(seg.startsWith('{') && seg.endsWith('}'))) {\n prefixMatches = false;\n break;\n }\n }\n if (prefixMatches) matching.push(cmd);\n }\n\n if (matching.length === 0) {\n return `No commands found for: ${prefixStr}`;\n }\n\n // If exactly one command matched (leaf command), show detailed help\n if (matching.length === 1 && matching[0]!.path.join(' ') === prefixStr) {\n return this.getCommandHelp(matching[0]!);\n }\n\n // Determine the placeholder: if all next segments are {param}, use that param name\n const nextSegments = new Set(matching.map((cmd) => cmd.path[prefix.length]).filter(Boolean));\n const allParams = [...nextSegments].every((s) => s!.startsWith('{') && s!.endsWith('}'));\n const placeholder =\n allParams && nextSegments.size === 1\n ? `<${[...nextSegments][0]!.slice(1, -1)}>`\n : '<command>';\n\n const lines = [`Usage: gr ${prefixStr} ${placeholder} [options]\\n`, 'Commands:'];\n for (const cmd of matching.sort((a, b) => a.path.join(' ').localeCompare(b.path.join(' ')))) {\n const subPath = cmd.path.slice(prefix.length).join(' ') || cmd.path[cmd.path.length - 1]!;\n lines.push(` ${subPath.padEnd(28)} ${cmd.description}`);\n }\n return lines.join('\\n') + '\\n';\n }\n\n private getCommandHelp(cmd: CommandDef): string {\n const cmdStr = cmd.path.join(' ');\n const lines = [`${cmd.description}\\n`, `Usage: gr ${cmdStr} [options]`];\n\n if (cmd.requiresWorkspace) {\n lines.push(' Requires: -w <workspace-uuid>');\n }\n if (cmd.mutates) {\n lines.push(' Requires: --allow-write');\n }\n\n if (cmd.args && cmd.args.length > 0) {\n lines.push('', 'Arguments:');\n for (const arg of cmd.args) {\n const flag = arg.isFlag ? `--${arg.name}` : `--${arg.name} <value>`;\n const req = arg.required ? ' (required)' : '';\n lines.push(` ${flag.padEnd(28)} ${arg.description}${req}`);\n }\n }\n\n if (cmd.examples && cmd.examples.length > 0) {\n lines.push('', 'Examples:');\n for (const ex of cmd.examples) {\n lines.push(` ${ex}`);\n }\n }\n\n return lines.join('\\n') + '\\n';\n }\n\n private getTopLevelHelp(): string {\n const lines = ['Usage: gr <command> [options]\\n', 'Commands:'];\n\n // Group by domain\n const seen = new Set<string>();\n for (const domain of this.domains) {\n if (!seen.has(domain.name)) {\n seen.add(domain.name);\n lines.push(` ${domain.name.padEnd(28)} ${domain.description}`);\n }\n }\n\n // Add standalone commands (not in any domain)\n for (const [, cmd] of this.commands) {\n const topWord = cmd.path[0]!;\n if (!seen.has(topWord) && cmd.path.length === 1) {\n seen.add(topWord);\n lines.push(` ${topWord.padEnd(28)} ${cmd.description}`);\n }\n }\n\n lines.push(\n '',\n 'Global Options:',\n ' --env <env> Environment: dev, staging, prod (default: dev)',\n ' -o, --output-format <fmt> Output format: json, jsonl, table (default: auto)',\n ' -v, --verbose Verbose output to stderr',\n ' --help Show help',\n ' --version Show version'\n );\n\n return lines.join('\\n') + '\\n';\n }\n}\n","import type { AuthenticatedContext, CommandContext } from './context';\nimport type { TableColumn } from './output';\n\nexport interface ArgDef {\n name: string;\n alias?: string;\n /** Additional long-form aliases (e.g. ['workspace-id', 'id'] for --wid) */\n aliases?: string[];\n description: string;\n required?: boolean;\n isFlag?: boolean;\n default?: string | boolean;\n}\n\nexport type ParsedArgs = Record<string, string | boolean | undefined>;\n\n/**\n * Context passed to a command handler.\n *\n * `ctx` is a discriminated union of `AuthenticatedContext` and `CommandContext`.\n * Handlers registered without `requiresAuth: false` always receive an\n * `AuthenticatedContext` at runtime, but the type does not express this — call\n * `requireAuth(hctx.ctx)` before accessing `apiClient` / `accessToken` so that\n * a handler missing `requiresAuth: false` cannot silently access undefined\n * fields if it is later miswired.\n */\nexport interface CommandHandlerContext {\n ctx: AuthenticatedContext | CommandContext;\n args: ParsedArgs;\n workspace: string;\n data?: unknown;\n}\n\nexport interface CommandDef<T = unknown> {\n path: string[];\n description: string;\n args?: ArgDef[];\n /** Example usage lines shown in command-level help */\n examples?: string[];\n requiresWorkspace?: boolean;\n requiresAuth?: boolean;\n /** Whether this command mutates data. Requires --allow-write to execute. */\n mutates?: boolean;\n columns?: TableColumn<T>[];\n handler: (hctx: CommandHandlerContext) => Promise<void>;\n}\n\nexport interface DomainDef {\n name: string;\n description: string;\n commands: CommandDef[];\n}\n\n/** Extract a required string arg, throwing if missing or not a string */\nexport function requireString(args: ParsedArgs, key: string): string {\n const val = args[key];\n if (typeof val !== 'string') throw new Error(`Missing required argument: --${key}`);\n return val;\n}\n\n/** Extract a required numeric arg, throwing if missing */\nexport function requireNumber(args: ParsedArgs, key: string): number {\n const val = args[key];\n if (typeof val !== 'string') throw new Error(`Missing required argument: --${key}`);\n const num = Number(val);\n if (isNaN(num)) throw new Error(`Argument --${key} must be a number`);\n return num;\n}\n\n/** First matching numeric arg among primary name and aliases (e.g. id + phone-number-id). */\nexport function requireNumberFrom(args: ParsedArgs, ...keys: string[]): number {\n for (const key of keys) {\n const val = args[key];\n if (typeof val === 'string') {\n const num = Number(val);\n if (!isNaN(num)) return num;\n }\n }\n const hint = keys.map((k) => `--${k}`).join(' or ');\n throw new Error(`Missing required argument: ${hint}`);\n}\n","import type { DomainDef } from '../lib/types';\nimport { requireString } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\n// Operator-facing CLI domain for async sub-agent tasks.\n//\n// Unlike the LLM a2a tools (which are scoped to the requestor for\n// inter-agent isolation), this domain calls workspace-scoped HTTP routes\n// that return any agent task in the workspace. The routes require the\n// caller to hold MEMBERS_READ / MEMBERS_WRITE — they are for operators,\n// not sibling agents.\n\nconst LIST_COLUMNS: TableColumn<unknown>[] = [\n { header: 'UUID', getValue: (item: any) => String(item.uuid ?? '') },\n { header: 'STATUS', getValue: (item: any) => String(item.status ?? '') },\n {\n header: 'AGENT',\n getValue: (item: any) => (item.agentMemberId != null ? String(item.agentMemberId) : ''),\n },\n { header: 'DEPTH', getValue: (item: any) => String(item.depth ?? 0) },\n { header: 'CREATED', getValue: (item: any) => String(item.createdAt ?? '') },\n];\n\nconst MESSAGE_COLUMNS: TableColumn<unknown>[] = [\n { header: 'ROLE', getValue: (item: any) => String(item.role ?? '') },\n {\n header: 'TIMESTAMP',\n getValue: (item: any) => String(item.receivedAt ?? ''),\n },\n {\n header: 'CONTENT',\n getValue: (item: any) => {\n const content = String(item.content ?? '');\n const oneLine = content.replace(/\\s+/g, ' ').trim();\n return oneLine.length > 80 ? `${oneLine.slice(0, 77)}...` : oneLine;\n },\n },\n];\n\nexport const agentTasksDomain: DomainDef = {\n name: 'agent-tasks',\n description:\n 'Inspect and cancel async sub-agent tasks (operator-facing; requires members_read/write)',\n commands: [\n {\n path: ['agent-tasks', 'list'],\n description: 'List agent tasks in the workspace (newest first)',\n requiresWorkspace: true,\n args: [\n {\n name: 'status',\n description:\n 'Filter by A2A state (submitted|working|input-required|completed|failed|canceled|rejected|auth-required)',\n required: false,\n },\n {\n name: 'agent',\n description: 'Filter by executing agent member id',\n required: false,\n },\n {\n name: 'parent-task',\n description:\n 'Filter by parent agent task uuid (not supported server-side yet — filters by id)',\n required: false,\n },\n {\n name: 'limit',\n description: 'Max rows to return (default 50)',\n required: false,\n },\n ],\n columns: LIST_COLUMNS,\n handler: async ({ ctx, workspace, args }) => {\n const params: {\n status?: any;\n agentMemberId?: number;\n parentTaskId?: number;\n limit?: number;\n } = {};\n if (typeof args.status === 'string') params.status = args.status;\n if (typeof args.agent === 'string') {\n const n = Number(args.agent);\n if (!isNaN(n)) params.agentMemberId = n;\n }\n if (typeof args['parent-task'] === 'string') {\n const n = Number(args['parent-task']);\n if (!isNaN(n)) params.parentTaskId = n;\n }\n if (typeof args.limit === 'string') {\n const n = Number(args.limit);\n if (!isNaN(n)) params.limit = n;\n }\n const result = await requireAuth(ctx).apiClient.getAgentTasks(workspace, params);\n outputData(result, ctx, LIST_COLUMNS);\n },\n },\n {\n path: ['agent-tasks', 'get'],\n description: 'Get a single agent task by UUID',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Agent task UUID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getAgentTask(\n workspace,\n requireString(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['agent-tasks', 'cancel'],\n description: 'Cancel a running agent task (idempotent; terminal tasks are returned as-is)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Agent task UUID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.cancelAgentTask(\n workspace,\n requireString(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['agent-tasks', 'messages'],\n description: 'Show recent messages from a sub-agent task context chat',\n requiresWorkspace: true,\n args: [\n { name: 'id', description: 'Agent task UUID', required: true },\n {\n name: 'limit',\n description: 'Max messages to return (default 20)',\n required: false,\n },\n ],\n columns: MESSAGE_COLUMNS,\n handler: async ({ ctx, workspace, args }) => {\n const params: { limit?: number } = {};\n if (typeof args.limit === 'string') {\n const n = Number(args.limit);\n if (!isNaN(n)) params.limit = n;\n }\n const result = await requireAuth(ctx).apiClient.getAgentTaskMessages(\n workspace,\n requireString(args, 'id'),\n params\n );\n outputData(result, ctx, MESSAGE_COLUMNS);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { COL } from '../lib/output';\n\nconst COLUMNS = [COL.id(), COL.uuid(), COL.name(), COL.status(), COL.created()];\n\nexport const agentsDomain: DomainDef = {\n name: 'agents',\n description: 'Manage agents',\n commands: [\n ...crudCommands({\n prefix: ['agents'],\n entityName: 'agent',\n listMethod: 'getAgents',\n getMethod: 'getAgent',\n createMethod: 'createAgent',\n updateMethod: 'updateAgent',\n deleteMethod: 'deleteAgent',\n archiveMethod: 'archiveAgent',\n unarchiveMethod: 'unarchiveAgent',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n ],\n};\n","import { type DomainDef, requireNumber, requireNumberFrom } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { AGUIClient, getTextDelta, getErrorMessage } from '../cli-utils';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n { header: 'TYPE', getValue: (item: any) => item.chatType ?? item.chat_type ?? '' },\n { header: 'MEMBER', getValue: (item: any) => item.member_name ?? String(item.member_id ?? '') },\n COL.status(),\n { header: 'CHANNEL', getValue: (item: any) => item.channel ?? '' },\n COL.created(),\n];\n\nconst LABEL_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n COL.name(),\n { header: 'COLOR', getValue: (item: any) => item.color ?? '' },\n];\n\nconst FILTER_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.uuid(), COL.name()];\n\nconst MESSAGE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'ROLE', getValue: (item: any) => item.role ?? '' },\n {\n header: 'CONTENT',\n getValue: (item: any) => String(item.content ?? '').slice(0, 80),\n maxWidth: 80,\n },\n {\n header: 'TOOL_CALLS',\n getValue: (item: any) =>\n Array.isArray(item.tool_calls) && item.tool_calls.length > 0\n ? item.tool_calls.map((t: any) => t.function?.name ?? '?').join(',')\n : '',\n },\n COL.created(),\n];\n\nexport const chatsDomain: DomainDef = {\n name: 'chats',\n description: 'Manage chats',\n commands: [\n ...crudCommands({\n prefix: ['chats'],\n entityName: 'chat',\n listMethod: 'getChats',\n getMethod: 'getChat',\n createMethod: 'createChat',\n updateMethod: 'updateChat',\n deleteMethod: 'deleteChat',\n archiveMethod: 'archiveChat',\n unarchiveMethod: 'unarchiveChat',\n columns: COLUMNS,\n paginationSupport: 'full',\n listArgs: [\n { name: 'search', description: 'Search by name' },\n { name: 'channel', description: 'Filter by channel (phone, sms, web, email)' },\n {\n name: 'is-anonymous',\n description: 'Show only anonymous chats (requires CHATS_ADMIN)',\n isFlag: true,\n },\n { name: 'is-test', description: 'Show only test chats', isFlag: true },\n { name: 'member-id', description: 'Filter by member ID' },\n {\n name: 'chat-type',\n description:\n 'Filter by chat type (assignment, manager, developer, member, contributor). Default: assignment',\n },\n ],\n }),\n // Messages\n {\n path: ['chats', 'messages', 'list'],\n description:\n 'List messages for a chat. Use --limit/--offset to page; the API caps a single request at 100. Tool-call shell rows that the API filter excludes (parent_message_id IS NOT NULL or parent_call_id IS NOT NULL) are still hidden — use `gr chats inspect --id <chat>` for the full debug view.',\n requiresWorkspace: true,\n args: [\n { name: 'chat-id', aliases: ['id'], description: 'Chat ID', required: true },\n {\n name: 'limit',\n description: 'Max messages to return (1-100, default 100)',\n },\n {\n name: 'offset',\n description: 'Offset for pagination (default 0)',\n },\n ],\n handler: async ({ ctx, workspace, args }) => {\n // Default to 100 (the API max). The API's own default of 10\n // hides almost every message in long voice chats — operators\n // hit it constantly when debugging EventRule canned messages\n // that show up later in the conversation. See\n // docs/dev/xai-grok-voice-agent-audit-2026-04-24.md \"P5\".\n const rawLimit = (args as any).limit;\n const rawOffset = (args as any).offset;\n const limit =\n rawLimit === undefined || rawLimit === null || rawLimit === ''\n ? 100\n : Number(rawLimit);\n const offset =\n rawOffset === undefined || rawOffset === null || rawOffset === ''\n ? 0\n : Number(rawOffset);\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) {\n throw new Error('--limit must be an integer between 1 and 100');\n }\n if (!Number.isInteger(offset) || offset < 0) {\n throw new Error('--offset must be a non-negative integer');\n }\n const result = await requireAuth(ctx).apiClient.getChatMessages(\n workspace,\n requireNumberFrom(args, 'chat-id', 'id'),\n limit,\n offset\n );\n outputData(result, ctx, MESSAGE_COLUMNS);\n },\n },\n {\n path: ['chats', 'messages', 'send'],\n description:\n 'Send a user message to a chat (triggers AI inference). Use --stream to stream the response.',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'chat-id', aliases: ['id'], description: 'Chat ID', required: true },\n { name: 'stream', description: 'Stream the AI response via AG-UI', isFlag: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const content = typeof data === 'string' ? data : (data as any)?.content;\n if (!content)\n throw new Error(\n 'Message content is required (pass --data \\'\"your message\"\\' or --data \\'{\"content\":\"your message\"}\\')'\n );\n const chatId = requireNumberFrom(args, 'chat-id', 'id');\n\n if (args.stream) {\n // Stream via AG-UI protocol\n const aguiClient = new AGUIClient({\n baseUrl: ctx.envConfig.apiUrl,\n workspaceUuid: workspace,\n chatId,\n accessToken: requireAuth(ctx).accessToken,\n });\n process.stdout.write('\\x1B[32mAssistant:\\x1B[0m ');\n await aguiClient.sendMessage([{ role: 'user', content }], (event) => {\n const delta = getTextDelta(event);\n if (delta) process.stdout.write(delta);\n const errorMsg = getErrorMessage(event);\n if (errorMsg) process.stderr.write(`\\n\\x1B[31mError: ${errorMsg}\\x1B[0m\\n`);\n });\n process.stdout.write('\\n');\n } else {\n const result = await requireAuth(ctx).apiClient.sendChatMessage(\n workspace,\n chatId,\n content\n );\n outputSingle(result, ctx, MESSAGE_COLUMNS);\n }\n },\n },\n {\n path: ['chats', 'messages', 'send-as-assistant'],\n description: 'Send an assistant message to a chat (does not trigger AI inference)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'chat-id', aliases: ['id'], description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.sendAssistantMessage(\n workspace,\n requireNumberFrom(args, 'chat-id', 'id'),\n data as any\n );\n outputSingle(result, ctx, MESSAGE_COLUMNS);\n },\n },\n // Summarize\n {\n path: ['chats', 'summarize'],\n description: 'Summarize a chat',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.summarizeChat(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n // Export\n {\n path: ['chats', 'export'],\n description: 'Export a single chat',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.exportChat(\n workspace,\n requireNumber(args, 'id')\n );\n process.stdout.write(await result.text());\n },\n },\n {\n path: ['chats', 'export-all'],\n description: 'Export all chats',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.exportChats(workspace);\n process.stdout.write(await result.text());\n },\n },\n // Token usage\n {\n path: ['chats', 'token-usage'],\n description: 'Get token usage for a chat',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getChatTokenUsage(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n // Needs response\n {\n path: ['chats', 'needs-response'],\n description: 'List chats that need a response',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getChatsNeedsResponse(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n // Inspect (aggregated debug view)\n {\n path: ['chats', 'inspect'],\n description: 'Inspect a chat with messages, assignment state, and data records',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const chatId = requireNumber(args, 'id');\n const [chat, messages, ws] = await Promise.all([\n requireAuth(ctx).apiClient.getChat(workspace, chatId),\n requireAuth(ctx).apiClient.getChatMessages(workspace, chatId),\n requireAuth(ctx).apiClient.getWorkspace(workspace),\n ]);\n const isHipaa = ws.features?.includes('hipaa_compliance' as any);\n\n const truncate = (content: unknown) => {\n const text = typeof content === 'string' ? content : JSON.stringify(content);\n return text.slice(0, 200);\n };\n\n const result: Record<string, unknown> = {\n chat: {\n id: chat.id,\n title: chat.title,\n channel: chat.channel,\n chatType: chat.chatType,\n workflowId: chat.workflowId,\n assignmentId: chat.assignmentId,\n messageCount: chat.messageCount,\n createdAt: chat.createdAt,\n },\n messages: messages.map((m: any) => ({\n id: m.id,\n role: m.role,\n content: isHipaa ? '[REDACTED — HIPAA workspace]' : truncate(m.content),\n })),\n };\n\n // If assignment chat, fetch assignment with current task + data records\n const assignmentId = chat.assignmentId;\n if (assignmentId) {\n const assignment = await requireAuth(ctx).apiClient.getAssignment(\n workspace,\n assignmentId\n );\n result.assignment = {\n id: assignment.id,\n status: assignment.status,\n workflowId: assignment.workflowId,\n workflowName: assignment.workflowName,\n currentTask: assignment.currentTask,\n dataRecords: assignment.dataRecords?.map((dr: any) => ({\n id: dr.id,\n dataTypeId: dr.dataTypeId,\n fieldValues: isHipaa ? '[REDACTED — HIPAA workspace]' : dr.fieldValues,\n })),\n };\n }\n\n outputSingle(result, ctx);\n },\n },\n // Chat Labels CRUD\n ...crudCommands({\n prefix: ['chats', 'labels'],\n entityName: 'chat label',\n listMethod: 'getChatLabels',\n getMethod: 'getChatLabel',\n createMethod: 'createChatLabel',\n updateMethod: 'updateChatLabel',\n deleteMethod: 'deleteChatLabel',\n columns: LABEL_COLUMNS,\n }),\n // Chat Filters CRUD\n ...crudCommands({\n prefix: ['chats', 'filters'],\n entityName: 'chat filter',\n listMethod: 'getChatFilters',\n getMethod: 'getChatFilter',\n createMethod: 'createChatFilter',\n updateMethod: 'updateChatFilter',\n deleteMethod: 'deleteChatFilter',\n columns: FILTER_COLUMNS,\n }),\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { CLIError } from '../lib/errors';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n COL.name(),\n { header: 'ROLE', getValue: (item: any) => item.role ?? '' },\n COL.status(),\n COL.created(),\n];\n\nconst LABEL_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n COL.name(),\n { header: 'COLOR', getValue: (item: any) => item.color ?? '' },\n];\n\nconst FILTER_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.uuid(), COL.name()];\n\nconst FIELD_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'TYPE', getValue: (item: any) => item.field_type ?? '' },\n { header: 'REQUIRED', getValue: (item: any) => String(item.required ?? false) },\n];\n\nconst ROLE_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.uuid(), COL.name()];\n\nexport const membersDomain: DomainDef = {\n name: 'members',\n description: 'Manage members',\n commands: [\n ...crudCommands({\n prefix: ['members'],\n entityName: 'member',\n listMethod: 'getWorkspaceMembers',\n getMethod: 'getWorkspaceMember',\n createMethod: 'createWorkspaceMember',\n updateMethod: 'updateMember',\n deleteMethod: 'deleteMember',\n archiveMethod: 'archiveMember',\n unarchiveMethod: 'unarchiveMember',\n columns: COLUMNS,\n }),\n // Current member\n {\n path: ['members', 'me'],\n description: 'Get the current member',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getCurrentMember(workspace);\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Import/Export\n {\n path: ['members', 'import'],\n description: 'Import members from data',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await (requireAuth(ctx).apiClient as any).importMembers(workspace, data);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['members', 'export'],\n description: 'Export members',\n requiresWorkspace: true,\n args: [\n {\n name: 'fields',\n description:\n 'Comma-separated field names (default: id,name,email,phone,member_type,labels)',\n },\n {\n name: 'member-type',\n description: 'Filter by member type: member, test, anonymous',\n },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const defaultFields = ['id', 'name', 'email', 'phone', 'member_type', 'labels'];\n const fields = args.fields\n ? String(args.fields)\n .split(',')\n .map((f: string) => f.trim())\n : defaultFields;\n const memberType = args['member-type'] as 'member' | 'test' | 'anonymous' | undefined;\n const result = await (requireAuth(ctx).apiClient as any).exportMembers(\n workspace,\n fields,\n [],\n memberType\n );\n process.stdout.write(await result.text());\n },\n },\n // Member Labels CRUD\n ...crudCommands({\n prefix: ['members', 'labels'],\n entityName: 'member label',\n listMethod: 'getMemberLabels',\n getMethod: 'getMemberLabel',\n createMethod: 'createMemberLabel',\n updateMethod: 'updateMemberLabel',\n deleteMethod: 'deleteMemberLabel',\n columns: LABEL_COLUMNS,\n }),\n // Member Filters CRUD\n ...crudCommands({\n prefix: ['members', 'filters'],\n entityName: 'member filter',\n listMethod: 'getMemberFilters',\n getMethod: 'getMemberFilter',\n createMethod: 'createMemberFilter',\n updateMethod: 'updateMemberFilter',\n deleteMethod: 'deleteMemberFilter',\n columns: FILTER_COLUMNS,\n }),\n // Member Fields — nested resource requiring memberId\n {\n path: ['members', 'fields', 'list'],\n description: 'List fields for a member',\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const memberId = requireNumber(args, 'member-id');\n const result = await requireAuth(ctx).apiClient.getMemberFields(workspace, memberId);\n outputData(result, ctx, FIELD_COLUMNS);\n },\n },\n {\n path: ['members', 'fields', 'create'],\n description: 'Create a member field',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const memberId = requireNumber(args, 'member-id');\n const result = await requireAuth(ctx).apiClient.createMemberField(\n workspace,\n memberId,\n data as any\n );\n outputSingle(result, ctx, FIELD_COLUMNS);\n },\n },\n {\n path: ['members', 'fields', 'update'],\n description: 'Update a member field',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'id', description: 'Field ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const memberId = requireNumber(args, 'member-id');\n const fieldId = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.updateMemberField(\n workspace,\n memberId,\n fieldId,\n data as any\n );\n outputSingle(result, ctx, FIELD_COLUMNS);\n },\n },\n {\n path: ['members', 'fields', 'delete'],\n description: 'Delete a member field',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'id', description: 'Field ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const memberId = requireNumber(args, 'member-id');\n const fieldId = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.deleteMemberField(workspace, memberId, fieldId);\n process.stdout.write(`Deleted member field ${fieldId}\\n`);\n },\n },\n // Member Roles CRUD\n ...crudCommands({\n prefix: ['members', 'roles'],\n entityName: 'member role',\n listMethod: 'getMemberRoles',\n getMethod: 'getMemberRole',\n createMethod: 'createMemberRole',\n updateMethod: 'updateMemberRole',\n deleteMethod: 'deleteMemberRole',\n columns: ROLE_COLUMNS,\n }),\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n COL.name(),\n COL.status(),\n {\n header: 'WORKFLOW',\n getValue: (item: any) => item.workflow_name ?? String(item.workflow_id ?? ''),\n },\n COL.created(),\n];\n\nexport const tasksDomain: DomainDef = {\n name: 'tasks',\n description: 'Manage tasks',\n commands: [\n ...crudCommands({\n prefix: ['tasks'],\n entityName: 'task',\n listMethod: 'getTasks',\n getMethod: 'getTask',\n createMethod: 'createTask',\n updateMethod: 'updateTask',\n deleteMethod: 'deleteTask',\n archiveMethod: 'archiveTask',\n unarchiveMethod: 'unarchiveTask',\n columns: COLUMNS,\n }),\n {\n path: ['tasks', 'clone'],\n description: 'Clone a task',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Task ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.cloneTask(\n workspace,\n requireNumber(args, 'id'),\n (data as any)?.name ?? '',\n (data as any)?.slug\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['tasks', 'ability-types'],\n description: 'List available ability types',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getAbilityTypes(workspace);\n outputData(result, ctx);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { CLIError } from '../lib/errors';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n COL.name(),\n { header: 'TASKS', getValue: (item: any) => String(item.taskCount ?? '') },\n COL.created(),\n];\n\nconst NOTE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'TITLE', getValue: (item: any) => item.title ?? '' },\n {\n header: 'CONTENT',\n getValue: (item: any) => String(item.content ?? '').slice(0, 60),\n maxWidth: 60,\n },\n COL.created(),\n];\n\nconst CONTRIBUTOR_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n {\n header: 'ACCOUNT',\n getValue: (item: any) => item.account_name ?? String(item.account_id ?? ''),\n },\n { header: 'ROLE', getValue: (item: any) => item.role ?? '' },\n];\n\nconst TEMPLATE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n {\n header: 'DESCRIPTION',\n getValue: (item: any) => String(item.description ?? '').slice(0, 60),\n maxWidth: 60,\n },\n];\n\nexport const workflowsDomain: DomainDef = {\n name: 'workflows',\n description: 'Manage workflows',\n commands: [\n ...crudCommands({\n prefix: ['workflows'],\n entityName: 'workflow',\n listMethod: 'getWorkflows',\n getMethod: 'getWorkflow',\n createMethod: 'createWorkflow',\n updateMethod: 'updateWorkflow',\n deleteMethod: 'deleteWorkflow',\n supportsCascade: true,\n archiveMethod: 'archiveWorkflow',\n unarchiveMethod: 'unarchiveWorkflow',\n columns: COLUMNS,\n }),\n // Clone\n {\n path: ['workflows', 'clone'],\n description: 'Clone a workflow',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.cloneWorkflow(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Templates\n {\n path: ['workflows', 'templates'],\n description: 'List workflow templates',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getWorkflowTemplates(workspace);\n outputData(result, ctx, TEMPLATE_COLUMNS);\n },\n },\n {\n path: ['workflows', 'create-from-template'],\n description: 'Create a workflow from a template',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.createWorkflowFromTemplate(\n workspace,\n (data as any)?.templateUuid ?? '',\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Activity\n {\n path: ['workflows', 'activity'],\n description: 'Get workflow activity',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getWorkflowActivity(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n // Diagram\n {\n path: ['workflows', 'diagram'],\n description: 'Get workflow diagram',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getWorkflowDiagram(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n // Notes — nested resource requiring workflowId\n {\n path: ['workflows', 'notes', 'list'],\n description: 'List workflow notes',\n requiresWorkspace: true,\n args: [{ name: 'workflow-id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const workflowId = requireNumber(args, 'workflow-id');\n const result = await requireAuth(ctx).apiClient.getWorkflowNotes(workspace, workflowId);\n outputData(result, ctx, NOTE_COLUMNS);\n },\n },\n {\n path: ['workflows', 'notes', 'create'],\n description: 'Create a workflow note',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'workflow-id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const workflowId = requireNumber(args, 'workflow-id');\n const result = await requireAuth(ctx).apiClient.createWorkflowNote(\n workspace,\n workflowId,\n data as any\n );\n outputSingle(result, ctx, NOTE_COLUMNS);\n },\n },\n {\n path: ['workflows', 'notes', 'update'],\n description: 'Update a workflow note',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'workflow-id', description: 'Workflow ID', required: true },\n { name: 'id', description: 'Note ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const workflowId = requireNumber(args, 'workflow-id');\n const noteId = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.updateWorkflowNote(\n workspace,\n workflowId,\n noteId,\n data as any\n );\n outputSingle(result, ctx, NOTE_COLUMNS);\n },\n },\n {\n path: ['workflows', 'notes', 'delete'],\n description: 'Delete a workflow note',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'workflow-id', description: 'Workflow ID', required: true },\n { name: 'id', description: 'Note ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const workflowId = requireNumber(args, 'workflow-id');\n const noteId = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.deleteWorkflowNote(workspace, workflowId, noteId);\n process.stdout.write(`Deleted workflow note ${noteId}\\n`);\n },\n },\n // Contributors — nested resource requiring workflowId\n {\n path: ['workflows', 'contributors', 'list'],\n description: 'List workflow contributors',\n requiresWorkspace: true,\n args: [{ name: 'workflow-id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const workflowId = requireNumber(args, 'workflow-id');\n const result = await requireAuth(ctx).apiClient.getWorkflowContributors(\n workspace,\n workflowId\n );\n outputData(result, ctx, CONTRIBUTOR_COLUMNS);\n },\n },\n {\n path: ['workflows', 'contributors', 'create'],\n description: 'Add a workflow contributor',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'workflow-id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const workflowId = requireNumber(args, 'workflow-id');\n const result = await requireAuth(ctx).apiClient.createWorkflowContributor(\n workspace,\n workflowId,\n data as any\n );\n outputSingle(result, ctx, CONTRIBUTOR_COLUMNS);\n },\n },\n {\n path: ['workflows', 'contributors', 'update'],\n description: 'Update a workflow contributor',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'workflow-id', description: 'Workflow ID', required: true },\n { name: 'id', description: 'Contributor ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const workflowId = requireNumber(args, 'workflow-id');\n const contributorId = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.updateWorkflowContributor(\n workspace,\n workflowId,\n contributorId,\n data as any\n );\n outputSingle(result, ctx, CONTRIBUTOR_COLUMNS);\n },\n },\n {\n path: ['workflows', 'contributors', 'delete'],\n description: 'Remove a workflow contributor',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'workflow-id', description: 'Workflow ID', required: true },\n { name: 'id', description: 'Contributor ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const workflowId = requireNumber(args, 'workflow-id');\n const contributorId = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.deleteWorkflowContributor(\n workspace,\n workflowId,\n contributorId\n );\n process.stdout.write(`Deleted workflow contributor ${contributorId}\\n`);\n },\n },\n ],\n};\n","import { type DomainDef, requireString, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst WORKFLOW_UUID_ARG = {\n name: 'workflow-uuid',\n description: 'Workflow UUID',\n required: true,\n} as const;\n\nconst VERSION_ARG = {\n name: 'version',\n description: 'Version number',\n required: true,\n} as const;\n\nconst COLUMNS: TableColumn<unknown>[] = [\n { header: 'VERSION', getValue: (item: any) => String(item.versionNumber ?? '') },\n COL.uuid(),\n COL.name(),\n {\n header: 'ACTIVE',\n getValue: (item: any) => (item.isActive ? 'yes' : 'no'),\n },\n {\n header: 'SOURCE',\n getValue: (item: any) => item.sourceType ?? '',\n },\n {\n header: 'PUBLISHED',\n getValue: (item: any) => item.publishedAt ?? '',\n },\n {\n header: 'SUMMARY',\n getValue: (item: any) => (item.changeSummary ?? '').slice(0, 50),\n maxWidth: 50,\n },\n];\n\nexport const workflowVersionsDomain: DomainDef = {\n name: 'workflow-versions',\n description: 'Manage workflow versions (publish, activate, inspect snapshots)',\n commands: [\n // List versions\n {\n path: ['workflow-versions', 'list'],\n description: 'List all published versions of a workflow',\n requiresWorkspace: true,\n args: [WORKFLOW_UUID_ARG],\n handler: async ({ ctx, workspace, args }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const result = await requireAuth(ctx).apiClient.getWorkflowVersions(\n workspace,\n workflowUuid\n );\n process.stderr.write(`Next version number: ${result.nextVersionNumber}\\n`);\n outputData(result.versions, ctx, COLUMNS);\n },\n },\n // Get specific version\n {\n path: ['workflow-versions', 'get'],\n description: 'Get a specific version by number (includes full snapshot)',\n requiresWorkspace: true,\n args: [WORKFLOW_UUID_ARG, VERSION_ARG],\n handler: async ({ ctx, workspace, args }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const versionNumber = requireNumber(args, 'version');\n const result = await requireAuth(ctx).apiClient.getWorkflowVersion(\n workspace,\n workflowUuid,\n versionNumber\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Get active version\n {\n path: ['workflow-versions', 'active'],\n description: 'Get the currently active version of a workflow',\n requiresWorkspace: true,\n args: [WORKFLOW_UUID_ARG],\n handler: async ({ ctx, workspace, args }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const result = await requireAuth(ctx).apiClient.getWorkflowVersionActive(\n workspace,\n workflowUuid\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Publish\n {\n path: ['workflow-versions', 'publish'],\n description: 'Publish the live workflow as a new immutable version',\n mutates: true,\n requiresWorkspace: true,\n args: [\n WORKFLOW_UUID_ARG,\n {\n name: 'name',\n description: 'Human-readable version name',\n required: false,\n },\n {\n name: 'summary',\n description: 'Change summary',\n required: false,\n },\n {\n name: 'no-activate',\n description: 'Publish without activating',\n isFlag: true,\n required: false,\n },\n ],\n examples: [\n 'workflow-versions publish --workflow-uuid $UUID',\n 'workflow-versions publish --workflow-uuid $UUID --name \"v2 Release\" --summary \"Added triage step\"',\n 'workflow-versions publish --workflow-uuid $UUID --no-activate',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const body = (data as Record<string, unknown>) ?? {};\n // CLI flags override JSON data\n if (args.name) body.name = args.name;\n if (args.summary) body.changeSummary = args.summary;\n if (args['no-activate']) body.activate = false;\n const result = await requireAuth(ctx).apiClient.publishWorkflowVersion(\n workspace,\n workflowUuid,\n body\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Activate\n {\n path: ['workflow-versions', 'activate'],\n description: 'Activate a version so it receives new assignments',\n mutates: true,\n requiresWorkspace: true,\n args: [WORKFLOW_UUID_ARG, VERSION_ARG],\n handler: async ({ ctx, workspace, args }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const versionNumber = requireNumber(args, 'version');\n const result = await requireAuth(ctx).apiClient.activateWorkflowVersion(\n workspace,\n workflowUuid,\n versionNumber\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Deactivate\n {\n path: ['workflow-versions', 'deactivate'],\n description: 'Deactivate a version so it no longer receives new assignments',\n mutates: true,\n requiresWorkspace: true,\n args: [WORKFLOW_UUID_ARG, VERSION_ARG],\n handler: async ({ ctx, workspace, args }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const versionNumber = requireNumber(args, 'version');\n const result = await requireAuth(ctx).apiClient.deactivateWorkflowVersion(\n workspace,\n workflowUuid,\n versionNumber\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Diff (compare two versions, 0 = draft)\n {\n path: ['workflow-versions', 'diff'],\n description: 'Compare two versions (use 0 for draft)',\n requiresWorkspace: true,\n args: [\n WORKFLOW_UUID_ARG,\n { name: 'from', description: 'Base version number (0 = draft)', required: true },\n { name: 'to', description: 'Target version number (0 = draft)', required: true },\n ],\n examples: [\n 'workflow-versions diff --workflow-uuid $UUID --from 1 --to 2',\n 'workflow-versions diff --workflow-uuid $UUID --from 1 --to 0 # compare v1 to draft',\n ],\n handler: async ({ ctx, workspace, args }) => {\n const workflowUuid = requireString(args, 'workflow-uuid');\n const from = requireNumber(args, 'from');\n const to = requireNumber(args, 'to');\n const diff = await requireAuth(ctx).apiClient.diffWorkflowVersions(\n workspace,\n workflowUuid,\n from,\n to\n );\n\n if (ctx.outputFormat === 'json') {\n process.stdout.write(JSON.stringify(diff, null, 2) + '\\n');\n return;\n }\n\n // Human-readable output\n process.stdout.write(\n `\\nComparing ${diff.fromVersion.label} → ${diff.toVersion.label}\\n`\n );\n process.stdout.write(\n `Changes: +${diff.summary.added} −${diff.summary.removed} ~${diff.summary.modified}\\n\\n`\n );\n\n if (diff.changes.length === 0) {\n process.stdout.write('No differences.\\n');\n return;\n }\n\n let currentCategory = '';\n for (const change of diff.changes) {\n if (change.category !== currentCategory) {\n currentCategory = change.category;\n process.stdout.write(`[${currentCategory}]\\n`);\n }\n const prefix =\n change.changeType === 'added'\n ? ' + '\n : change.changeType === 'removed'\n ? ' − '\n : ' ~ ';\n const fieldSummary =\n change.fields && change.fields.length > 0\n ? ` (${change.fields.map((f: any) => f.field).join(', ')})`\n : '';\n process.stdout.write(`${prefix}${change.label}${fieldSummary}\\n`);\n\n // Show text-level diffs for fields with old/new values\n if (change.fields) {\n for (const field of change.fields) {\n if (field.oldValue != null || field.newValue != null) {\n process.stdout.write(` ${field.field}:\\n`);\n if (field.oldValue != null) {\n process.stdout.write(` - ${field.oldValue}\\n`);\n }\n if (field.newValue != null) {\n process.stdout.write(` + ${field.newValue}\\n`);\n }\n }\n }\n }\n }\n process.stdout.write('\\n');\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { CLIError } from '../lib/errors';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { listResult } from '../lib/pagination';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.uuid(),\n COL.name(),\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.status(),\n COL.created(),\n];\n\nconst PRODUCT_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.uuid(), COL.name(), COL.status()];\n\nconst INVITATION_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'EMAIL', getValue: (item: any) => item.email ?? '' },\n COL.status(),\n COL.created(),\n];\n\nconst NOTIFICATION_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'TYPE', getValue: (item: any) => item.type ?? '' },\n { header: 'READ', getValue: (item: any) => String(item.read ?? false) },\n COL.created(),\n];\n\nconst FEATURE_COLUMNS: TableColumn<unknown>[] = [\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.name(),\n { header: 'CATEGORY', getValue: (item: any) => item.category ?? '' },\n];\n\nconst SCOPE_COLUMNS: TableColumn<unknown>[] = [\n COL.name(),\n { header: 'CATEGORY', getValue: (item: any) => item.category ?? '' },\n COL.description(),\n];\n\nconst THEME_COLUMNS: TableColumn<unknown>[] = [\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.name(),\n COL.description(),\n];\n\nconst DM_COLUMNS: TableColumn<unknown>[] = [\n { header: 'ID', getValue: (item: any) => String(item.id ?? '') },\n {\n header: 'PARTICIPANTS',\n getValue: (item: any) => (item.participants ?? []).map((p: any) => p.name).join(', '),\n maxWidth: 40,\n },\n {\n header: 'SUMMARY',\n getValue: (item: any) => String(item.summary ?? '').slice(0, 60),\n maxWidth: 60,\n },\n { header: 'UPDATED', getValue: (item: any) => item.updatedAt ?? '' },\n];\n\nconst MESSAGE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'ROLE', getValue: (item: any) => item.role ?? '' },\n {\n header: 'CONTENT',\n getValue: (item: any) => String(item.content ?? '').slice(0, 80),\n maxWidth: 80,\n },\n COL.created(),\n];\n\nexport const workspacesDomain: DomainDef = {\n name: 'workspaces',\n description: 'Manage workspaces',\n commands: [\n // List workspaces (no workspace required)\n ...crudCommands({\n prefix: ['workspaces'],\n entityName: 'workspace',\n listMethod: 'getWorkspaces',\n // getMethod omitted — custom get below accepts -w as the identifier\n updateMethod: 'updateWorkspace',\n deleteMethod: 'deleteWorkspace',\n columns: COLUMNS,\n requiresWorkspace: false,\n }),\n // Custom get that accepts either --id or -w as the workspace identifier\n {\n path: ['workspaces', 'get'],\n description: 'Get a workspace by UUID (via --id or -w)',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Workspace UUID (or use -w)' }],\n handler: async ({ ctx, workspace, args }) => {\n const id = (args.id ?? args.uuid ?? workspace) as string | undefined;\n if (!id) throw new CLIError('Provide workspace UUID via --id or -w');\n const result = await requireAuth(ctx).apiClient.getWorkspace(id);\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Create a workspace via the public endpoint\n {\n path: ['workspaces', 'create'],\n description: 'Create a workspace',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const payload = data as Record<string, unknown>;\n if (!payload.organizationId) {\n throw new CLIError(\n 'organizationId is required in --data (e.g. --data \\'{\"organizationId\": 1, \"name\": \"My Workspace\"}\\')'\n );\n }\n const result = await requireAuth(ctx).apiClient.createWorkspace(payload as any);\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Defaults\n {\n path: ['workspaces', 'defaults'],\n description: 'Get workspace defaults',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getWorkspaceDefaults(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['workspaces', 'update-defaults'],\n description: 'Update workspace defaults',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.updateWorkspaceDefaults(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n // Counts\n {\n path: ['workspaces', 'counts'],\n description: 'Get workspace entity counts',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getWorkspaceCounts(workspace);\n outputSingle(result, ctx);\n },\n },\n // Export/Import\n {\n path: ['workspaces', 'export'],\n description: 'Export workspace configuration',\n requiresWorkspace: true,\n args: [\n {\n name: 'scope',\n description: 'Export scope: \"workflows\" for workflow-only export',\n },\n {\n name: 'workflow-id',\n description: 'Export a single workflow by ID',\n },\n {\n name: 'exclude',\n description: 'Comma-separated categories to exclude (e.g. \"channels\")',\n },\n ],\n examples: [\n 'yarn gr workspaces export -w $UUID --env prod',\n 'yarn gr workspaces export -w $UUID --env prod --scope workflows',\n 'yarn gr workspaces export -w $UUID --env prod --workflow-id 42',\n 'yarn gr workspaces export -w $UUID --env prod --exclude channels',\n ],\n handler: async ({ ctx, workspace, args }) => {\n const scope = args['scope'] as string | undefined;\n const workflowIdStr = args['workflow-id'] as string | undefined;\n const exclude = args['exclude'] as string | undefined;\n const workflowId = workflowIdStr ? Number(workflowIdStr) : undefined;\n if (workflowId !== undefined && isNaN(workflowId)) {\n throw new CLIError('--workflow-id must be a number');\n }\n if (scope && workflowId !== undefined) {\n throw new CLIError('Cannot specify both --scope and --workflow-id');\n }\n if (scope && scope !== 'workflows') {\n throw new CLIError('--scope must be \"workflows\"');\n }\n const result = await requireAuth(ctx).apiClient.exportWorkspace(\n workspace,\n workflowId,\n scope as 'workflows' | undefined,\n exclude\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['workspaces', 'import'],\n description: 'Import workspace configuration',\n mutates: true,\n requiresWorkspace: true,\n args: [\n {\n name: 'create-all',\n description:\n 'Auto-generate createNew entries for all entities in the export data. Use when importing into a fresh workspace.',\n isFlag: true,\n },\n ],\n examples: [\n 'yarn gr workspaces import -w $UUID --env dev --file export.json --create-all',\n 'yarn gr workspaces import -w $UUID --env dev --data \\'{\"exportData\": ..., \"createNew\": ..., \"importMappings\": {}}\\'',\n ],\n handler: async ({ ctx, workspace, data, args }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const payload = data as Record<string, unknown>;\n const createAll = args['create-all'] === true;\n\n // Detect if input is a full import payload or raw export data\n let exportData: Record<string, unknown>;\n let importMappings: Record<string, Record<string, string>>;\n let createNew: Record<string, string[]>;\n\n if (payload.exportData && typeof payload.exportData === 'object') {\n // Full import payload: {exportData, importMappings?, createNew?}\n exportData = payload.exportData as Record<string, unknown>;\n importMappings =\n (payload.importMappings as Record<string, Record<string, string>>) ?? {};\n createNew = (payload.createNew as Record<string, string[]>) ?? {};\n } else if (payload.version && payload.workflows) {\n // Raw export data (has version + entity arrays at top level)\n exportData = payload;\n importMappings = {};\n createNew = {};\n } else {\n throw new CLIError(\n 'Unrecognized data format. Provide either raw export data (from \"workspaces export\") or a full import payload with {exportData, importMappings, createNew}.'\n );\n }\n\n if (createAll) {\n // Auto-generate createNew from all UUIDs in the export data.\n // Entity keys that contain arrays of objects with uuid fields.\n const entityKeys = [\n 'workflows',\n 'tasks',\n 'dataTypes',\n 'agents',\n 'memberLabels',\n 'files',\n 'eventRules',\n 'memberRoles',\n 'phoneNumbers',\n 'sites',\n 'inboxes',\n 'routines',\n 'memberFilters',\n 'memberFilterRules',\n 'milestones',\n 'milestoneGoals',\n 'customToolkits',\n 'customTools',\n 'pages',\n 'menuItems',\n 'mcpServers',\n 'fileFolders',\n 'fileLabels',\n 'workflowNotes',\n 'abilities',\n 'qualifications',\n 'chatLabels',\n 'chatFilters',\n 'chatFilterRules',\n 'calendars',\n 'calendarEventTypes',\n 'calendarSchedules',\n 'journeys',\n ];\n for (const key of entityKeys) {\n const entities = exportData[key];\n if (Array.isArray(entities)) {\n createNew[key] = entities\n .map((e: Record<string, unknown>) => e.uuid as string)\n .filter(Boolean);\n }\n }\n }\n\n const result = await requireAuth(ctx).apiClient.importWorkspace(\n workspace,\n exportData as any,\n importMappings as any,\n createNew as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['workspaces', 'preview-import'],\n description: 'Preview workspace import',\n requiresWorkspace: true,\n args: [\n {\n name: 'create-all',\n description: 'Auto-generate createNew entries for all entities in the export data',\n isFlag: true,\n },\n ],\n handler: async ({ ctx, workspace, data, args }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const payload = data as Record<string, unknown>;\n const createAll = args['create-all'] === true;\n\n let exportData: Record<string, unknown>;\n let importMappings: Record<string, Record<string, string>>;\n let createNew: Record<string, string[]>;\n\n if (payload.exportData && typeof payload.exportData === 'object') {\n exportData = payload.exportData as Record<string, unknown>;\n importMappings =\n (payload.importMappings as Record<string, Record<string, string>>) ?? {};\n createNew = (payload.createNew as Record<string, string[]>) ?? {};\n } else if (payload.version && payload.workflows) {\n exportData = payload;\n importMappings = {};\n createNew = {};\n } else {\n throw new CLIError(\n 'Unrecognized data format. Provide either raw export data (from \"workspaces export\") or a full import payload with {exportData, importMappings, createNew}.'\n );\n }\n\n if (createAll) {\n const entityKeys = [\n 'workflows',\n 'tasks',\n 'dataTypes',\n 'agents',\n 'memberLabels',\n 'files',\n 'eventRules',\n 'memberRoles',\n 'phoneNumbers',\n 'sites',\n 'inboxes',\n 'routines',\n 'memberFilters',\n 'memberFilterRules',\n 'milestones',\n 'milestoneGoals',\n 'customToolkits',\n 'customTools',\n 'pages',\n 'menuItems',\n 'mcpServers',\n 'fileFolders',\n 'fileLabels',\n 'workflowNotes',\n 'abilities',\n 'qualifications',\n 'chatLabels',\n 'chatFilters',\n 'chatFilterRules',\n 'calendars',\n 'calendarEventTypes',\n 'calendarSchedules',\n 'journeys',\n ];\n for (const key of entityKeys) {\n const entities = exportData[key];\n if (Array.isArray(entities)) {\n createNew[key] = entities\n .map((e: Record<string, unknown>) => e.uuid as string)\n .filter(Boolean);\n }\n }\n }\n\n const result = await requireAuth(ctx).apiClient.previewImportWorkspace(\n workspace,\n exportData as any,\n importMappings as any,\n createNew as any\n );\n outputSingle(result, ctx);\n },\n },\n // Features\n {\n path: ['workspaces', 'features'],\n description: 'List available workspace features',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getAvailableWorkspaceFeatures();\n outputData(listResult(result, false), ctx, FEATURE_COLUMNS);\n },\n },\n // Scopes\n {\n path: ['workspaces', 'scopes'],\n description: 'List workspace scopes',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getWorkspaceScopes();\n outputData(listResult(result, false), ctx, SCOPE_COLUMNS);\n },\n },\n // Products — getProduct is a global endpoint (no workspace param), so use a custom get handler\n ...crudCommands({\n prefix: ['workspaces', 'products'],\n entityName: 'product',\n listMethod: 'getProducts',\n // getMethod omitted — custom get below handles the global endpoint\n createMethod: 'createProduct',\n updateMethod: 'updateProduct',\n deleteMethod: 'deleteProduct',\n columns: PRODUCT_COLUMNS,\n }),\n {\n path: ['workspaces', 'products', 'get'],\n description: 'Get a product by ID',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Product ID', required: true }],\n handler: async ({ ctx, args }) => {\n const id = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.getProduct(id);\n outputSingle(result, ctx, PRODUCT_COLUMNS);\n },\n },\n // Invitations — workspace-scoped admin methods\n {\n path: ['workspaces', 'invitations', 'list'],\n description: 'List workspace invitations',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result =\n await requireAuth(ctx).apiClient.listWorkspaceInvitationsAdmin(workspace);\n outputData(listResult(result, false), ctx, INVITATION_COLUMNS);\n },\n },\n {\n path: ['workspaces', 'invitations', 'delete'],\n description: 'Delete a workspace invitation',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Invitation ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const invitationId = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.deleteWorkspaceInvitationAdmin(\n workspace,\n invitationId\n );\n process.stdout.write(`Deleted invitation ${invitationId}\\n`);\n },\n },\n {\n path: ['workspaces', 'invitations', 'invite'],\n description: 'Invite a user to the workspace',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const payload = data as Record<string, unknown> | undefined;\n if (!payload) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const emailOrAccountId = (payload.email ?? payload.accountId) as string | number;\n if (!emailOrAccountId) {\n throw new CLIError('--data must include \"email\" or \"accountId\"');\n }\n const result = await requireAuth(ctx).apiClient.inviteToWorkspace(\n workspace,\n emailOrAccountId,\n payload.message as string | undefined,\n payload.memberRoleId !== undefined ? Number(payload.memberRoleId) : undefined,\n payload.name as string | undefined\n );\n outputSingle(result, ctx, INVITATION_COLUMNS);\n },\n },\n {\n path: ['workspaces', 'invitations', 'approve'],\n description: 'Approve a workspace invitation',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Invitation ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const invitationId = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.approveWorkspaceInvitation(\n workspace,\n invitationId\n );\n outputSingle(result, ctx, INVITATION_COLUMNS);\n },\n },\n {\n path: ['workspaces', 'invitations', 'deny'],\n description: 'Deny a workspace invitation',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Invitation ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const invitationId = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.denyWorkspaceInvitation(\n workspace,\n invitationId\n );\n outputSingle(result, ctx, INVITATION_COLUMNS);\n },\n },\n // Notifications\n ...crudCommands({\n prefix: ['workspaces', 'notifications'],\n entityName: 'notification',\n listMethod: 'getNotifications',\n getMethod: 'getNotification',\n columns: NOTIFICATION_COLUMNS,\n paginationSupport: 'full',\n }),\n {\n path: ['workspaces', 'notifications', 'mark-read'],\n description: 'Mark a notification as read',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Notification ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.markNotificationAsRead(\n workspace,\n requireNumber(args, 'id')\n );\n process.stdout.write(`Marked notification ${args.id} as read\\n`);\n },\n },\n {\n path: ['workspaces', 'notifications', 'dismiss-all'],\n description: 'Dismiss all notifications',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n await requireAuth(ctx).apiClient.dismissAllNotifications(workspace);\n process.stdout.write('Dismissed all notifications\\n');\n },\n },\n // Themes\n {\n path: ['workspaces', 'themes', 'list'],\n description: 'List workspace themes',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getWorkspaceThemes(workspace);\n outputData(listResult(result, false), ctx, THEME_COLUMNS);\n },\n },\n {\n path: ['workspaces', 'themes', 'update'],\n description: 'Update workspace themes',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.updateWorkspaceThemes(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n // Direct Messages (via chats API with chatType=dm)\n {\n path: ['workspaces', 'dms', 'list'],\n description: 'List direct message chats',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getChats(workspace, {\n chatType: 'member',\n mine: true,\n sortBy: 'updatedAt',\n sortOrder: 'desc',\n });\n outputData(listResult(result, false), ctx, DM_COLUMNS);\n },\n },\n {\n path: ['workspaces', 'dms', 'get'],\n description: 'Get messages for a DM chat',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getChatMessages(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(listResult(result, false), ctx, MESSAGE_COLUMNS);\n },\n },\n {\n path: ['workspaces', 'dms', 'send'],\n description: 'Send a message in a DM chat',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Chat ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const chatId = requireNumber(args, 'id');\n const content = (data as any)?.content ?? '';\n const result = await requireAuth(ctx).apiClient.sendChatMessage(\n workspace,\n chatId,\n content\n );\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.status(),\n { header: 'MEMBER', getValue: (item: any) => String(item.member_id ?? '') },\n { header: 'TASK', getValue: (item: any) => String(item.current_assignment_task_id ?? '') },\n { header: 'WF_VERSION', getValue: (item: any) => String(item.workflowVersionNumber ?? '') },\n COL.created(),\n];\n\nconst MESSAGE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'ROLE', getValue: (item: any) => item.role ?? '' },\n { header: 'CONTENT', getValue: (item: any) => (item.content ?? '').slice(0, 80) },\n COL.created(),\n];\n\nconst TASK_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.name(), COL.status()];\n\nconst TOOL_COLUMNS: TableColumn<unknown>[] = [\n COL.name(),\n { header: 'DESCRIPTION', getValue: (item: any) => (item.description ?? '').slice(0, 60) },\n];\n\nexport const assignmentsDomain: DomainDef = {\n name: 'assignments',\n description: 'Manage assignments',\n commands: [\n ...crudCommands({\n prefix: ['assignments'],\n entityName: 'assignment',\n listMethod: 'getAssignments',\n getMethod: 'getAssignment',\n createMethod: 'createAssignment',\n updateMethod: 'updateAssignment',\n deleteMethod: 'deleteAssignment',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n {\n path: ['assignments', 'cancel'],\n description: 'Cancel an assignment',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Assignment ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const body = (data as any) ?? {};\n const result = await requireAuth(ctx).apiClient.cancelAssignment(\n workspace,\n requireNumber(args, 'id'),\n body\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['assignments', 'messages', 'list'],\n description: 'List messages for an assignment',\n requiresWorkspace: true,\n args: [{ name: 'assignment-id', description: 'Assignment ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getAssignmentMessages(\n workspace,\n requireNumber(args, 'assignment-id')\n );\n outputData(result, ctx, MESSAGE_COLUMNS);\n },\n },\n {\n path: ['assignments', 'tasks', 'get'],\n description: 'Get an assignment task',\n requiresWorkspace: true,\n args: [\n { name: 'assignment-id', description: 'Assignment ID', required: true },\n { name: 'id', description: 'Assignment task ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getAssignmentTask(\n workspace,\n requireNumber(args, 'assignment-id'),\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, TASK_COLUMNS);\n },\n },\n {\n path: ['assignments', 'tasks', 'detail'],\n description: 'Get current task detail for an assignment',\n requiresWorkspace: true,\n args: [{ name: 'assignment-id', description: 'Assignment ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getAssignmentTaskDetail(\n workspace,\n requireNumber(args, 'assignment-id')\n );\n outputSingle(result, ctx, TASK_COLUMNS);\n },\n },\n {\n path: ['assignments', 'tasks', 'select'],\n description: 'Select current assignment task',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'assignment-id', description: 'Assignment ID', required: true },\n { name: 'id', description: 'Assignment task ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.selectCurrentAssignmentTask(\n workspace,\n requireNumber(args, 'assignment-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write(`Selected assignment task ${args.id}\\n`);\n },\n },\n {\n path: ['assignments', 'tools', 'list'],\n description: 'List tools for an assignment',\n requiresWorkspace: true,\n args: [{ name: 'assignment-id', description: 'Assignment ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getAssignmentTools(\n workspace,\n requireNumber(args, 'assignment-id')\n );\n const tools = result.tools ?? result;\n outputData(Array.isArray(tools) ? tools : [tools], ctx, TOOL_COLUMNS);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'TIMEZONE', getValue: (item: any) => item.timezone ?? '' },\n];\n\nconst SCHEDULE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'CALENDAR', getValue: (item: any) => String(item.calendar_id ?? '') },\n];\n\nconst EVENT_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'TITLE', getValue: (item: any) => item.title ?? item.name ?? '' },\n { header: 'START', getValue: (item: any) => item.start_time ?? item.start ?? '' },\n { header: 'END', getValue: (item: any) => item.end_time ?? item.end ?? '' },\n COL.status(),\n];\n\nconst EVENT_TYPE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'DURATION', getValue: (item: any) => String(item.duration ?? '') },\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n];\n\nexport const calendarsDomain: DomainDef = {\n name: 'calendars',\n description: 'Manage calendars, schedules, events, and event types',\n commands: [\n ...crudCommands({\n prefix: ['calendars'],\n entityName: 'calendar',\n listMethod: 'getCalendars',\n getMethod: 'getCalendar',\n createMethod: 'createCalendar',\n updateMethod: 'updateCalendar',\n deleteMethod: 'deleteCalendar',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n // Schedules sub-resource\n {\n path: ['calendars', 'schedules', 'list'],\n description: 'List schedules for a calendar',\n requiresWorkspace: true,\n args: [{ name: 'calendar-id', description: 'Calendar ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getCalendarSchedules(\n workspace,\n requireNumber(args, 'calendar-id')\n );\n outputData(result, ctx, SCHEDULE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'schedules', 'create'],\n description: 'Create a schedule',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'calendar-id', description: 'Calendar ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.createCalendarSchedule(\n workspace,\n requireNumber(args, 'calendar-id'),\n data as any\n );\n outputSingle(result, ctx, SCHEDULE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'schedules', 'update'],\n description: 'Update a schedule',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'calendar-id', description: 'Calendar ID', required: true },\n { name: 'id', description: 'Schedule ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateCalendarSchedule(\n workspace,\n requireNumber(args, 'calendar-id'),\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, SCHEDULE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'schedules', 'delete'],\n description: 'Delete a schedule',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'calendar-id', description: 'Calendar ID', required: true },\n { name: 'id', description: 'Schedule ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deleteCalendarSchedule(\n workspace,\n requireNumber(args, 'calendar-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write(`Deleted schedule ${args.id}\\n`);\n },\n },\n // Events sub-resource\n {\n path: ['calendars', 'events', 'list'],\n description: 'List calendar events (optionally filter by calendar)',\n requiresWorkspace: true,\n args: [{ name: 'calendar-id', description: 'Calendar ID (optional filter)' }],\n handler: async ({ ctx, workspace, args }) => {\n const calendarId = args['calendar-id'] ? requireNumber(args, 'calendar-id') : undefined;\n const result = await requireAuth(ctx).apiClient.getCalendarEvents(workspace, {\n ...(calendarId ? { calendarId } : {}),\n });\n outputData(result, ctx, EVENT_COLUMNS);\n },\n },\n {\n path: ['calendars', 'events', 'get'],\n description: 'Get a calendar event',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getCalendarEvent(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, EVENT_COLUMNS);\n },\n },\n {\n path: ['calendars', 'events', 'create'],\n description: 'Create a calendar event',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.createCalendarEvent(\n workspace,\n data as any\n );\n outputSingle(result, ctx, EVENT_COLUMNS);\n },\n },\n {\n path: ['calendars', 'events', 'update'],\n description: 'Update a calendar event',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateCalendarEvent(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, EVENT_COLUMNS);\n },\n },\n {\n path: ['calendars', 'events', 'cancel'],\n description: 'Cancel a calendar event',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.cancelCalendarEvent(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, EVENT_COLUMNS);\n },\n },\n {\n path: ['calendars', 'events', 'delete'],\n description: 'Delete a calendar event',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deleteCalendarEvent(\n workspace,\n requireNumber(args, 'id')\n );\n process.stdout.write(`Deleted calendar event ${args.id}\\n`);\n },\n },\n // Event types sub-resource\n {\n path: ['calendars', 'event-types', 'list'],\n description: 'List calendar event types',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getCalendarEventTypes(workspace);\n outputData(result, ctx, EVENT_TYPE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'event-types', 'get'],\n description: 'Get a calendar event type',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event type ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getCalendarEventType(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, EVENT_TYPE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'event-types', 'create'],\n description: 'Create a calendar event type',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.createCalendarEventType(\n workspace,\n data as any\n );\n outputSingle(result, ctx, EVENT_TYPE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'event-types', 'update'],\n description: 'Update a calendar event type',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event type ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateCalendarEventType(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, EVENT_TYPE_COLUMNS);\n },\n },\n {\n path: ['calendars', 'event-types', 'delete'],\n description: 'Delete a calendar event type',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event type ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deleteCalendarEventType(\n workspace,\n requireNumber(args, 'id')\n );\n process.stdout.write(`Deleted event type ${args.id}\\n`);\n },\n },\n ],\n};\n","import { type DomainDef, requireString, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { fetchAllPages, parsePaginationArgs, listResult } from '../lib/pagination';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.status(),\n];\n\nconst RECORD_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'DATA TYPE', getValue: (item: any) => String(item.data_type_id ?? '') },\n { header: 'MEMBER', getValue: (item: any) => String(item.member_id ?? '') },\n COL.updated(),\n];\n\nexport const dataTypesDomain: DomainDef = {\n name: 'data-types',\n description: 'Manage data types and records',\n commands: [\n ...crudCommands({\n prefix: ['data-types'],\n entityName: 'data type',\n listMethod: 'getDataTypes',\n getMethod: 'getDataType',\n createMethod: 'createDataType',\n updateMethod: 'updateDataType',\n deleteMethod: 'deleteDataType',\n archiveMethod: 'archiveDataType',\n unarchiveMethod: 'unarchiveDataType',\n columns: COLUMNS,\n }),\n {\n path: ['data-types', 'clone'],\n description: 'Clone a data type',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Data type ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.cloneDataType(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['data-types', 'get-by-slug'],\n description: 'Get a data type by slug',\n requiresWorkspace: true,\n args: [{ name: 'slug', description: 'Data type slug', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getDataTypeBySlug(\n workspace,\n requireString(args, 'slug')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Data Records sub-resource\n {\n path: ['data-types', 'records', 'list'],\n description: 'List records for a data type',\n requiresWorkspace: true,\n args: [\n { name: 'data-type-id', description: 'Data type ID', required: true },\n { name: 'page', description: 'Page number (default: 1)' },\n { name: 'page-size', description: 'Page size (default: 10)' },\n { name: 'all', description: 'Fetch all pages', isFlag: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const dataTypeId = requireNumber(args, 'data-type-id');\n const pag = parsePaginationArgs(args);\n\n if (pag.all) {\n const allItems = await fetchAllPages(({ page, pageSize }) =>\n requireAuth(ctx).apiClient.getDataRecords(workspace, dataTypeId, {\n page,\n pageSize,\n })\n );\n outputData(allItems, ctx, RECORD_COLUMNS);\n } else {\n const options: { page?: number; pageSize?: number } = {};\n if (pag.page) options.page = pag.page;\n if (pag.pageSize) options.pageSize = pag.pageSize;\n const result = await requireAuth(ctx).apiClient.getDataRecords(\n workspace,\n dataTypeId,\n options\n );\n // Explicit contract: supportsAll=true because this command HAS --all\n outputData(listResult(result, true), ctx, RECORD_COLUMNS);\n }\n },\n },\n {\n path: ['data-types', 'records', 'get'],\n description: 'Get a data record',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Record ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getDataRecord(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, RECORD_COLUMNS);\n },\n },\n {\n path: ['data-types', 'records', 'create'],\n description: 'Create a data record',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'data-type-id', description: 'Data type ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.createDataRecord(\n workspace,\n requireNumber(args, 'data-type-id'),\n data as any\n );\n outputSingle(result, ctx, RECORD_COLUMNS);\n },\n },\n {\n path: ['data-types', 'records', 'update'],\n description: 'Update a data record',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'data-type-id', description: 'Data type ID', required: true },\n { name: 'id', description: 'Record ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateDataRecord(\n workspace,\n requireNumber(args, 'data-type-id'),\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, RECORD_COLUMNS);\n },\n },\n {\n path: ['data-types', 'records', 'delete'],\n description: 'Delete a data record',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'data-type-id', description: 'Data type ID', required: true },\n { name: 'id', description: 'Record ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deleteDataRecord(\n workspace,\n requireNumber(args, 'data-type-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write(`Deleted data record ${args.id}\\n`);\n },\n },\n ],\n};\n","import { EventRuleActionType, EventRuleEventType, EventRuleObjectType } from '@gravity-rail/sdk';\nimport { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { fetchAllPages, listResult } from '../lib/pagination';\nimport { requireAuth } from '../lib/context';\n\ninterface SearchEventRulesArgs {\n objectType?: EventRuleObjectType;\n eventType?: EventRuleEventType;\n actionType?: EventRuleActionType;\n taskId?: number;\n dataTypeId?: number;\n routineId?: number;\n workflowId?: number;\n journeyStepId?: number;\n includeDisabled?: boolean;\n}\n\nconst RULE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'EVENT', getValue: (item: any) => item.eventType ?? '' },\n { header: 'ACTIVE', getValue: (item: any) => String(item.active ?? '') },\n];\n\nconst EVENT_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.status(),\n];\n\n// Generate event rules CRUD commands (get/create/update/delete only — list is customized below)\nconst eventRulesCrudNoList = crudCommands({\n prefix: ['events', 'rules'],\n entityName: 'event rule',\n getMethod: 'getEventRule',\n createMethod: 'createEventRule',\n updateMethod: 'updateEventRule',\n deleteMethod: 'deleteEventRule',\n columns: RULE_COLUMNS,\n createExamples: [\n 'gr events rules create -w $WID --data \\'{\"name\":\"Label on step\",\"objectType\":\"journey\",',\n ' \"eventType\":\"journey_step:execute\",\"actionType\":\"member:label\",',\n ' \"actionParams\":{\"addLabelIds\":[\"<label-uuid>\"]},\"journeyStepId\":<step-id>}\\'',\n '',\n 'Scheduled outbound (routine → chat → voice/SMS):',\n 'gr events rules create -w $WID --allow-write --data \\'{\"name\":\"AM voice check-in\",',\n ' \"objectType\":\"routine\",\"eventType\":\"routine:triggered\",\"actionType\":\"chat:create\",',\n ' \"routineId\":<routine-id>,',\n ' \"actionParams\":{\"workflowId\":<workflow-id>,\"channel\":\"phone-voice\",',\n ' \"phoneNumberId\":<workspace-phone-id>}}\\'',\n '',\n ' PM SMS variant: use \"channel\":\"phone-sms\" and a second rule on the same routineId.',\n ' Prereq: org phone assigned + gr phone-numbers link; workflow published with start task.',\n '',\n 'Required: objectType, eventType, actionType',\n 'Optional: name, actionParams, conditions (CEL), journeyStepId, routineId, delay (sec), order',\n '',\n 'Common eventTypes: journey_step:execute, journey:enrolled, routine:triggered,',\n ' task:created, chat:created, data_record:created, member:created',\n '',\n 'Common actionTypes: member:label, member:notify, webhook:send, email:send,',\n ' sms:send, chat:create, member:upsert',\n '',\n 'member:label actionParams: {\"addLabelIds\":[\"uuid\"],\"removeLabelIds\":[\"uuid\"]}',\n ],\n});\n\n// Custom list command for event rules — supports journey-step-id / event-type filters.\n// When filters are provided, routes to searchEventRules (unpaginated, filter-aware);\n// otherwise falls back to the paginated getEventRules endpoint with --page/--page-size/--all.\nconst eventRulesListCmd = {\n path: ['events', 'rules', 'list'],\n description: 'List event rules (use --journey-step-id or --event-type to filter)',\n requiresWorkspace: true,\n columns: RULE_COLUMNS,\n args: [\n { name: 'journey-step-id', description: 'Filter by journey step ID' },\n { name: 'event-type', description: 'Filter by event type (e.g. journey_step:execute)' },\n { name: 'object-type', description: 'Filter by object type (e.g. journey, task)' },\n { name: 'include-disabled', description: 'Include inactive rules', isFlag: true as const },\n { name: 'page', description: 'Page number (without filters)' },\n { name: 'page-size', description: 'Page size (without filters)' },\n {\n name: 'all',\n description: 'Fetch all pages (without filters)',\n isFlag: true as const,\n },\n ],\n handler: async ({ ctx, workspace, args }: any) => {\n const client = requireAuth(ctx).apiClient;\n const journeyStepId = args['journey-step-id']\n ? requireNumber(args, 'journey-step-id')\n : undefined;\n const eventType = args['event-type'] as EventRuleEventType | undefined;\n const objectType = args['object-type'] as EventRuleObjectType | undefined;\n const includeDisabled = args['include-disabled'] === true;\n\n // When any filter (including --include-disabled) is specified, delegate\n // to searchEventRules. The paginated getEventRules endpoint returns only\n // active rules and ignores includeDisabled, so we must route through\n // search to honor it.\n if (\n journeyStepId !== undefined ||\n eventType !== undefined ||\n objectType !== undefined ||\n includeDisabled\n ) {\n const result = await client.searchEventRules(workspace, {\n ...(journeyStepId !== undefined ? { journeyStepId } : {}),\n ...(eventType ? { eventType } : {}),\n ...(objectType ? { objectType } : {}),\n ...(includeDisabled ? { includeDisabled: true } : {}),\n });\n outputData(listResult(result, false), ctx, RULE_COLUMNS);\n return;\n }\n\n // No filters — paginated getEventRules\n if (args['all']) {\n const allItems = await fetchAllPages(async ({ page, pageSize }) =>\n client.getEventRules(workspace, { page, pageSize })\n );\n outputData(allItems, ctx, RULE_COLUMNS);\n return;\n }\n const page = args['page'] ? requireNumber(args, 'page') : undefined;\n const pageSize = args['page-size'] ? requireNumber(args, 'page-size') : undefined;\n const result = await client.getEventRules(workspace, {\n ...(page !== undefined ? { page } : {}),\n ...(pageSize !== undefined ? { pageSize } : {}),\n });\n outputData(listResult(result, true), ctx, RULE_COLUMNS);\n },\n};\n\n// Combine into the full set used by eventsDomain\nconst eventRulesCrud = [eventRulesListCmd, ...eventRulesCrudNoList];\n\n// Build aliases: \"events list\" → \"events rules list\", \"events get\" → \"events rules get\"\nconst eventRulesAliases = eventRulesCrud\n .filter((cmd) => {\n const verb = cmd.path[cmd.path.length - 1];\n return verb === 'list' || verb === 'get';\n })\n .map((cmd) => ({\n ...cmd,\n path: ['events', cmd.path[cmd.path.length - 1]!],\n description: `${cmd.description} (alias for events rules ${cmd.path[cmd.path.length - 1]})`,\n }));\n\nexport const eventsDomain: DomainDef = {\n name: 'events',\n description: 'Manage event rules and custom events',\n commands: [\n // Event rules\n ...eventRulesCrud,\n // Aliases: \"events list\" → \"events rules list\", etc.\n ...eventRulesAliases,\n {\n path: ['events', 'rules', 'executions'],\n description: 'List executions for an event rule',\n requiresWorkspace: true,\n args: [{ name: 'rule-id', description: 'Event rule ID' }],\n handler: async ({ ctx, workspace, args }) => {\n const ruleId = args['rule-id'] ? requireNumber(args, 'rule-id') : undefined;\n const result = await requireAuth(ctx).apiClient.getRuleExecutions(workspace, {\n ...(ruleId ? { ruleId } : {}),\n });\n outputData(result, ctx);\n },\n },\n {\n // The /event-rules/search endpoint returns an unpaginated list — the\n // server applies the filters and returns whatever matches. No --all\n // flag is needed; if the result becomes too large in practice,\n // tighten the filter rather than paginate.\n path: ['events', 'rules', 'search'],\n description: 'Search event rules by object/event/action type or related entity ID',\n requiresWorkspace: true,\n args: [\n {\n name: 'object-type',\n description:\n 'Filter by object type (task, routine, journey, workflow, calendar, ...)',\n },\n { name: 'event-type', description: 'Filter by event type' },\n { name: 'action-type', description: 'Filter by action type' },\n { name: 'task-id', description: 'Filter by task ID' },\n { name: 'data-type-id', description: 'Filter by data type ID' },\n { name: 'routine-id', description: 'Filter by routine ID' },\n { name: 'workflow-id', description: 'Filter by workflow ID' },\n { name: 'journey-step-id', description: 'Filter by journey step ID' },\n {\n name: 'include-disabled',\n description: 'Include inactive rules (default: active only)',\n },\n ],\n columns: RULE_COLUMNS,\n handler: async ({ ctx, workspace, args }) => {\n const opts: SearchEventRulesArgs = {};\n if (args['object-type']) opts.objectType = args['object-type'] as EventRuleObjectType;\n if (args['event-type']) opts.eventType = args['event-type'] as EventRuleEventType;\n if (args['action-type']) opts.actionType = args['action-type'] as EventRuleActionType;\n if (args['task-id']) opts.taskId = requireNumber(args, 'task-id');\n if (args['data-type-id']) opts.dataTypeId = requireNumber(args, 'data-type-id');\n if (args['routine-id']) opts.routineId = requireNumber(args, 'routine-id');\n if (args['workflow-id']) opts.workflowId = requireNumber(args, 'workflow-id');\n if (args['journey-step-id'])\n opts.journeyStepId = requireNumber(args, 'journey-step-id');\n if (args['include-disabled']) opts.includeDisabled = true;\n const result = await requireAuth(ctx).apiClient.searchEventRules(workspace, opts);\n outputData(result, ctx, RULE_COLUMNS);\n },\n },\n // Routines\n ...crudCommands({\n prefix: ['routines'],\n entityName: 'routine',\n listMethod: 'getRoutines',\n getMethod: 'getRoutine',\n createMethod: 'createRoutine',\n updateMethod: 'updateRoutine',\n deleteMethod: 'deleteRoutine',\n paginationSupport: 'full',\n columns: EVENT_COLUMNS,\n }),\n {\n path: ['routines', 'run'],\n description: 'Run a routine now',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Routine ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.runRoutine(\n workspace,\n requireNumber(args, 'id'),\n (data ?? {}) as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['routines', 'runs', 'list'],\n description: 'List runs for a routine',\n requiresWorkspace: true,\n args: [\n {\n name: 'id',\n description: 'Routine ID (aligns with routines get/run/update/delete)',\n },\n { name: 'status', description: 'Filter by run status' },\n { name: 'page', description: 'Page number (1-indexed)' },\n { name: 'page-size', description: 'Page size (max 100)' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const routineId = args.id ? requireNumber(args, 'id') : undefined;\n const page = args.page ? requireNumber(args, 'page') : undefined;\n const pageSize = args['page-size'] ? requireNumber(args, 'page-size') : undefined;\n const status = (args.status as string | undefined) ?? undefined;\n const result = await requireAuth(ctx).apiClient.getRoutineRuns(workspace, {\n ...(routineId !== undefined ? { routineId } : {}),\n ...(page !== undefined ? { page } : {}),\n ...(pageSize !== undefined ? { pageSize } : {}),\n ...(status ? { status } : {}),\n });\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'TYPE', getValue: (item: any) => item.content_type ?? item.type ?? '' },\n { header: 'SIZE', getValue: (item: any) => String(item.size ?? '') },\n { header: 'FOLDER', getValue: (item: any) => String(item.folder_id ?? '') },\n];\n\nconst FOLDER_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'PARENT', getValue: (item: any) => String(item.parentId ?? '') },\n { header: 'CHILDREN', getValue: (item: any) => String(item.childCount ?? '') },\n { header: 'FILES', getValue: (item: any) => String(item.fileCount ?? '') },\n { header: 'ACCESS', getValue: (item: any) => item.access ?? '' },\n];\n\nconst LABEL_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'COLOR', getValue: (item: any) => item.color ?? '' },\n];\n\nexport const filesDomain: DomainDef = {\n name: 'files',\n description: 'Manage files, folders, and labels',\n commands: [\n ...crudCommands({\n prefix: ['files'],\n entityName: 'file',\n listMethod: 'getFiles',\n getMethod: 'getFile',\n createMethod: 'createFile',\n updateMethod: 'updateFile',\n deleteMethod: 'deleteFile',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n // Folders sub-resource\n ...crudCommands({\n prefix: ['files', 'folders'],\n entityName: 'folder',\n listMethod: 'getFolders',\n getMethod: 'getFolder',\n createMethod: 'createFolder',\n updateMethod: 'updateFolder',\n deleteMethod: 'deleteFolder',\n columns: FOLDER_COLUMNS,\n listArgs: [\n {\n name: 'parent-id',\n description: 'Parent folder ID (required)',\n required: true,\n },\n ],\n }),\n {\n path: ['files', 'folders', 'reindex'],\n description: 'Reindex a folder',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Folder ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.reindexFolder(workspace, requireNumber(args, 'id'));\n process.stdout.write(`Reindexing folder ${args.id}\\n`);\n },\n },\n // Labels sub-resource\n ...crudCommands({\n prefix: ['files', 'labels'],\n entityName: 'file label',\n listMethod: 'getFileLabels',\n getMethod: 'getFileLabel',\n createMethod: 'createFileLabel',\n updateMethod: 'updateFileLabel',\n deleteMethod: 'deleteFileLabel',\n columns: LABEL_COLUMNS,\n }),\n ],\n};\n","import { EventRuleEventType } from '@gravity-rail/sdk';\nimport { requireAuth, type AuthenticatedContext } from '../lib/context';\nimport { CLIError } from '../lib/errors';\nimport type { TableColumn } from '../lib/output';\nimport { COL, outputData, outputSingle } from '../lib/output';\nimport { listResult } from '../lib/pagination';\nimport type { DomainDef } from '../lib/types';\nimport { requireNumber, requireString } from '../lib/types';\n\n// ── Column definitions ──────────────────────────────────────────────\n\nconst JOURNEY_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'UUID', getValue: (item: any) => (item.uuid ?? '').slice(0, 8) },\n COL.name(),\n COL.status(),\n COL.created(),\n];\n\nconst STEP_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'UUID', getValue: (item: any) => (item.uuid ?? '').slice(0, 8) },\n COL.name(),\n { header: 'TYPE', getValue: (item: any) => item.stepType ?? '' },\n { header: 'TRIGGER', getValue: (item: any) => item.triggerType ?? '' },\n { header: 'ORDER', getValue: (item: any) => String(item.order ?? '') },\n];\n\nconst MEMBER_JOURNEY_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'MEMBER', getValue: (item: any) => String(item.memberId ?? '') },\n COL.status(),\n { header: 'ENROLLED', getValue: (item: any) => item.enrolledAt ?? '' },\n];\n\nconst MEMBER_STEP_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'STEP', getValue: (item: any) => String(item.journeyStepId ?? '') },\n COL.status(),\n { header: 'ELIGIBLE', getValue: (item: any) => item.eligibleAt ?? '' },\n { header: 'COMPLETED', getValue: (item: any) => item.completedAt ?? '' },\n];\n\nconst GOAL_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'UUID', getValue: (item: any) => (item.uuid ?? '').slice(0, 8) },\n COL.name(),\n { header: 'VALUE', getValue: (item: any) => (item.value != null ? String(item.value) : '') },\n {\n header: 'ACHIEVED',\n getValue: (item: any) => (item.achievedCount != null ? String(item.achievedCount) : ''),\n },\n {\n header: 'ENROLLED',\n getValue: (item: any) => (item.totalEnrolled != null ? String(item.totalEnrolled) : ''),\n },\n];\n\nconst CONNECTION_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'PARENT', getValue: (item: any) => String(item.parentStepId ?? '') },\n { header: 'CHILD', getValue: (item: any) => String(item.childStepId ?? '') },\n { header: 'REQUIRED', getValue: (item: any) => (item.required ? 'yes' : '') },\n {\n header: 'TIMEOUT',\n getValue: (item: any) => (item.timeoutSeconds != null ? `${item.timeoutSeconds}s` : ''),\n },\n { header: 'CONDITION', getValue: (item: any) => item.celCondition ?? '' },\n {\n header: 'FILTER',\n getValue: (item: any) => (item.filterId != null ? String(item.filterId) : ''),\n },\n];\n\nconst NOTE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'AUTHOR', getValue: (item: any) => String(item.creatorId ?? '') },\n { header: 'CONTENT', getValue: (item: any) => (item.contents ?? '').slice(0, 60) },\n { header: 'CREATED', getValue: (item: any) => item.createdAt ?? '' },\n];\n\nconst ACTION_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'UUID', getValue: (item: any) => (item.uuid ?? '').slice(0, 8) },\n COL.name(),\n { header: 'EVENT', getValue: (item: any) => item.eventType ?? '' },\n { header: 'ACTION', getValue: (item: any) => item.actionType ?? '' },\n { header: 'ACTIVE', getValue: (item: any) => String(item.active ?? '') },\n { header: 'CONDITIONS', getValue: (item: any) => (item.conditions ?? '').slice(0, 40) },\n];\n\n// ── REST helpers ────────────────────────────────────────────────────\n\nfunction baseUrl(ctx: AuthenticatedContext, wid: string): string {\n return `${ctx.envConfig.apiUrl}/api/v2/w/${wid}/journeys`;\n}\n\nfunction notesUrl(ctx: AuthenticatedContext, wid: string, journeyId: string): string {\n return `${baseUrl(ctx, wid)}/${journeyId}/notes`;\n}\n\nfunction headers(ctx: AuthenticatedContext): Record<string, string> {\n return {\n Authorization: `Bearer ${ctx.accessToken}`,\n 'Content-Type': 'application/json',\n };\n}\n\nasync function errorDetail(res: Response): Promise<string> {\n try {\n const text = await res.text();\n const json = JSON.parse(text);\n return json.detail ?? json.message ?? text;\n } catch {\n return '';\n }\n}\n\nasync function apiGet(ctx: AuthenticatedContext, url: string): Promise<unknown> {\n const res = await fetch(url, { headers: headers(ctx) });\n if (!res.ok) {\n const detail = await errorDetail(res);\n throw new CLIError(`GET ${url} failed: ${res.status}${detail ? ` — ${detail}` : ''}`);\n }\n return res.json();\n}\n\nasync function apiPost(ctx: AuthenticatedContext, url: string, body?: unknown): Promise<unknown> {\n const res = await fetch(url, {\n method: 'POST',\n headers: headers(ctx),\n body: body ? JSON.stringify(body) : undefined,\n });\n if (!res.ok) {\n const detail = await errorDetail(res);\n throw new CLIError(`POST ${url} failed: ${res.status}${detail ? ` — ${detail}` : ''}`);\n }\n return res.json();\n}\n\nasync function apiPut(ctx: AuthenticatedContext, url: string, body: unknown): Promise<unknown> {\n const res = await fetch(url, {\n method: 'PUT',\n headers: headers(ctx),\n body: JSON.stringify(body),\n });\n if (!res.ok) {\n const detail = await errorDetail(res);\n throw new CLIError(`PUT ${url} failed: ${res.status}${detail ? ` — ${detail}` : ''}`);\n }\n return res.json();\n}\n\nasync function apiDelete(ctx: AuthenticatedContext, url: string): Promise<void> {\n const res = await fetch(url, { method: 'DELETE', headers: headers(ctx) });\n if (!res.ok) {\n const detail = await errorDetail(res);\n throw new CLIError(`DELETE ${url} failed: ${res.status}${detail ? ` — ${detail}` : ''}`);\n }\n}\n\n// ── Domain definition ───────────────────────────────────────────────\n\nexport const journeysDomain: DomainDef = {\n name: 'journeys',\n description: 'Manage journeys, steps, goals, connections, and enrollment',\n commands: [\n // ── Journey CRUD ───────────────────────────────────────────\n {\n path: ['journeys', 'list'],\n description: 'List all journeys in a workspace',\n requiresWorkspace: true,\n examples: ['gr journeys list -w $WID --env staging'],\n handler: async ({ ctx, workspace }) => {\n const result = await apiGet(requireAuth(ctx), baseUrl(requireAuth(ctx), workspace));\n outputData(listResult(result, false), ctx, JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'get'],\n description: 'Get a journey by ID',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n const result = await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}`\n );\n outputSingle(result, ctx, JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'create'],\n description: 'Create a journey',\n mutates: true,\n requiresWorkspace: true,\n examples: [\n 'gr journeys create -w $WID --data \\'{\"name\":\"Onboarding\",\"description\":\"New patient flow\",\"status\":\"draft\"}\\'',\n '',\n 'Fields: name (required), description, status (draft|active|paused)',\n ' ownerId (member ID), autoEnrollFilterId (filter ID)',\n ],\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await apiPost(\n requireAuth(ctx),\n baseUrl(requireAuth(ctx), workspace),\n data\n );\n outputSingle(result, ctx, JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'update'],\n description: 'Update a journey',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: ['gr journeys update -w $WID --id <journey-id> --data \\'{\"status\":\"active\"}\\''],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = requireString(args, 'id');\n const result = await apiPut(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}`,\n data\n );\n outputSingle(result, ctx, JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'archive'],\n description: 'Archive a journey (soft delete)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n await apiDelete(requireAuth(ctx), `${baseUrl(requireAuth(ctx), workspace)}/${id}`);\n process.stdout.write(`Archived journey ${id}\\n`);\n },\n },\n\n // ── Steps ──────────────────────────────────────────────────\n {\n path: ['journeys', 'steps', 'list'],\n description: 'List steps for a journey (from journey detail)',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: ['gr journeys steps list -w $WID --id <id>'],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n const result = (await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}`\n )) as any;\n outputData(result?.steps ?? [], ctx, STEP_COLUMNS);\n },\n },\n {\n path: ['journeys', 'steps', 'create'],\n description: 'Create a step in a journey',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'journey-id', description: 'Journey ID', required: true }],\n examples: [\n 'gr journeys steps create -w $WID --journey-id <journey-id> --data \\'{\"name\":\"Intake\"}\\'',\n '',\n 'Fields: name (required), description, order (int), workflowId (int),',\n ' assigneeId (member ID), posX/posY (canvas coords)',\n '',\n 'Attach event rules (e.g. label member) via \"gr events rules create\"',\n 'with eventType \"journey_step:execute\" and journeyStepId <step-id>',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const journeyId = requireString(args, 'journey-id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/steps`,\n data\n );\n outputSingle(result, ctx, STEP_COLUMNS);\n },\n },\n {\n path: ['journeys', 'steps', 'update'],\n description: 'Update a step',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Step UUID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const journeyId = requireString(args, 'journey-id');\n const stepId = requireString(args, 'id');\n const result = await apiPut(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/steps/${stepId}`,\n data\n );\n outputSingle(result, ctx, STEP_COLUMNS);\n },\n },\n {\n path: ['journeys', 'steps', 'archive'],\n description: 'Archive a step',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Step UUID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const stepId = requireString(args, 'id');\n await apiDelete(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/steps/${stepId}`\n );\n process.stdout.write(`Archived step ${stepId}\\n`);\n },\n },\n\n // ── Connections ────────────────────────────────────────────\n {\n path: ['journeys', 'connections', 'list'],\n description: 'List connections for a journey (aggregated from steps)',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: ['gr journeys connections list -w $WID --id <id>'],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n const result = (await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}`\n )) as any;\n // Connections are nested in steps — dedupe by id from childConnections\n const seen = new Set<number>();\n const connections: unknown[] = [];\n for (const step of result?.steps ?? []) {\n for (const conn of step?.childConnections ?? []) {\n if (!seen.has(conn.id)) {\n seen.add(conn.id);\n connections.push(conn);\n }\n }\n }\n outputData(connections, ctx, CONNECTION_COLUMNS);\n },\n },\n {\n path: ['journeys', 'connections', 'create'],\n description: 'Create a DAG edge between two steps (with optional CEL condition)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'journey-id', description: 'Journey ID', required: true }],\n examples: [\n 'gr journeys connections create -w $WID --journey-id <journey-id> \\\\',\n ' --data \\'{\"parentStepUuid\":\"<src>\",\"childStepUuid\":\"<dst>\"}\\'',\n '',\n 'Fields: parentStepUuid (required), childStepUuid (required),',\n ' order (int), celCondition (CEL expression string),',\n ' required (bool, default false), timeoutSeconds (int),',\n ' filterId (member filter ID, optional)',\n '',\n 'CEL condition example: \"member.labels.contains(\\\\\"step-1-done\\\\\")\"',\n '',\n 'Required edge (AND-gate — child waits for this parent):',\n ' --data \\'{\"parentStepUuid\":\"<src>\",\"childStepUuid\":\"<dst>\",\"required\":true}\\'',\n '',\n 'Edge with CEL timeout (300s = 5 min):',\n ' --data \\'{\"parentStepUuid\":\"<src>\",\"childStepUuid\":\"<dst>\",',\n ' \"celCondition\":\"member.labels.contains(\\\\\"approved\\\\\")\",\"timeoutSeconds\":300}\\'',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const journeyId = requireString(args, 'journey-id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/connections`,\n data\n );\n outputSingle(result, ctx, CONNECTION_COLUMNS);\n },\n },\n {\n path: ['journeys', 'connections', 'update'],\n description: 'Update a connection',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Connection ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const journeyId = requireString(args, 'journey-id');\n const connId = requireString(args, 'id');\n const result = await apiPut(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/connections/${connId}`,\n data\n );\n outputSingle(result, ctx, CONNECTION_COLUMNS);\n },\n },\n {\n path: ['journeys', 'connections', 'delete'],\n description: 'Remove a connection',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Connection ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const connId = requireString(args, 'id');\n await apiDelete(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/connections/${connId}`\n );\n process.stdout.write(`Deleted connection ${connId}\\n`);\n },\n },\n\n // ── Goals ──────────────────────────────────────────────────\n {\n path: ['journeys', 'goals', 'list'],\n description: 'List goals for a journey (from journey detail)',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: ['gr journeys goals list -w $WID --id <id>'],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n const result = (await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}`\n )) as any;\n outputData(result?.goals ?? [], ctx, GOAL_COLUMNS);\n },\n },\n {\n path: ['journeys', 'goals', 'create'],\n description: 'Create a goal (high-value outcome to track) for a journey',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'journey-id', description: 'Journey ID', required: true }],\n examples: [\n 'gr journeys goals create -w $WID --journey-id <journey-id> \\\\',\n ' --data \\'{\"name\":\"Onboarded\",\"goalStepUuid\":\"<step-uuid>\"}\\'',\n '',\n 'Fields: name (required), description, goalStepUuid (step that satisfies goal),',\n ' completionCel (CEL expression), value (float), order (int)',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const journeyId = requireString(args, 'journey-id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/goals`,\n data\n );\n outputSingle(result, ctx, GOAL_COLUMNS);\n },\n },\n {\n path: ['journeys', 'goals', 'update'],\n description: 'Update a goal',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Goal UUID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const journeyId = requireString(args, 'journey-id');\n const goalId = requireString(args, 'id');\n const result = await apiPut(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/goals/${goalId}`,\n data\n );\n outputSingle(result, ctx, GOAL_COLUMNS);\n },\n },\n {\n path: ['journeys', 'goals', 'delete'],\n description: 'Delete a goal',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Goal UUID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const goalId = requireString(args, 'id');\n await apiDelete(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/goals/${goalId}`\n );\n process.stdout.write(`Deleted goal ${goalId}\\n`);\n },\n },\n\n // ── Enrollment ─────────────────────────────────────────────\n {\n path: ['journeys', 'enroll'],\n description: 'Enroll member(s) in a journey',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: [\n 'gr journeys enroll -w $WID --id <id> --data \\'{\"memberIds\":[1,2,3]}\\'',\n 'gr journeys enroll -w $WID --id <id> --data \\'{\"memberId\":42}\\'',\n '',\n 'Fields: memberId (single) or memberIds (batch, max 100)',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = requireString(args, 'id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}/enroll`,\n data\n );\n outputData(listResult(result, false), ctx, MEMBER_JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'unenroll'],\n description: 'Unenroll member(s) from a journey',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: [\n 'gr journeys unenroll -w $WID --id <journey-id> --data \\'{\"memberIds\":[1],\"canceledReason\":\"test\"}\\'',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = requireString(args, 'id');\n await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}/unenroll`,\n data\n );\n process.stdout.write(`Unenrolled member(s) from journey ${id}\\n`);\n },\n },\n {\n path: ['journeys', 'reenroll'],\n description: 'Re-enroll a canceled member back into a journey',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = requireString(args, 'id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}/reenroll`,\n data\n );\n outputSingle(result, ctx, MEMBER_JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'members', 'delete'],\n description: 'Hard-delete a canceled enrollment so member can re-enroll fresh',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'member-id', description: 'Member ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const memberId = requireString(args, 'member-id');\n await apiDelete(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/members/${memberId}`\n );\n process.stdout.write(\n `Deleted enrollment for member ${memberId} from journey ${journeyId}\\n`\n );\n },\n },\n {\n path: ['journeys', 'members', 'list'],\n description: 'List members enrolled in a journey',\n requiresWorkspace: true,\n args: [{ name: 'journey-id', description: 'Journey ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const result = await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/members`\n );\n outputData(listResult(result, false), ctx, MEMBER_JOURNEY_COLUMNS);\n },\n },\n {\n path: ['journeys', 'members', 'get'],\n description: \"Get a member's journeys\",\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const memberId = requireString(args, 'member-id');\n const result = await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/by-member/${memberId}`\n );\n outputData(listResult(result, false), ctx, MEMBER_JOURNEY_COLUMNS);\n },\n },\n\n // ── Step progression ───────────────────────────────────────\n {\n path: ['journeys', 'steps', 'advance'],\n description: 'Mark a step as completed for a member (triggers downstream propagation)',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Step UUID', required: true },\n ],\n examples: [\n 'gr journeys steps advance -w $WID --journey-id <journey-id> --id <step-uuid>',\n 'gr journeys steps advance -w $WID --journey-id <journey-id> --id <step-uuid> --data \\'{\"memberId\":42,\"notes\":\"Passed\"}\\'',\n '',\n 'Fields: memberId (defaults to current user), notes (optional)',\n 'Completing a step makes downstream steps eligible (if all parents complete)',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const journeyId = requireString(args, 'journey-id');\n const stepId = requireString(args, 'id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/steps/${stepId}/advance`,\n data ?? {}\n );\n outputSingle(result, ctx, MEMBER_STEP_COLUMNS);\n },\n },\n {\n path: ['journeys', 'steps', 'skip'],\n description: 'Skip a step for a member (requires journeys:admin scope)',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Step UUID', required: true },\n ],\n examples: [\n 'gr journeys steps skip -w $WID --journey-id <journey-id> --id <step-uuid> --data \\'{\"memberId\":42,\"reason\":\"N/A\"}\\'',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const journeyId = requireString(args, 'journey-id');\n const stepId = requireString(args, 'id');\n const result = await apiPost(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/steps/${stepId}/skip`,\n data ?? {}\n );\n outputSingle(result, ctx, MEMBER_STEP_COLUMNS);\n },\n },\n\n // ── Step member visibility ──────────────────────────────────\n {\n path: ['journeys', 'steps', 'members'],\n description: 'List members at a specific journey step',\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Step UUID', required: true },\n ],\n examples: [\n 'gr journeys steps members -w $WID --journey-id 5 --id <step-uuid>',\n 'gr journeys steps members -w $WID --journey-id 5 --id <step-uuid> --data \\'{\"status\":\"in_progress\"}\\'',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const journeyId = requireString(args, 'journey-id');\n const stepId = requireString(args, 'id');\n const qs = new URLSearchParams();\n if (data && typeof data === 'object') {\n const d = data as Record<string, unknown>;\n if (d.status) qs.set('status', String(d.status));\n if (d.mode) qs.set('mode', String(d.mode));\n if (d.page) qs.set('page', String(d.page));\n if (d.pageSize) qs.set('pageSize', String(d.pageSize));\n }\n const query = qs.toString();\n const url = `${baseUrl(requireAuth(ctx), workspace)}/${journeyId}/steps/${stepId}/members${query ? `?${query}` : ''}`;\n const result = await apiGet(requireAuth(ctx), url);\n const STEP_MEMBER_COLS: TableColumn<unknown>[] = [\n { header: 'MEMBER_ID', getValue: (item: any) => String(item.memberId ?? '') },\n { header: 'NAME', getValue: (item: any) => item.memberName ?? '' },\n { header: 'STATUS', getValue: (item: any) => item.stepStatus ?? '' },\n { header: 'ELIGIBLE', getValue: (item: any) => item.eligibleAt ?? '' },\n { header: 'ACTIVATED', getValue: (item: any) => item.activatedAt ?? '' },\n { header: 'COMPLETED', getValue: (item: any) => item.completedAt ?? '' },\n ];\n outputData(listResult(result, false), ctx, STEP_MEMBER_COLS);\n },\n },\n {\n path: ['journeys', 'step-member-counts'],\n description: 'Get member counts per step for a journey',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Journey ID', required: true }],\n examples: ['gr journeys step-member-counts -w $WID --id 5'],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n const result = await apiGet(\n requireAuth(ctx),\n `${baseUrl(requireAuth(ctx), workspace)}/${id}/step-member-counts`\n );\n const COUNT_COLS: TableColumn<unknown>[] = [\n { header: 'STEP_ID', getValue: (item: any) => String(item.stepId ?? '') },\n {\n header: 'STEP_UUID',\n getValue: (item: any) => (item.stepUuid ?? '').slice(0, 8),\n },\n { header: 'TOTAL', getValue: (item: any) => String(item.total ?? 0) },\n {\n header: 'BY_STATUS',\n getValue: (item: any) => {\n const bs = item.byStatus;\n if (!bs || typeof bs !== 'object') return '';\n return Object.entries(bs)\n .filter(([, v]) => (v as number) > 0)\n .map(([k, v]) => `${k}:${v}`)\n .join(', ');\n },\n },\n ];\n outputData(listResult(result, false), ctx, COUNT_COLS);\n },\n },\n\n // ── Notes ───────────────────────────────────────────────────\n {\n path: ['journeys', 'notes', 'list'],\n description: 'List notes for a journey',\n requiresWorkspace: true,\n args: [{ name: 'journey-id', description: 'Journey ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const result = await apiGet(\n requireAuth(ctx),\n notesUrl(requireAuth(ctx), workspace, journeyId)\n );\n outputData(listResult(result, false), ctx, NOTE_COLUMNS);\n },\n },\n {\n path: ['journeys', 'notes', 'create'],\n description: 'Create a note on a journey (canvas sticky note)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'journey-id', description: 'Journey ID', required: true }],\n examples: [\n 'gr journeys notes create -w $WID --journey-id 5 --data \\'{\"posX\":0,\"posY\":0,\"contents\":\"Note text\"}\\'',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data with content)');\n const journeyId = requireString(args, 'journey-id');\n const result = await apiPost(\n requireAuth(ctx),\n notesUrl(requireAuth(ctx), workspace, journeyId),\n data\n );\n outputSingle(result, ctx, NOTE_COLUMNS);\n },\n },\n {\n path: ['journeys', 'notes', 'update'],\n description: 'Update a journey note',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Note ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data with content)');\n const journeyId = requireString(args, 'journey-id');\n const noteId = requireString(args, 'id');\n const result = await apiPut(\n requireAuth(ctx),\n `${notesUrl(requireAuth(ctx), workspace, journeyId)}/${noteId}`,\n data\n );\n outputSingle(result, ctx, NOTE_COLUMNS);\n },\n },\n {\n path: ['journeys', 'notes', 'delete'],\n description: 'Delete a journey note',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'journey-id', description: 'Journey ID', required: true },\n { name: 'id', description: 'Note ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const journeyId = requireString(args, 'journey-id');\n const noteId = requireString(args, 'id');\n await apiDelete(\n requireAuth(ctx),\n `${notesUrl(requireAuth(ctx), workspace, journeyId)}/${noteId}`\n );\n process.stdout.write(`Deleted note ${noteId}\\n`);\n },\n },\n\n // ── Step execute actions (event rules scoped to a step) ────────\n {\n path: ['journeys', 'steps', 'actions', 'list'],\n description: 'List event rules (actions) attached to a journey step',\n requiresWorkspace: true,\n args: [\n { name: 'step-id', description: 'Journey step ID (numeric)', required: true },\n {\n name: 'include-disabled',\n description: 'Include inactive/disabled rules',\n isFlag: true,\n },\n ],\n examples: [\n 'gr journeys steps actions list -w $WID --step-id <step-id>',\n 'gr journeys steps actions list -w $WID --step-id <step-id> --include-disabled',\n ],\n handler: async ({ ctx, workspace, args }) => {\n const stepId = requireNumber(args, 'step-id');\n const includeDisabled = args['include-disabled'] === true;\n const result = await requireAuth(ctx).apiClient.searchEventRules(workspace, {\n eventType: EventRuleEventType.JOURNEY_STEP_EXECUTE,\n journeyStepId: stepId,\n ...(includeDisabled ? { includeDisabled: true } : {}),\n });\n outputData(listResult(result, false), ctx, ACTION_COLUMNS);\n },\n },\n {\n path: ['journeys', 'steps', 'actions', 'get'],\n description: 'Get a journey step action (event rule) by ID',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event rule ID', required: true }],\n examples: ['gr journeys steps actions get -w $WID --id <rule-id>'],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.getEventRule(workspace, id);\n outputSingle(result, ctx, ACTION_COLUMNS);\n },\n },\n {\n path: ['journeys', 'steps', 'actions', 'update'],\n description: 'Update a journey step action — modify template, conditions, or active state',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Event rule ID', required: true }],\n examples: [\n 'gr journeys steps actions update -w $WID --id <rule-id> \\\\',\n ' --data \\'{\"actionParams\":{\"messageTemplate\":\"Hello {{member.name}}\"}}\\' --allow-write',\n '',\n 'Updatable fields: name, conditions (CEL), actionParams, active, delay, order',\n 'Non-updatable: objectType, eventType, actionType, journeyStepId',\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const id = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.updateEventRule(\n workspace,\n id,\n data as any\n );\n outputSingle(result, ctx, ACTION_COLUMNS);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport type { TableColumn } from '../lib/output';\nimport { COL } from '../lib/output';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'AGE', getValue: (item: any) => (item.age != null ? String(item.age) : '') },\n {\n header: 'HAS_PHONE',\n getValue: (item: any) => (item.hasPhone ? 'yes' : 'no'),\n },\n {\n header: 'HAS_EMAIL',\n getValue: (item: any) => (item.hasEmail ? 'yes' : 'no'),\n },\n {\n header: 'DATA_RECORDS',\n getValue: (item: any) =>\n item.dataRecords ? String(Object.keys(item.dataRecords).length) : '0',\n },\n COL.created(),\n];\n\nexport const personasDomain: DomainDef = {\n name: 'personas',\n description: 'Manage workspace-scoped test personas (identity templates for scenario runs)',\n commands: [\n ...crudCommands({\n prefix: ['personas'],\n entityName: 'persona',\n listMethod: 'listPersonas',\n getMethod: 'getPersona',\n createMethod: 'createPersona',\n updateMethod: 'updatePersona',\n deleteMethod: 'deletePersona',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst QUALIFICATION_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'WORKFLOW', getValue: (item: any) => String(item.workflowId ?? '') },\n { header: 'WORKFLOW_NAME', getValue: (item: any) => item.workflowName ?? '' },\n COL.created(),\n];\n\nconst SCENARIO_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'PERSONA', getValue: (item: any) => item.personaName ?? '' },\n { header: 'CHANNEL', getValue: (item: any) => item.channel ?? '' },\n];\n\nconst RUN_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'WORKFLOW', getValue: (item: any) => String(item.workflowId ?? '') },\n {\n header: 'SCENARIO',\n getValue: (item: any) =>\n item.scenarioName ?? (item.scenarioId != null ? String(item.scenarioId) : 'ad-hoc'),\n },\n {\n header: 'DRIVER',\n getValue: (item: any) =>\n item.driverMemberId == null\n ? 'auto'\n : (item.driverMemberName ?? `member #${item.driverMemberId}`),\n },\n { header: 'STARTED', getValue: (item: any) => item.startedAt ?? '' },\n { header: 'COMPLETED', getValue: (item: any) => item.completedAt ?? '' },\n {\n header: 'SCORE',\n getValue: (item: any) => (item.overallScore != null ? String(item.overallScore) : ''),\n },\n {\n header: 'PASSED',\n getValue: (item: any) => (item.passed != null ? String(item.passed) : ''),\n },\n];\n\nexport const qualificationsDomain: DomainDef = {\n name: 'qualifications',\n description: 'Manage qualifications, scenarios, and test chat runs',\n commands: [\n {\n path: ['qualifications', 'list'],\n description: 'List qualifications (one per workflow)',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getQualifications(workspace);\n outputData(result.items, ctx, QUALIFICATION_COLUMNS);\n },\n },\n {\n path: ['qualifications', 'get'],\n description: 'Get a qualification by ID',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Qualification ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getQualification(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['qualifications', 'for-workflow'],\n description: 'Fetch (auto-creating if absent) the qualification for a workflow',\n requiresWorkspace: true,\n args: [{ name: 'workflow-id', description: 'Workflow ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getOrCreateQualificationForWorkflow(\n workspace,\n requireNumber(args, 'workflow-id')\n );\n outputSingle(result, ctx);\n },\n },\n // Scenarios\n {\n path: ['qualifications', 'scenarios', 'list'],\n description: 'List scenarios on a qualification',\n requiresWorkspace: true,\n args: [{ name: 'qualification-id', description: 'Qualification ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.listScenarios(\n workspace,\n requireNumber(args, 'qualification-id')\n );\n outputData(result, ctx, SCENARIO_COLUMNS);\n },\n },\n {\n path: ['qualifications', 'scenarios', 'get'],\n description: 'Get a scenario',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Scenario ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getScenario(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, SCENARIO_COLUMNS);\n },\n },\n {\n path: ['qualifications', 'scenarios', 'create'],\n description: 'Create a scenario on a qualification (pass JSON via --data)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'qualification-id', description: 'Qualification ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.createScenario(\n workspace,\n requireNumber(args, 'qualification-id'),\n data as any\n );\n outputSingle(result, ctx, SCENARIO_COLUMNS);\n },\n },\n {\n path: ['qualifications', 'scenarios', 'update'],\n description: 'Update a scenario (pass JSON via --data)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Scenario ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateScenario(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, SCENARIO_COLUMNS);\n },\n },\n {\n path: ['qualifications', 'scenarios', 'delete'],\n description: 'Archive a scenario',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Scenario ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deleteScenario(workspace, requireNumber(args, 'id'));\n process.stdout.write(`Archived scenario ${args['id']}\\n`);\n },\n },\n // Test chat runs\n {\n path: ['qualifications', 'runs', 'list'],\n description: 'List recent test chat runs for a workflow',\n requiresWorkspace: true,\n args: [\n { name: 'workflow-id', description: 'Workflow ID', required: true },\n { name: 'scenario-id', description: 'Filter by scenario', required: false },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const scenarioId = args['scenario-id'] ? requireNumber(args, 'scenario-id') : undefined;\n const result = await requireAuth(ctx).apiClient.listTestChatRuns(\n workspace,\n requireNumber(args, 'workflow-id'),\n scenarioId != null ? { scenarioId } : undefined\n );\n outputData(result, ctx, RUN_COLUMNS);\n },\n },\n {\n path: ['qualifications', 'runs', 'get'],\n description: 'Get a test chat run',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Test chat run ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getTestChatRun(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['qualifications', 'runs', 'start'],\n description: 'Start a test chat run',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'workflow-id', description: 'Workflow ID', required: true },\n { name: 'scenario-id', description: 'Bind to a scenario', required: false },\n {\n name: 'persona-id',\n description: 'Persona (required if no scenario)',\n required: false,\n },\n { name: 'goal', description: 'Goal for the user simulator', required: false },\n { name: 'driver', description: 'Driver mode: auto | human', required: false },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const driver = (args['driver'] === 'human' ? 'human' : 'auto') as 'auto' | 'human';\n const scenarioId = args['scenario-id'] ? requireNumber(args, 'scenario-id') : undefined;\n const personaId = args['persona-id'] ? requireNumber(args, 'persona-id') : undefined;\n const result = await requireAuth(ctx).apiClient.startTestChatRun(\n workspace,\n requireNumber(args, 'workflow-id'),\n {\n ...(scenarioId != null ? { scenarioId } : {}),\n ...(personaId != null ? { personaId } : {}),\n ...(args['goal'] ? { goal: String(args['goal']) } : {}),\n driver,\n } as any\n );\n outputSingle(result.run, ctx);\n },\n },\n {\n path: ['qualifications', 'runs', 'evaluate'],\n description: 'Evaluate a completed scenario-bound test chat run',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Test chat run ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.evaluateTestChatRun(\n workspace,\n requireNumber(args, 'id')\n );\n process.stdout.write(`Evaluation started for test chat run ${args['id']}\\n`);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n { header: 'DOMAIN', getValue: (item: any) => item.domain ?? '' },\n];\n\nconst PAGE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'TITLE', getValue: (item: any) => item.title ?? '' },\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.status(),\n];\n\nconst MENU_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'LABEL', getValue: (item: any) => item.label ?? '' },\n { header: 'TYPE', getValue: (item: any) => item.type ?? '' },\n { header: 'ORDER', getValue: (item: any) => String(item.order ?? '') },\n];\n\nexport const sitesDomain: DomainDef = {\n name: 'sites',\n description: 'Manage sites, pages, and menus',\n commands: [\n ...crudCommands({\n prefix: ['sites'],\n entityName: 'site',\n listMethod: 'getSites',\n getMethod: 'getSite',\n createMethod: 'createSite',\n updateMethod: 'updateSite',\n deleteMethod: 'deleteSite',\n columns: COLUMNS,\n }),\n // Pages sub-resource\n {\n path: ['sites', 'pages', 'list'],\n description: 'List pages for a site',\n requiresWorkspace: true,\n args: [{ name: 'site-id', description: 'Site ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getSitePages(\n workspace,\n requireNumber(args, 'site-id')\n );\n outputData(result, ctx, PAGE_COLUMNS);\n },\n },\n {\n path: ['sites', 'pages', 'get'],\n description: 'Get a page',\n requiresWorkspace: true,\n args: [\n { name: 'site-id', description: 'Site ID', required: true },\n { name: 'id', description: 'Page ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getPage(\n workspace,\n requireNumber(args, 'site-id'),\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, PAGE_COLUMNS);\n },\n },\n {\n path: ['sites', 'pages', 'create'],\n description: 'Create a page',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'site-id', description: 'Site ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.createPage(\n workspace,\n requireNumber(args, 'site-id'),\n data as any\n );\n outputSingle(result, ctx, PAGE_COLUMNS);\n },\n },\n {\n path: ['sites', 'pages', 'update'],\n description: 'Update a page',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'site-id', description: 'Site ID', required: true },\n { name: 'id', description: 'Page ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updatePage(\n workspace,\n requireNumber(args, 'site-id'),\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, PAGE_COLUMNS);\n },\n },\n {\n path: ['sites', 'pages', 'delete'],\n description: 'Delete a page',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'site-id', description: 'Site ID', required: true },\n { name: 'id', description: 'Page ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deletePage(\n workspace,\n requireNumber(args, 'site-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write(`Deleted page ${args.id}\\n`);\n },\n },\n // Menu items sub-resource\n {\n path: ['sites', 'menu', 'list'],\n description: 'List menu items for a site',\n requiresWorkspace: true,\n args: [{ name: 'site-id', description: 'Site ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getMenuItems(\n workspace,\n requireNumber(args, 'site-id')\n );\n outputData(result, ctx, MENU_COLUMNS);\n },\n },\n {\n path: ['sites', 'menu', 'create'],\n description: 'Create a menu item',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'site-id', description: 'Site ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.createMenuItem(\n workspace,\n requireNumber(args, 'site-id'),\n data as any\n );\n outputSingle(result, ctx, MENU_COLUMNS);\n },\n },\n {\n path: ['sites', 'menu', 'update'],\n description: 'Update a menu item',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'site-id', description: 'Site ID', required: true },\n { name: 'id', description: 'Menu item ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateMenuItem(\n workspace,\n requireNumber(args, 'site-id'),\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, MENU_COLUMNS);\n },\n },\n {\n path: ['sites', 'menu', 'delete'],\n description: 'Delete a menu item',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'site-id', description: 'Site ID', required: true },\n { name: 'id', description: 'Menu item ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.deleteMenuItem(\n workspace,\n requireNumber(args, 'site-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write(`Deleted menu item ${args.id}\\n`);\n },\n },\n ],\n};\n","import { type DomainDef, requireString, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { listResult } from '../lib/pagination';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.status(),\n { header: 'GRANTOR', getValue: (item: any) => String(item.grantor_member_id ?? '') },\n { header: 'GRANTEE', getValue: (item: any) => String(item.grantee_member_id ?? '') },\n COL.created(),\n];\n\nexport const accessGrantsDomain: DomainDef = {\n name: 'access-grants',\n description: 'Manage access grants',\n commands: [\n {\n path: ['access-grants', 'list'],\n description: 'List all access grants',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getAccessGrants(workspace);\n outputData(listResult(result, false), ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'get'],\n description: 'Get an access grant by ID',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Access grant ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getAccessGrant(\n workspace,\n requireString(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'create'],\n description: 'Create an access grant',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.createAccessGrant(\n workspace,\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'received'],\n description: 'List access grants received by me',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMyReceivedGrants(workspace, {\n pageSize: 200,\n });\n outputData(listResult(result, false), ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'given'],\n description: 'List access grants given by me',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMyGivenGrants(workspace, {\n pageSize: 200,\n });\n outputData(listResult(result, false), ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'resolve'],\n description: 'Resolve an access grant',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Access grant ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.resolveAccessGrant(\n workspace,\n requireString(args, 'id'),\n (data ?? {}) as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'revoke'],\n description: 'Revoke an access grant',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Access grant ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.revokeAccessGrant(\n workspace,\n requireString(args, 'id'),\n (data ?? {}) as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['access-grants', 'member'],\n description: 'List access grants for a specific member',\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getMemberGrants(\n workspace,\n requireNumber(args, 'member-id')\n );\n outputData(listResult(result, false), ctx, COLUMNS);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n { header: 'ID', getValue: (item: any) => String(item.id ?? item.model_id ?? '') },\n { header: 'NAME', getValue: (item: any) => item.name ?? item.display_name ?? '' },\n { header: 'PROVIDER', getValue: (item: any) => item.provider ?? '' },\n { header: 'TYPE', getValue: (item: any) => item.type ?? '' },\n];\n\nexport const aiModelsDomain: DomainDef = {\n name: 'ai-models',\n description: 'List available AI models',\n commands: [\n {\n path: ['ai-models', 'list'],\n description: 'List all available AI models',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getAllModels();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['ai-models', 'chat'],\n description: 'List chat models',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getChatModels();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['ai-models', 'realtime'],\n description: 'List realtime models',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getRealtimeModels();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['ai-models', 'voice'],\n description: 'List voice models',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getVoiceModels();\n outputData(result, ctx, COLUMNS);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'PREFIX', getValue: (item: any) => item.prefix ?? '' },\n COL.created(),\n];\n\n// Includes the plaintext key — only used on create responses where the key is present.\nconst CREATE_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'KEY', getValue: (item: any) => item.key ?? '' },\n { header: 'PREFIX', getValue: (item: any) => item.prefix ?? '' },\n COL.created(),\n];\n\nexport const apiKeysDomain: DomainDef = {\n name: 'api-keys',\n description: 'Manage API keys',\n commands: [\n {\n path: ['api-keys', 'list'],\n description: 'List workspace API keys',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getApiKeys(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['api-keys', 'create'],\n description: 'Create a workspace API key',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.createApiKey(workspace, data as any);\n outputSingle(result, ctx, CREATE_COLUMNS);\n if (ctx.outputFormat === 'table') {\n process.stdout.write('\\n⚠ This key will not be shown again. Copy it now.\\n');\n }\n },\n },\n {\n path: ['api-keys', 'revoke'],\n description: 'Revoke a workspace API key',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'API key ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.revokeApiKey(workspace, id);\n process.stdout.write(`Revoked API key ${id}\\n`);\n },\n },\n {\n path: ['api-keys', 'global', 'list'],\n description: 'List global/account-level API keys',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getGlobalApiKeys();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['api-keys', 'global', 'create'],\n description: 'Create a global/account-level API key',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.createGlobalApiKey(data as any);\n outputSingle(result, ctx, CREATE_COLUMNS);\n if (ctx.outputFormat === 'table') {\n process.stdout.write('\\n⚠ This key will not be shown again. Copy it now.\\n');\n }\n },\n },\n {\n path: ['api-keys', 'global', 'revoke'],\n description: 'Revoke a global/account-level API key',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'API key ID', required: true }],\n handler: async ({ ctx, args }) => {\n const id = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.revokeGlobalApiKey(id);\n process.stdout.write(`Revoked global API key ${id}\\n`);\n },\n },\n ],\n};\n","import { type DomainDef, requireString } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst APP_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'CLIENT_ID', getValue: (item: any) => item.client_id ?? '' },\n COL.status(),\n];\n\nconst BUILDER_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.name(), COL.status()];\n\nconst INQUIRY_COLUMNS: TableColumn<unknown>[] = [COL.id(), COL.status(), COL.created()];\n\nexport const appsDomain: DomainDef = {\n name: 'apps',\n description: 'Manage apps, builders, and inquiries',\n commands: [\n // Apps\n {\n path: ['apps', 'list'],\n description: 'List apps',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.listApps();\n outputData(result, ctx, APP_COLUMNS);\n },\n },\n {\n path: ['apps', 'get'],\n description: 'Get an app by ID',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'App ID', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.getApp(requireString(args, 'id'));\n outputSingle(result, ctx, APP_COLUMNS);\n },\n },\n {\n path: ['apps', 'create'],\n description: 'Create an app',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.createApp(data as any);\n outputSingle(result, ctx, APP_COLUMNS);\n },\n },\n {\n path: ['apps', 'update'],\n description: 'Update an app',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'App ID', required: true }],\n handler: async ({ ctx, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateApp(\n requireString(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, APP_COLUMNS);\n },\n },\n {\n path: ['apps', 'delete'],\n description: 'Delete an app',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'App ID', required: true }],\n handler: async ({ ctx, args }) => {\n const id = requireString(args, 'id');\n await requireAuth(ctx).apiClient.deleteApp(id);\n process.stdout.write(`Deleted app ${id}\\n`);\n },\n },\n {\n path: ['apps', 'regenerate-secret'],\n description: 'Regenerate client secret for an app',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'App ID', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.regenerateClientSecret(\n requireString(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n\n // Builders\n ...crudCommands({\n prefix: ['apps', 'builders'],\n entityName: 'builder',\n listMethod: 'listBuilders',\n getMethod: 'getBuilder',\n createMethod: 'createBuilder',\n updateMethod: 'updateBuilder',\n deleteMethod: 'deleteBuilder',\n columns: BUILDER_COLUMNS,\n requiresWorkspace: false,\n }),\n {\n path: ['apps', 'builders', 'apps'],\n description: 'List apps for a builder',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Builder ID', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.getBuilderApps(\n requireString(args, 'id')\n );\n outputData(result, ctx, APP_COLUMNS);\n },\n },\n\n // Inquiries\n ...crudCommands({\n prefix: ['apps', 'inquiries'],\n entityName: 'inquiry',\n listMethod: 'listInquiries',\n getMethod: 'getInquiry',\n createMethod: 'createInquiry',\n updateMethod: 'updateInquiry',\n deleteMethod: 'deleteInquiry',\n columns: INQUIRY_COLUMNS,\n requiresWorkspace: false,\n paginationSupport: 'full',\n }),\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputSingle, outputData } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nexport const authManageDomain: DomainDef = {\n name: 'auth',\n description: 'Manage authentication, 2FA, and credentials',\n commands: [\n {\n path: ['auth', 'account'],\n description: 'Get current user account info',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getUserAccount();\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', 'update-account'],\n description: 'Update current user account',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.updateUserAccount(data as any);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', 'password-status'],\n description: 'Get password status',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getPasswordStatus();\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', 'change-password'],\n description: 'Change password',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.changePassword(\n (data as any)?.currentPassword,\n (data as any)?.newPassword\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', 'set-password'],\n description: 'Set password (for accounts without one)',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.setPassword(data as any);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', '2fa-status'],\n description: 'Get two-factor authentication status',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getTwoFactorStatus();\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', 'pending-credential-changes'],\n description: 'List pending credential changes',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getPendingCredentialChanges();\n outputData(result, ctx);\n },\n },\n {\n path: ['auth', 'request-credential-change'],\n description: 'Request a credential change',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const result = await requireAuth(ctx).apiClient.requestCredentialChange(\n (data as any)?.credentialType,\n (data as any)?.newValue\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['auth', 'cancel-credential-change'],\n description: 'Cancel a pending credential change',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Credential change ID', required: true }],\n handler: async ({ ctx, args }) => {\n await requireAuth(ctx).apiClient.cancelCredentialChange(requireNumber(args, 'id'));\n process.stdout.write(`Cancelled credential change ${args.id}\\n`);\n },\n },\n // ── Consent (GDPR) ──\n {\n path: ['auth', 'consent'],\n description: 'Get current consent state',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getConsentState();\n const columns: TableColumn<unknown>[] = [\n { header: 'TYPE', getValue: (item: any) => item.consent_type ?? '' },\n { header: 'GRANTED', getValue: (item: any) => String(item.granted) },\n { header: 'UPDATED', getValue: (item: any) => item.updated_at ?? '' },\n { header: 'VERSION', getValue: (item: any) => item.policy_version ?? '' },\n ];\n outputData(result.consents, ctx, columns);\n },\n },\n {\n path: ['auth', 'consent-update'],\n description:\n 'Update consent (e.g. --data \\'{\"consents\":[{\"consent_type\":\"cookie_analytics\",\"granted\":true}]}\\')',\n mutates: true,\n requiresWorkspace: false,\n handler: async ({ ctx, data }) => {\n const body = data as any;\n const consents = body?.consents;\n if (!Array.isArray(consents) || consents.length === 0) {\n process.stderr.write(\n 'Error: --data must include \"consents\" array, e.g. --data \\'{\"consents\":[{\"consent_type\":\"cookie_analytics\",\"granted\":true}]}\\'\\n'\n );\n process.exit(1);\n }\n const result = await requireAuth(ctx).apiClient.updateConsent(consents);\n const columns: TableColumn<unknown>[] = [\n { header: 'TYPE', getValue: (item: any) => item.consent_type ?? '' },\n { header: 'GRANTED', getValue: (item: any) => String(item.granted) },\n { header: 'UPDATED', getValue: (item: any) => item.updated_at ?? '' },\n { header: 'VERSION', getValue: (item: any) => item.policy_version ?? '' },\n ];\n outputData(result.consents, ctx, columns);\n },\n },\n ],\n};\n","// `Invoice` is not re-exported from the public `@gravity-rail/sdk` surface.\n// Use a structural shape that matches the runtime response.\ninterface Invoice {\n id: number;\n invoiceNumber: string;\n status: string;\n amount: number;\n periodStart?: string;\n periodEnd?: string;\n productName?: string;\n paymentReference?: string | null;\n}\nimport { CLIError } from '../lib/errors';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle } from '../lib/output';\nimport { listResult } from '../lib/pagination';\nimport type { CommandDef, DomainDef } from '../lib/types';\nimport { requireAuth } from '../lib/context';\n\nconst INVOICE_COLUMNS: TableColumn<Invoice>[] = [\n { header: 'ID', getValue: (i) => String(i.id) },\n { header: 'Invoice #', getValue: (i) => i.invoiceNumber },\n { header: 'Status', getValue: (i) => i.status },\n {\n header: 'Amount',\n getValue: (i) => `$${(i.amount / 100).toFixed(2)}`,\n },\n {\n header: 'Period Start',\n getValue: (i) => (i.periodStart ? new Date(i.periodStart).toLocaleDateString() : ''),\n },\n {\n header: 'Period End',\n getValue: (i) => (i.periodEnd ? new Date(i.periodEnd).toLocaleDateString() : ''),\n },\n { header: 'Product', getValue: (i) => i.productName ?? '' },\n { header: 'Ref', getValue: (i) => i.paymentReference ?? '' },\n];\n\nconst commands: CommandDef[] = [\n {\n path: ['billing', 'customers'],\n description: 'List your customer accounts',\n requiresWorkspace: false,\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.getMyCustomers();\n outputData(listResult(result, false), hctx.ctx);\n },\n },\n {\n path: ['billing', 'customer'],\n description: 'Get a customer by UUID',\n args: [{ name: 'uuid', description: 'Customer UUID', required: true }],\n requiresWorkspace: false,\n handler: async (hctx) => {\n const uuid = hctx.args.uuid as string;\n const result = await requireAuth(hctx.ctx).apiClient.getMyCustomer(uuid);\n outputSingle(result, hctx.ctx);\n },\n },\n {\n path: ['billing', 'update-customer'],\n description: 'Update a customer record (billing owner only)',\n mutates: true,\n args: [\n { name: 'uuid', description: 'Customer UUID', required: true },\n { name: 'name', description: 'Customer name' },\n { name: 'email', description: 'Billing email' },\n { name: 'phone', description: 'Phone number' },\n { name: 'description', description: 'Description / notes' },\n ],\n requiresWorkspace: false,\n handler: async (hctx) => {\n const uuid = hctx.args.uuid as string;\n const data: Record<string, string | undefined> = {};\n if (hctx.args.name) data.name = hctx.args.name as string;\n if (hctx.args.email) data.email = hctx.args.email as string;\n if (hctx.args.phone) data.phone = hctx.args.phone as string;\n if (hctx.args.description) data.description = hctx.args.description as string;\n if (Object.keys(data).length === 0 && !hctx.data) {\n throw new CLIError('Provide --name, --email, --phone, --description, or JSON data');\n }\n const result = await requireAuth(hctx.ctx).apiClient.updateMyCustomer(\n uuid,\n hctx.data ? (hctx.data as Record<string, string>) : data\n );\n outputSingle(result, hctx.ctx);\n },\n },\n {\n path: ['billing', 'invoices'],\n description: 'List invoices for a customer',\n args: [{ name: 'uuid', description: 'Customer UUID', required: true }],\n requiresWorkspace: false,\n handler: async (hctx) => {\n const uuid = hctx.args.uuid as string;\n const result = await requireAuth(hctx.ctx).apiClient.getMyCustomerInvoices(uuid);\n outputData(listResult(result, false), hctx.ctx, INVOICE_COLUMNS as TableColumn<unknown>[]);\n },\n },\n {\n path: ['billing', 'subscriptions'],\n description: 'List subscriptions for a customer',\n args: [{ name: 'uuid', description: 'Customer UUID', required: true }],\n requiresWorkspace: false,\n handler: async (hctx) => {\n const uuid = hctx.args.uuid as string;\n const result = await requireAuth(hctx.ctx).apiClient.getMyCustomerSubscriptions(uuid);\n outputData(listResult(result, false), hctx.ctx);\n },\n },\n];\n\nexport const billingPortalDomain: DomainDef = {\n name: 'billing',\n description: 'Billing portal (customer invoices, subscriptions)',\n commands,\n};\n","/**\n * Concierge API client — direct HTTP calls to the global concierge endpoints.\n *\n * The concierge is account-level (no workspace), so these bypass the ApiClient\n * which is workspace-oriented.\n */\n\nimport type { AuthenticatedContext } from './context';\n\nexport interface ConciergeChat {\n id: number;\n uuid: string;\n chatType: string;\n title: string | null;\n threadId: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ConciergeMessage {\n id: string;\n role: string;\n content: string;\n createdAt: string | null;\n toolCalls: any[] | null;\n toolCallId: string | null;\n}\n\nfunction baseUrl(ctx: AuthenticatedContext): string {\n return `${ctx.envConfig.apiUrl}/api/v2/concierge`;\n}\n\nfunction authHeaders(ctx: AuthenticatedContext): Record<string, string> {\n return {\n Authorization: `Bearer ${ctx.accessToken}`,\n 'Content-Type': 'application/json',\n };\n}\n\nfunction toCamelChat(raw: any): ConciergeChat {\n return {\n id: raw.id,\n uuid: raw.uuid,\n chatType: raw.chat_type,\n title: raw.title,\n threadId: raw.thread_id,\n createdAt: raw.created_at,\n updatedAt: raw.updated_at,\n };\n}\n\nfunction toCamelMessage(raw: any): ConciergeMessage {\n return {\n id: raw.id,\n role: raw.role,\n content: raw.content ?? '',\n createdAt: raw.created_at ?? null,\n toolCalls: raw.tool_calls ?? null,\n toolCallId: raw.tool_call_id ?? null,\n };\n}\n\nexport async function listConciergeChats(ctx: AuthenticatedContext): Promise<ConciergeChat[]> {\n const res = await fetch(`${baseUrl(ctx)}/chats`, { headers: authHeaders(ctx) });\n if (!res.ok) throw new Error(`Failed to list concierge chats: ${res.status}`);\n const data = await res.json();\n return (data as any[]).map(toCamelChat);\n}\n\nexport async function createConciergeChat(\n ctx: AuthenticatedContext,\n title?: string\n): Promise<ConciergeChat> {\n const res = await fetch(`${baseUrl(ctx)}/chats`, {\n method: 'POST',\n headers: authHeaders(ctx),\n body: JSON.stringify({ title: title ?? null }),\n });\n if (!res.ok) throw new Error(`Failed to create concierge chat: ${res.status}`);\n return toCamelChat(await res.json());\n}\n\nexport async function getConciergeChat(\n ctx: AuthenticatedContext,\n chatId: number\n): Promise<ConciergeChat> {\n const res = await fetch(`${baseUrl(ctx)}/chats/${chatId}`, { headers: authHeaders(ctx) });\n if (!res.ok) throw new Error(`Failed to get concierge chat ${chatId}: ${res.status}`);\n return toCamelChat(await res.json());\n}\n\nexport async function getConciergeChatMessages(\n ctx: AuthenticatedContext,\n chatId: number\n): Promise<ConciergeMessage[]> {\n const res = await fetch(`${baseUrl(ctx)}/chats/${chatId}/messages`, {\n headers: authHeaders(ctx),\n });\n if (!res.ok)\n throw new Error(`Failed to get concierge messages for chat ${chatId}: ${res.status}`);\n const data = await res.json();\n return (data as any[]).map(toCamelMessage);\n}\n","import type { DomainDef } from '../lib/types';\nimport { requireAuth } from '../lib/context';\nimport { outputData, COL } from '../lib/output';\nimport { listConciergeChats, getConciergeChatMessages } from '../lib/concierge-api';\n\nconst CHAT_COLUMNS = [\n COL.id(),\n COL.uuid(),\n { header: 'TITLE', getValue: (c: any) => c.title ?? '' },\n { header: 'UPDATED', getValue: (c: any) => c.updatedAt ?? '' },\n];\n\nconst MESSAGE_COLUMNS = [\n { header: 'ID', getValue: (m: any) => m.id },\n { header: 'ROLE', getValue: (m: any) => m.role },\n { header: 'CONTENT', getValue: (m: any) => (m.content || '').slice(0, 120) },\n];\n\nexport const conciergeDomain: DomainDef = {\n name: 'concierge',\n description: 'Concierge chat management',\n commands: [\n {\n path: ['concierge', 'list'],\n description: 'List concierge chats',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const auth = requireAuth(ctx);\n const chats = await listConciergeChats(auth);\n outputData(chats, auth, CHAT_COLUMNS);\n },\n },\n {\n path: ['concierge', 'messages'],\n description: 'Show messages for a concierge chat',\n requiresWorkspace: false,\n args: [{ name: 'id', aliases: ['chat-id'], description: 'Chat ID', required: true }],\n handler: async ({ ctx, args }) => {\n const auth = requireAuth(ctx);\n const chatId = Number(args.id);\n if (isNaN(chatId)) throw new Error('--id must be a number');\n const messages = await getConciergeChatMessages(auth, chatId);\n outputData(messages, auth, MESSAGE_COLUMNS);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { CLIError } from '../lib/errors';\nimport { outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS = [COL.id(), COL.name(), COL.description(), COL.enabled()];\n\nconst TOOL_COLUMNS = [COL.id(), COL.name(), COL.description()];\n\nexport const customToolkitsDomain: DomainDef = {\n name: 'custom-toolkits',\n description: 'Manage custom toolkits and their tools',\n commands: [\n ...crudCommands({\n prefix: ['custom-toolkits'],\n entityName: 'custom toolkit',\n listMethod: 'getCustomToolkits',\n getMethod: 'getCustomToolkit',\n createMethod: 'createCustomToolkit',\n updateMethod: 'updateCustomToolkit',\n deleteMethod: 'deleteCustomToolkit',\n columns: COLUMNS,\n }),\n {\n path: ['custom-toolkits', 'enable'],\n description: 'Enable a custom toolkit',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Custom toolkit ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.enableCustomToolkit(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['custom-toolkits', 'disable'],\n description: 'Disable a custom toolkit',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Custom toolkit ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.disableCustomToolkit(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n // Tools — nested resource requiring toolkitId\n {\n path: ['custom-toolkits', 'tools', 'create'],\n description: 'Create a custom tool in a toolkit',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'toolkit-id', description: 'Custom toolkit ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const toolkitId = requireNumber(args, 'toolkit-id');\n const result = await requireAuth(ctx).apiClient.createCustomTool(\n workspace,\n toolkitId,\n data as any\n );\n outputSingle(result, ctx, TOOL_COLUMNS);\n },\n },\n {\n path: ['custom-toolkits', 'tools', 'update'],\n description: 'Update a custom tool',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'toolkit-id', description: 'Custom toolkit ID', required: true },\n { name: 'id', description: 'Tool ID', required: true },\n ],\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const toolkitId = requireNumber(args, 'toolkit-id');\n const toolId = requireNumber(args, 'id');\n const result = await requireAuth(ctx).apiClient.updateCustomTool(\n workspace,\n toolkitId,\n toolId,\n data as any\n );\n outputSingle(result, ctx, TOOL_COLUMNS);\n },\n },\n {\n path: ['custom-toolkits', 'tools', 'delete'],\n description: 'Delete a custom tool',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'toolkit-id', description: 'Custom toolkit ID', required: true },\n { name: 'id', description: 'Tool ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const toolkitId = requireNumber(args, 'toolkit-id');\n const toolId = requireNumber(args, 'id');\n await requireAuth(ctx).apiClient.deleteCustomTool(workspace, toolkitId, toolId);\n process.stdout.write(`Deleted custom tool ${toolId}\\n`);\n },\n },\n ],\n};\n","import { type DomainDef, requireString } from '../lib/types';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS = [\n { header: 'SLUG', getValue: (item: any) => item.slug ?? '' },\n COL.name(),\n COL.description(),\n];\n\nexport const featuresDomain: DomainDef = {\n name: 'features',\n description: 'List available features',\n commands: [\n {\n path: ['features', 'list'],\n description: 'List all available features',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getFeatureRegistry();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['features', 'get'],\n description: 'Get a feature by slug',\n requiresWorkspace: false,\n args: [{ name: 'slug', description: 'Feature slug', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.getFeatureBySlug(\n requireString(args, 'slug')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['features', 'workspace'],\n description: 'List available features for a workspace',\n requiresWorkspace: true,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getAvailableWorkspaceFeatures();\n outputData(result, ctx, COLUMNS);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'EMAIL', getValue: (item: any) => item.email_address ?? '' },\n COL.status(),\n];\n\nconst EMAIL_COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'SUBJECT', getValue: (item: any) => item.subject ?? '' },\n { header: 'FROM', getValue: (item: any) => item.from_address ?? '' },\n { header: 'DATE', getValue: (item: any) => item.received_at ?? '' },\n { header: 'READ', getValue: (item: any) => String(item.is_read ?? '') },\n];\n\nexport const inboxesDomain: DomainDef = {\n name: 'inboxes',\n description: 'Manage email inboxes',\n commands: [\n ...crudCommands({\n prefix: ['inboxes'],\n entityName: 'inbox',\n listMethod: 'getInboxes',\n getMethod: 'getInbox',\n createMethod: 'createInbox',\n updateMethod: 'updateInbox',\n deleteMethod: 'deleteInbox',\n columns: COLUMNS,\n }),\n {\n path: ['inboxes', 'emails', 'list'],\n description: 'List emails in an inbox',\n requiresWorkspace: true,\n args: [{ name: 'inbox-id', description: 'Inbox ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getInboxEmails(\n workspace,\n requireNumber(args, 'inbox-id')\n );\n outputData(result, ctx, EMAIL_COLUMNS);\n },\n },\n {\n path: ['inboxes', 'emails', 'get'],\n description: 'Get a specific email',\n requiresWorkspace: true,\n args: [\n { name: 'inbox-id', description: 'Inbox ID', required: true },\n { name: 'id', description: 'Email ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getInboxEmail(\n workspace,\n requireNumber(args, 'inbox-id'),\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, EMAIL_COLUMNS);\n },\n },\n {\n path: ['inboxes', 'emails', 'threads'],\n description: 'List email threads in an inbox',\n requiresWorkspace: true,\n args: [{ name: 'inbox-id', description: 'Inbox ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getInboxThreads(\n workspace,\n requireNumber(args, 'inbox-id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['inboxes', 'emails', 'mark-read'],\n description: 'Mark an email as read',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'inbox-id', description: 'Inbox ID', required: true },\n { name: 'id', description: 'Email ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.markEmailAsRead(\n workspace,\n requireNumber(args, 'inbox-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write('Email marked as read\\n');\n },\n },\n {\n path: ['inboxes', 'emails', 'mark-unread'],\n description: 'Mark an email as unread',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'inbox-id', description: 'Inbox ID', required: true },\n { name: 'id', description: 'Email ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.markEmailAsUnread(\n workspace,\n requireNumber(args, 'inbox-id'),\n requireNumber(args, 'id')\n );\n process.stdout.write('Email marked as unread\\n');\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS = [\n COL.id(),\n COL.name(),\n { header: 'URL', getValue: (item: any) => item.url ?? '' },\n COL.enabled(),\n];\n\nexport const mcpServersDomain: DomainDef = {\n name: 'mcp-servers',\n description: 'Manage MCP servers',\n commands: [\n ...crudCommands({\n prefix: ['mcp-servers'],\n entityName: 'MCP server',\n listMethod: 'getMcpServers',\n getMethod: 'getMcpServer',\n createMethod: 'createMcpServer',\n updateMethod: 'updateMcpServer',\n deleteMethod: 'deleteMcpServer',\n columns: COLUMNS,\n }),\n {\n path: ['mcp-servers', 'enable'],\n description: 'Enable an MCP server',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'MCP server ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.enableMcpServer(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['mcp-servers', 'disable'],\n description: 'Disable an MCP server',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'MCP server ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.disableMcpServer(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['mcp-servers', 'tools', 'list'],\n description: 'List tools for an MCP server',\n requiresWorkspace: true,\n args: [{ name: 'mcp-server-id', description: 'MCP server ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getMcpServerTools(\n workspace,\n requireNumber(args, 'mcp-server-id')\n );\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber, requireString } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport type { MemoryType } from '@gravity-rail/client';\nimport { outputData } from '../lib/output';\nimport { listResult } from '../lib/pagination';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n { header: 'KEY', getValue: (item: any) => item.key ?? '' },\n { header: 'TYPE', getValue: (item: any) => item.type ?? 'basic' },\n { header: 'DESCRIPTION', getValue: (item: any) => truncate(item.description ?? '', 60) },\n { header: 'PRIORITY', getValue: (item: any) => item.priority ?? 0 },\n { header: 'UPDATED', getValue: (item: any) => item.updatedAt ?? item.createdAt ?? '' },\n];\n\nfunction truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max - 1) + '…' : s;\n}\n\nexport const memberMemoriesDomain: DomainDef = {\n name: 'member-memories',\n description: 'Manage member persistent memories',\n commands: [\n {\n path: ['member-memories', 'list'],\n description: 'List memories for a member',\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n {\n name: 'type',\n description:\n 'Memory type filter (basic, preferences, semantic, summaries, episodic, all)',\n },\n { name: 'query', description: 'Semantic search query (for AgentCore memory types)' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const memberId = requireNumber(args, 'member-id');\n const type = args.type as MemoryType | 'all' | undefined;\n const query = args.query as string | undefined;\n const result = await requireAuth(ctx).apiClient.getMemberMemories(workspace, memberId, {\n type,\n query,\n });\n outputData(listResult(result, false), ctx, COLUMNS);\n },\n },\n {\n path: ['member-memories', 'delete'],\n description: 'Delete a memory for a member',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'key', description: 'Memory key', required: true },\n {\n name: 'type',\n description: 'Memory type (basic, preferences, semantic, summaries, episodic)',\n },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const memberId = requireNumber(args, 'member-id');\n const key = requireString(args, 'key');\n const type = args.type as MemoryType | undefined;\n await requireAuth(ctx).apiClient.deleteMemberMemory(\n workspace,\n memberId,\n key,\n type ? { type } : undefined\n );\n process.stdout.write(`Deleted memory ${key}\\n`);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { COL } from '../lib/output';\n\nconst COLUMNS = [\n COL.id(),\n COL.name(),\n COL.status(),\n { header: 'DUE DATE', getValue: (item: any) => item.due_date ?? '' },\n];\n\nexport const milestonesDomain: DomainDef = {\n name: 'milestones',\n description: 'Manage milestones',\n commands: [\n ...crudCommands({\n prefix: ['milestones'],\n entityName: 'milestone',\n listMethod: 'getMilestones',\n getMethod: 'getMilestone',\n createMethod: 'createMilestone',\n updateMethod: 'updateMilestone',\n deleteMethod: 'deleteMilestone',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { COL } from '../lib/output';\n\nconst COLUMNS = [\n COL.id(),\n COL.name(),\n { header: 'TYPE', getValue: (item: any) => item.noticeType ?? '' },\n COL.enabled(),\n];\n\nexport const notificationRulesDomain: DomainDef = {\n name: 'notification-rules',\n description: 'Manage notification rules',\n commands: [\n ...crudCommands({\n prefix: ['notification-rules'],\n entityName: 'notification rule',\n listMethod: 'getNotificationRules',\n createMethod: 'createNotificationRule',\n updateMethod: 'updateNotificationRule',\n deleteMethod: 'deleteNotificationRule',\n columns: COLUMNS,\n }),\n ],\n};\n","import { type DomainDef, requireString } from '../lib/types';\nimport { outputSingle, outputData } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nexport const oauthDomain: DomainDef = {\n name: 'oauth',\n description: 'Manage OAuth connections',\n commands: [\n {\n path: ['oauth', 'status'],\n description: 'Get OAuth connection status for a provider',\n requiresWorkspace: false,\n args: [{ name: 'provider', description: 'OAuth provider name', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.getOAuthConnectionStatus(\n requireString(args, 'provider') as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['oauth', 'auth-url'],\n description: 'Get OAuth authorization URL for a provider',\n requiresWorkspace: false,\n args: [{ name: 'provider', description: 'OAuth provider name', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.getOAuthAuthorizationUrl(\n requireString(args, 'provider') as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['oauth', 'disconnect'],\n description: 'Disconnect an OAuth provider',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'provider', description: 'OAuth provider name', required: true }],\n handler: async ({ ctx, args }) => {\n const provider = requireString(args, 'provider');\n await requireAuth(ctx).apiClient.disconnectOAuthProvider(provider as any);\n process.stdout.write(`Disconnected OAuth provider ${provider}\\n`);\n },\n },\n {\n path: ['oauth', 'scopes'],\n description: 'List available OAuth scopes',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getAvailableScopes();\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS = [COL.id(), COL.name(), COL.description()];\n\nexport const operatorGroupsDomain: DomainDef = {\n name: 'operator-groups',\n description: 'Manage operator groups',\n commands: [\n ...crudCommands({\n prefix: ['operator-groups'],\n entityName: 'operator group',\n listMethod: 'getOperatorGroups',\n getMethod: 'getOperatorGroup',\n createMethod: 'createOperatorGroup',\n updateMethod: 'updateOperatorGroup',\n deleteMethod: 'deleteOperatorGroup',\n columns: COLUMNS,\n }),\n {\n path: ['operator-groups', 'add-member'],\n description: 'Add a member to an operator group',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'id', description: 'Operator group ID', required: true },\n { name: 'member-id', description: 'Member ID to add', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.addGroupMember(\n workspace,\n requireNumber(args, 'id'),\n { member_id: requireNumber(args, 'member-id') } as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['operator-groups', 'remove-member'],\n description: 'Remove a member from an operator group',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'id', description: 'Operator group ID', required: true },\n { name: 'member-id', description: 'Member ID to remove', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.removeGroupMember(\n workspace,\n requireNumber(args, 'id'),\n requireNumber(args, 'member-id')\n );\n process.stdout.write('Member removed from group\\n');\n },\n },\n {\n path: ['operator-groups', 'live'],\n description: 'List live operators',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getLiveOperators(workspace);\n outputData(result, ctx);\n },\n },\n {\n path: ['operator-groups', 'presence'],\n description: 'Get presence status',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getPresenceStatus(workspace);\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import type { OrgDomain } from '@gravity-rail/sdk';\nimport { requireAuth, type AuthenticatedContext } from '../lib/context';\nimport { CLIError } from '../lib/errors';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle } from '../lib/output';\nimport type { CommandDef, DomainDef, ParsedArgs } from '../lib/types';\n\ntype OrgMembership = Awaited<\n ReturnType<AuthenticatedContext['apiClient']['getMyOrganizations']>\n>[number];\n\nconst ORG_COLUMNS: TableColumn<OrgMembership>[] = [\n { header: 'ID', getValue: (item) => String(item.organizationId ?? '') },\n { header: 'NAME', getValue: (item) => item.organizationName || '' },\n { header: 'ROLE', getValue: (item) => item.role || '' },\n];\n\nconst ORG_DOMAIN_COLUMNS: TableColumn<OrgDomain>[] = [\n { header: 'UUID', getValue: (item) => item.uuid ?? '' },\n { header: 'DOMAIN', getValue: (item) => item.domain ?? '' },\n { header: 'OWNERSHIP', getValue: (item) => item.ownershipStatus ?? '' },\n { header: 'EMAIL', getValue: (item) => item.emailStatus ?? '-' },\n { header: 'SITE', getValue: (item) => item.siteStatus ?? '-' },\n { header: 'TXT HOST', getValue: (item) => item.ownershipDnsRecord?.host ?? '' },\n {\n header: 'TXT VALUE',\n getValue: (item) => item.ownershipDnsRecord?.value ?? '',\n maxWidth: 80,\n },\n];\n\nfunction requireOrgId(args: ParsedArgs): string {\n const val = args['org-uuid'] ?? args.org;\n if (typeof val !== 'string' || !val) {\n throw new CLIError('Missing required argument: --org-uuid');\n }\n return val;\n}\n\nfunction requireDomainUuid(args: ParsedArgs): string {\n const val = args['domain-uuid'] ?? args.uuid;\n if (typeof val !== 'string' || !val) {\n throw new CLIError('Missing required argument: --domain-uuid');\n }\n return val;\n}\n\nfunction requireDomain(args: ParsedArgs): string {\n const val = args.domain;\n if (typeof val !== 'string' || !val) {\n throw new CLIError('Missing required argument: --domain');\n }\n return val;\n}\n\nconst ORG_UUID_ARG = {\n name: 'org-uuid',\n aliases: ['org'],\n description: 'Organization UUID or ID',\n required: true,\n};\n\nconst DOMAIN_UUID_ARG = {\n name: 'domain-uuid',\n aliases: ['domain-id'],\n description: 'OrgDomain UUID',\n required: true,\n};\n\nfunction pluralize(count: number, singular: string, plural = `${singular}s`): string {\n return count === 1 ? singular : plural;\n}\n\nfunction emailVerifyCommand(path: string[], description: string): CommandDef {\n return {\n path,\n description,\n mutates: true,\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: [\n `yarn gr ${path.join(' ')} --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --allow-write`,\n ],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.verifyOrgDomainEmail(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n };\n}\n\nfunction siteVerifyCommand(path: string[], description: string): CommandDef {\n return {\n path,\n description,\n mutates: true,\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: [\n `yarn gr ${path.join(' ')} --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --allow-write`,\n ],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.verifyOrgDomainSite(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n };\n}\n\nfunction registerDomainCommand(path: string[]): CommandDef {\n return {\n path,\n description: 'Register an organization domain and return ownership TXT instructions',\n mutates: true,\n requiresWorkspace: false,\n args: [\n ORG_UUID_ARG,\n { name: 'domain', description: 'Domain to register, e.g. example.com', required: true },\n ],\n examples: [\n `yarn gr ${path.join(' ')} --org-uuid $ORG_UUID --domain example.com --allow-write`,\n ],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.registerOrgDomain(\n requireOrgId(hctx.args),\n requireDomain(hctx.args)\n );\n outputSingle(result, hctx.ctx, ORG_DOMAIN_COLUMNS);\n },\n };\n}\n\nconst domainCommands: CommandDef[] = [\n {\n path: ['org', 'domains', 'list'],\n description: 'List domains registered to an organization',\n requiresWorkspace: false,\n args: [ORG_UUID_ARG],\n examples: ['yarn gr org domains list --org-uuid $ORG_UUID'],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.listOrgDomains(\n requireOrgId(hctx.args)\n );\n outputData(result, hctx.ctx, ORG_DOMAIN_COLUMNS);\n },\n },\n {\n path: ['org', 'domains', 'get'],\n description: 'Get a registered organization domain',\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: ['yarn gr org domains get --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID'],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.getOrgDomain(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx, ORG_DOMAIN_COLUMNS);\n },\n },\n registerDomainCommand(['org', 'domains', 'register']),\n registerDomainCommand(['org', 'domains', 'create']),\n {\n path: ['org', 'domains', 'verify-ownership'],\n description: 'Verify domain ownership by checking the _gravity-verify TXT record',\n mutates: true,\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: [\n 'yarn gr org domains verify-ownership --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --allow-write',\n ],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.verifyOrgDomainOwnership(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n },\n {\n path: ['org', 'domains', 'delete'],\n description: 'Delete a registered organization domain',\n mutates: true,\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: [\n 'yarn gr org domains delete --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --allow-write',\n ],\n handler: async (hctx) => {\n const domainUuid = requireDomainUuid(hctx.args);\n await requireAuth(hctx.ctx).apiClient.deleteOrgDomain(requireOrgId(hctx.args), domainUuid);\n process.stdout.write(`Deleted org domain ${domainUuid}\\n`);\n },\n },\n {\n path: ['org', 'domains', 'email', 'enable'],\n description: 'Enable email DNS records on a verified organization domain',\n mutates: true,\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: [\n 'yarn gr org domains email enable --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --allow-write',\n ],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.enableOrgDomainEmail(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n },\n {\n path: ['org', 'domains', 'email', 'get'],\n description: 'Get email DNS setup and status for an organization domain',\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: ['yarn gr org domains email get --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID'],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.getOrgDomainEmail(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n },\n emailVerifyCommand(\n ['org', 'domains', 'email', 'verify'],\n 'Verify email DNS records, including MX'\n ),\n emailVerifyCommand(\n ['org', 'domains', 'email', 'verify-mx'],\n 'Verify email DNS records, including MX'\n ),\n {\n path: ['org', 'domains', 'email', 'disable'],\n description: 'Disable email on an organization domain',\n mutates: true,\n requiresWorkspace: false,\n args: [\n ORG_UUID_ARG,\n DOMAIN_UUID_ARG,\n {\n name: 'confirm',\n description: 'Confirm removal of inbox routing that depends on this domain',\n isFlag: true,\n },\n ],\n examples: [\n 'yarn gr org domains email disable --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --confirm --allow-write',\n ],\n handler: async (hctx) => {\n const domainUuid = requireDomainUuid(hctx.args);\n const result = await requireAuth(hctx.ctx).apiClient.disableOrgDomainEmail(\n requireOrgId(hctx.args),\n domainUuid,\n hctx.args.confirm === true\n );\n if (!result.ok) {\n const { inboxCount } = result.impact;\n throw new CLIError(\n `Email is still used by ${inboxCount} ${pluralize(\n inboxCount,\n 'inbox',\n 'inboxes'\n )}. Re-run with --confirm to disable it anyway.`\n );\n }\n process.stdout.write(`Disabled email for org domain ${domainUuid}\\n`);\n },\n },\n {\n path: ['org', 'domains', 'site', 'enable'],\n description: 'Enable custom site CNAME verification on a verified organization domain',\n mutates: true,\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: [\n 'yarn gr org domains site enable --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --allow-write',\n ],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.enableOrgDomainSite(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n },\n {\n path: ['org', 'domains', 'site', 'get'],\n description: 'Get custom site CNAME setup and status for an organization domain',\n requiresWorkspace: false,\n args: [ORG_UUID_ARG, DOMAIN_UUID_ARG],\n examples: ['yarn gr org domains site get --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID'],\n handler: async (hctx) => {\n const result = await requireAuth(hctx.ctx).apiClient.getOrgDomainSite(\n requireOrgId(hctx.args),\n requireDomainUuid(hctx.args)\n );\n outputSingle(result, hctx.ctx);\n },\n },\n siteVerifyCommand(\n ['org', 'domains', 'site', 'verify'],\n 'Verify the site CNAME points at Gravity Rail'\n ),\n siteVerifyCommand(\n ['org', 'domains', 'site', 'verify-cname'],\n 'Verify the site CNAME points at Gravity Rail'\n ),\n {\n path: ['org', 'domains', 'site', 'disable'],\n description: 'Disable custom site routing on an organization domain',\n mutates: true,\n requiresWorkspace: false,\n args: [\n ORG_UUID_ARG,\n DOMAIN_UUID_ARG,\n {\n name: 'confirm',\n description: 'Confirm removal of site mappings that depend on this domain',\n isFlag: true,\n },\n ],\n examples: [\n 'yarn gr org domains site disable --org-uuid $ORG_UUID --domain-uuid $DOMAIN_UUID --confirm --allow-write',\n ],\n handler: async (hctx) => {\n const domainUuid = requireDomainUuid(hctx.args);\n const result = await requireAuth(hctx.ctx).apiClient.disableOrgDomainSite(\n requireOrgId(hctx.args),\n domainUuid,\n hctx.args.confirm === true\n );\n if (!result.ok) {\n const { siteCount } = result.impact;\n throw new CLIError(\n `Site routing is still used by ${siteCount} ${pluralize(\n siteCount,\n 'site'\n )}. Re-run with --confirm to disable it anyway.`\n );\n }\n process.stdout.write(`Disabled site routing for org domain ${domainUuid}\\n`);\n },\n },\n];\n\nexport const orgDomain: DomainDef = {\n name: 'org',\n description: 'Organization membership and domains',\n commands: [\n {\n path: ['org', 'list'],\n description: 'List my organizations',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getMyOrganizations();\n outputData(result, ctx, ORG_COLUMNS);\n },\n },\n ...domainCommands,\n ],\n};\n","/**\n * Organization-scoped phone number management CLI commands.\n *\n * Covers the /api/v2/o/{org_uuid}/phone-numbers/ routes:\n * - list, search, purchase, assign, reassign, release, delete\n */\nimport { OrgApi } from '@gravity-rail/sdk';\nimport { requireAuth } from '../lib/context';\nimport { CLIError } from '../lib/errors';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle } from '../lib/output';\nimport type { CommandDef, CommandHandlerContext, DomainDef } from '../lib/types';\n\nfunction getOrgApi(hctx: CommandHandlerContext): OrgApi {\n const ctx = requireAuth(hctx.ctx);\n return new OrgApi(ctx.accessToken, ctx.envConfig.apiUrl);\n}\n\ntype AnyRecord = Record<string, any>;\n\nconst PROVIDER_PHONE_COLUMNS: TableColumn<AnyRecord>[] = [\n { header: 'ID', getValue: (p) => String(p.id ?? '') },\n { header: 'UUID', getValue: (p) => (p.uuid ?? '').slice(0, 8) },\n { header: 'Phone', getValue: (p) => p.phoneNumber ?? '' },\n { header: 'Type', getValue: (p) => p.phoneNumberType ?? '' },\n { header: 'Assigned', getValue: (p) => String(p.isAssigned ?? false) },\n { header: 'Workspace', getValue: (p) => p.workspaceName ?? '-' },\n];\n\nconst AVAILABLE_PHONE_COLUMNS: TableColumn<AnyRecord>[] = [\n { header: 'Phone', getValue: (p) => p.phoneNumber ?? '' },\n { header: 'Name', getValue: (p) => p.friendlyName ?? '' },\n { header: 'Locality', getValue: (p) => p.locality ?? '' },\n { header: 'Region', getValue: (p) => p.region ?? '' },\n { header: 'Type', getValue: (p) => p.phoneNumberType ?? '' },\n];\n\nfunction requireOrgUuid(args: Record<string, any>): string {\n const val = args['org-uuid'] ?? args['org'];\n if (typeof val !== 'string' || !val) {\n throw new CLIError('Missing required argument: --org-uuid');\n }\n return val;\n}\n\nconst commands: CommandDef[] = [\n {\n path: ['org', 'phone-numbers', 'list'],\n description: 'List all phone numbers owned by an organization',\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n ],\n requiresWorkspace: false,\n columns: PROVIDER_PHONE_COLUMNS as TableColumn<unknown>[],\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const result = await getOrgApi(hctx).listPhoneNumbers(orgUuid);\n outputData(result, hctx.ctx, PROVIDER_PHONE_COLUMNS);\n },\n },\n {\n path: ['org', 'phone-numbers', 'search'],\n description: 'Search for available phone numbers to purchase',\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n { name: 'number-type', description: 'Number type: local or toll_free', default: 'local' },\n { name: 'area-code', description: 'Area code filter' },\n { name: 'contains', description: 'Phone number pattern to match' },\n { name: 'limit', description: 'Maximum results (default: 20)' },\n ],\n requiresWorkspace: false,\n columns: AVAILABLE_PHONE_COLUMNS as TableColumn<unknown>[],\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const result = await getOrgApi(hctx).searchPhoneNumbers(orgUuid, {\n numberType: (hctx.args['number-type'] as 'local' | 'toll_free') ?? 'local',\n areaCode: hctx.args['area-code'] as string | undefined,\n contains: hctx.args.contains as string | undefined,\n limit: hctx.args.limit ? Number(hctx.args.limit) : undefined,\n });\n outputData(result, hctx.ctx, AVAILABLE_PHONE_COLUMNS);\n },\n },\n {\n path: ['org', 'phone-numbers', 'purchase'],\n description: 'Purchase a phone number from Twilio for this org',\n mutates: true,\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n { name: 'phone-number', description: 'E.164 phone number to purchase', required: true },\n { name: 'number-type', description: 'Number type: local or toll_free', default: 'local' },\n ],\n requiresWorkspace: false,\n columns: PROVIDER_PHONE_COLUMNS as TableColumn<unknown>[],\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const phoneNumber = hctx.args['phone-number'] as string;\n if (!phoneNumber) throw new CLIError('Missing required argument: --phone-number');\n const numberType = (hctx.args['number-type'] as 'local' | 'toll_free') ?? 'local';\n const result = await getOrgApi(hctx).purchasePhoneNumber(orgUuid, phoneNumber, numberType);\n outputSingle(result, hctx.ctx, PROVIDER_PHONE_COLUMNS);\n },\n },\n {\n path: ['org', 'phone-numbers', 'assign'],\n description: 'Assign an org phone number to a workspace',\n mutates: true,\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n { name: 'provider-phone-uuid', description: 'Provider phone UUID', required: true },\n { name: 'workspace-uuid', description: 'Target workspace UUID', required: true },\n ],\n requiresWorkspace: false,\n columns: PROVIDER_PHONE_COLUMNS as TableColumn<unknown>[],\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const providerPhoneUuid = hctx.args['provider-phone-uuid'] as string;\n const workspaceUuid = hctx.args['workspace-uuid'] as string;\n if (!providerPhoneUuid)\n throw new CLIError('Missing required argument: --provider-phone-uuid');\n if (!workspaceUuid) throw new CLIError('Missing required argument: --workspace-uuid');\n const result = await getOrgApi(hctx).assignPhoneToWorkspace(\n orgUuid,\n providerPhoneUuid,\n workspaceUuid\n );\n outputSingle(result, hctx.ctx, PROVIDER_PHONE_COLUMNS);\n process.stdout.write(\n '\\nCreate a workspace phone linked to this provider number (sets Twilio webhooks):\\n' +\n ` gr phone-numbers create -w ${workspaceUuid} --allow-write ` +\n `--data '{\"name\":\"…\",\"providerPhoneUuid\":\"${providerPhoneUuid}\"}'\\n`\n );\n },\n },\n {\n path: ['org', 'phone-numbers', 'reassign'],\n description: 'Reassign a phone number to a different workspace',\n mutates: true,\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n { name: 'provider-phone-uuid', description: 'Provider phone UUID', required: true },\n { name: 'new-workspace-uuid', description: 'New workspace UUID', required: true },\n ],\n requiresWorkspace: false,\n columns: PROVIDER_PHONE_COLUMNS as TableColumn<unknown>[],\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const providerPhoneUuid = hctx.args['provider-phone-uuid'] as string;\n const newWorkspaceUuid = hctx.args['new-workspace-uuid'] as string;\n if (!providerPhoneUuid)\n throw new CLIError('Missing required argument: --provider-phone-uuid');\n if (!newWorkspaceUuid)\n throw new CLIError('Missing required argument: --new-workspace-uuid');\n const result = await getOrgApi(hctx).reassignPhone(\n orgUuid,\n providerPhoneUuid,\n newWorkspaceUuid\n );\n outputSingle(result, hctx.ctx, PROVIDER_PHONE_COLUMNS);\n },\n },\n {\n path: ['org', 'phone-numbers', 'release'],\n description: 'Release a phone number from its current workspace',\n mutates: true,\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n { name: 'provider-phone-uuid', description: 'Provider phone UUID', required: true },\n ],\n requiresWorkspace: false,\n columns: PROVIDER_PHONE_COLUMNS as TableColumn<unknown>[],\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const providerPhoneUuid = hctx.args['provider-phone-uuid'] as string;\n if (!providerPhoneUuid)\n throw new CLIError('Missing required argument: --provider-phone-uuid');\n const result = await getOrgApi(hctx).releasePhone(orgUuid, providerPhoneUuid);\n outputSingle(result, hctx.ctx, PROVIDER_PHONE_COLUMNS);\n },\n },\n {\n path: ['org', 'phone-numbers', 'delete'],\n description: 'Delete a phone number from the org (releases from Twilio)',\n mutates: true,\n args: [\n { name: 'org-uuid', aliases: ['org'], description: 'Organization UUID', required: true },\n { name: 'provider-phone-uuid', description: 'Provider phone UUID', required: true },\n ],\n requiresWorkspace: false,\n handler: async (hctx) => {\n const orgUuid = requireOrgUuid(hctx.args);\n const providerPhoneUuid = hctx.args['provider-phone-uuid'] as string;\n if (!providerPhoneUuid)\n throw new CLIError('Missing required argument: --provider-phone-uuid');\n await getOrgApi(hctx).deletePhoneNumber(orgUuid, providerPhoneUuid);\n console.log('Phone number deleted successfully');\n },\n },\n];\n\nexport const orgPhoneNumbersDomain: DomainDef = {\n name: 'org',\n description: 'Organization management',\n commands,\n};\n","import { type DomainDef, requireNumberFrom, requireString } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { crudCommands } from '../lib/crud';\nimport { outputData, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'NUMBER', getValue: (item: any) => item.phone_number ?? '' },\n { header: 'LABEL', getValue: (item: any) => item.label ?? '' },\n COL.status(),\n];\n\nexport const phoneNumbersDomain: DomainDef = {\n name: 'phone-numbers',\n description: 'Manage phone numbers',\n commands: [\n ...crudCommands({\n prefix: ['phone-numbers'],\n entityName: 'phone number',\n listMethod: 'getPhoneNumbers',\n getMethod: 'getPhoneNumber',\n createMethod: 'createPhoneNumber',\n updateMethod: 'updatePhoneNumber',\n archiveMethod: 'archivePhoneNumber',\n columns: COLUMNS,\n }),\n {\n path: ['phone-numbers', 'available'],\n description: 'List available phone numbers for purchase',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getAvailablePhoneNumbers(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['phone-numbers', 'link'],\n description: 'Link a workspace phone number to a provider (org) phone',\n mutates: true,\n requiresWorkspace: true,\n args: [\n {\n name: 'phone-number-id',\n aliases: ['id'],\n description: 'Workspace phone number ID',\n required: true,\n },\n { name: 'provider-phone-uuid', description: 'Provider phone UUID', required: true },\n ],\n examples: [\n 'gr phone-numbers link -w $WID --id 1 --provider-phone-uuid <uuid> --allow-write',\n ],\n handler: async ({ ctx, workspace, args }) => {\n const auth = requireAuth(ctx);\n const id = requireNumberFrom(args, 'phone-number-id', 'id');\n const providerPhoneUuid = requireString(args, 'provider-phone-uuid');\n const result = await auth.apiClient.linkPhoneNumber(workspace, id, providerPhoneUuid);\n outputData([result], auth, COLUMNS);\n },\n },\n {\n path: ['phone-numbers', 'request'],\n description: 'Request a phone number',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n const result = await requireAuth(ctx).apiClient.requestPhoneNumber(\n workspace,\n data as any\n );\n outputData([result], ctx, COLUMNS);\n },\n },\n {\n path: ['phone-numbers', 'calls', 'list'],\n description: 'List calls for a phone number',\n requiresWorkspace: true,\n args: [\n {\n name: 'phone-number-id',\n aliases: ['id'],\n description: 'Phone number ID',\n required: true,\n },\n { name: 'page', description: 'Page number' },\n { name: 'page-size', description: 'Page size' },\n { name: 'status', description: 'Filter by status' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const status = args.status as string | undefined;\n const result = await requireAuth(ctx).apiClient.getPhoneNumberCalls(\n workspace,\n requireNumberFrom(args, 'phone-number-id', 'id'),\n args.page ? Number(args.page) : undefined,\n args['page-size'] ? Number(args['page-size']) : undefined,\n status ? { status } : undefined\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['phone-numbers', 'messages', 'list'],\n description: 'List messages for a phone number',\n requiresWorkspace: true,\n args: [\n {\n name: 'phone-number-id',\n aliases: ['id'],\n description: 'Phone number ID',\n required: true,\n },\n { name: 'page', description: 'Page number' },\n { name: 'page-size', description: 'Page size' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getPhoneNumberMessages(\n workspace,\n requireNumberFrom(args, 'phone-number-id', 'id'),\n args.page ? Number(args.page) : undefined,\n args['page-size'] ? Number(args['page-size']) : undefined\n );\n outputData(result, ctx);\n },\n },\n ],\n};\n","import type { GravityRailClient } from '@gravity-rail/client';\nimport type {\n CreatePronunciationEntryFormData,\n UpdatePronunciationEntryFormData,\n} from '@gravity-rail/sdk';\nimport { CLIError } from './errors';\n\n/** Resolve organization UUID from a workspace UUID (for org-scoped API routes). */\nexport async function resolveOrgUuidFromWorkspace(\n apiClient: GravityRailClient,\n workspaceUuid: string\n): Promise<string> {\n const workspace = await apiClient.getWorkspace(workspaceUuid);\n const orgUuid = workspace.organizationUuid;\n if (!orgUuid) {\n throw new CLIError(\n 'Workspace has no organization; pass --org-uuid for organization-scoped commands'\n );\n }\n return orgUuid;\n}\n\nexport function normalizePronunciationCreatePayload(\n data: unknown\n): CreatePronunciationEntryFormData {\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n throw new CLIError('JSON body required with term and respelling (--data or --file)');\n }\n const raw = data as Record<string, unknown>;\n const term = raw.term ?? raw.word;\n const respelling = raw.respelling ?? raw.pronunciation;\n if (typeof term !== 'string' || !term) {\n throw new CLIError('Payload requires term (alias: word)');\n }\n if (typeof respelling !== 'string' || !respelling) {\n throw new CLIError('Payload requires respelling (alias: pronunciation)');\n }\n const payload: CreatePronunciationEntryFormData = { term, respelling };\n if (raw.accountId !== undefined && raw.accountId !== null) {\n payload.accountId = Number(raw.accountId);\n }\n return payload;\n}\n\nexport function normalizePronunciationUpdatePayload(\n data: unknown\n): UpdatePronunciationEntryFormData {\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n throw new CLIError('JSON body required (--data or --file)');\n }\n const raw = data as Record<string, unknown>;\n const respelling = raw.respelling ?? raw.pronunciation;\n if (typeof respelling !== 'string' || !respelling) {\n throw new CLIError('Payload requires respelling (alias: pronunciation)');\n }\n return { respelling };\n}\n","import { type DomainDef, requireString, requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\nimport {\n normalizePronunciationCreatePayload,\n normalizePronunciationUpdatePayload,\n resolveOrgUuidFromWorkspace,\n} from '../lib/resolve-org';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n { header: 'TERM', getValue: (item: any) => item.term ?? '' },\n { header: 'RESPELLING', getValue: (item: any) => item.respelling ?? '' },\n { header: 'SCOPE', getValue: (item: any) => item.scope ?? '' },\n];\n\nconst CREATE_EXAMPLES = [\n 'gr pronunciations create -w $WID --data \\'{\"term\":\"Jeeves\",\"respelling\":\"JEEVZ\"}\\' --allow-write',\n ' (aliases: word → term, pronunciation → respelling)',\n];\n\nexport const pronunciationsDomain: DomainDef = {\n name: 'pronunciations',\n description: 'Manage pronunciation entries (org-scoped; -w resolves organization)',\n commands: [\n {\n path: ['pronunciations', 'list'],\n description: 'List pronunciation entries for the workspace organization',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const auth = requireAuth(ctx);\n const orgUuid = await resolveOrgUuidFromWorkspace(auth.apiClient, workspace);\n const result = await auth.apiClient.getPronunciationEntries(orgUuid);\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['pronunciations', 'create'],\n description: 'Create a pronunciation entry (term + respelling)',\n mutates: true,\n requiresWorkspace: true,\n examples: CREATE_EXAMPLES,\n handler: async ({ ctx, workspace, data }) => {\n const auth = requireAuth(ctx);\n const orgUuid = await resolveOrgUuidFromWorkspace(auth.apiClient, workspace);\n const payload = normalizePronunciationCreatePayload(data);\n const result = await auth.apiClient.createPronunciationEntry(orgUuid, payload);\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['pronunciations', 'update'],\n description: 'Update a pronunciation entry',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Pronunciation entry ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const auth = requireAuth(ctx);\n const orgUuid = await resolveOrgUuidFromWorkspace(auth.apiClient, workspace);\n const payload = normalizePronunciationUpdatePayload(data);\n const result = await auth.apiClient.updatePronunciationEntry(\n orgUuid,\n requireNumber(args, 'id'),\n payload\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['pronunciations', 'delete'],\n description: 'Delete a pronunciation entry',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Pronunciation entry ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const auth = requireAuth(ctx);\n const orgUuid = await resolveOrgUuidFromWorkspace(auth.apiClient, workspace);\n const id = requireNumber(args, 'id');\n await auth.apiClient.deletePronunciationEntry(orgUuid, id);\n process.stdout.write(`Deleted pronunciation entry ${id}\\n`);\n },\n },\n {\n path: ['pronunciations', 'my-list'],\n description: 'List my personal pronunciations',\n requiresWorkspace: true,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getMyPronunciations();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['pronunciations', 'my-create'],\n description: 'Create a personal pronunciation',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, data }) => {\n const payload = normalizePronunciationCreatePayload(data);\n const result = await requireAuth(ctx).apiClient.createMyPronunciation(payload);\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['pronunciations', 'suggest'],\n description: 'Get pronunciation suggestions for a word',\n requiresWorkspace: true,\n args: [\n {\n name: 'word',\n aliases: ['term'],\n description: 'Word to get suggestions for',\n required: true,\n },\n ],\n handler: async ({ ctx, args }) => {\n const word =\n typeof args.word === 'string'\n ? args.word\n : typeof args.term === 'string'\n ? args.term\n : requireString(args, 'word');\n const result = await requireAuth(ctx).apiClient.suggestPronunciations(word);\n outputData(result, ctx);\n },\n },\n {\n path: ['pronunciations', 'voices'],\n description: 'Get recommended voices',\n requiresWorkspace: true,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getRecommendedVoices();\n outputData(result, ctx);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport { outputSingle } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nexport const reportsDomain: DomainDef = {\n name: 'reports',\n description: 'View usage reports',\n commands: [\n {\n path: ['reports', 'ai-usage'],\n description: 'Get AI usage report',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getAIUsageReport(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['reports', 'sms-usage'],\n description: 'Get SMS usage report',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getSMSUsageReport(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['reports', 'phone-usage'],\n description: 'Get phone usage report',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getPhoneUsageReport(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['reports', 'voice-usage'],\n description: 'Get voice usage report',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getVoiceUsageReport(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['reports', 'member-usage'],\n description: 'Get usage for a specific member',\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getMemberUsage(\n workspace,\n requireNumber(args, 'member-id')\n );\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { requireNumber } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle, COL } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.status(),\n { header: 'PLAN', getValue: (item: any) => item.plan_name ?? item.plan ?? '' },\n COL.created(),\n];\n\nexport const subscriptionsDomain: DomainDef = {\n name: 'subscriptions',\n description: 'Manage subscriptions',\n commands: [\n {\n path: ['subscriptions', 'list'],\n description: 'List all subscriptions',\n requiresWorkspace: false,\n handler: async ({ ctx }) => {\n const result = await requireAuth(ctx).apiClient.getSubscriptions();\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['subscriptions', 'workspace'],\n description: 'List subscriptions for a workspace',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getWorkspaceSubscriptions(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['subscriptions', 'cancel'],\n description: 'Cancel a subscription',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Subscription ID', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.cancelSubscription(\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['subscriptions', 'reactivate'],\n description: 'Reactivate a cancelled subscription',\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Subscription ID', required: true }],\n handler: async ({ ctx, args }) => {\n const result = await requireAuth(ctx).apiClient.reactivateSubscription(\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['subscriptions', 'update'],\n description: 'Update a subscription',\n mutates: true,\n requiresWorkspace: false,\n args: [{ name: 'id', description: 'Subscription ID', required: true }],\n handler: async ({ ctx, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateSubscription(\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../lib/types';\nimport { outputSingle } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nexport const promptsDomain: DomainDef = {\n name: 'prompts',\n description: 'Inspect and debug LLM prompts',\n commands: [\n {\n path: ['prompts', 'inspect'],\n description: 'Show the full composed prompt for a task or chat, broken into layers',\n requiresWorkspace: true,\n args: [\n { name: 'task-id', description: 'Task ID to inspect (static mode)' },\n { name: 'chat-id', description: 'Chat ID to inspect (live mode)' },\n { name: 'channel', description: 'Channel to simulate (static mode only)' },\n { name: 'turn', description: 'Turn number (chat mode only, default 1)' },\n ],\n examples: [\n 'gr prompts inspect --task-id 42',\n 'gr prompts inspect --task-id 42 --channel phone-voice',\n 'gr prompts inspect --chat-id 789',\n 'gr prompts inspect --chat-id 789 --turn 3',\n ],\n handler: async ({ ctx, workspace, args }) => {\n const taskId = args['task-id'] !== undefined ? requireNumber(args, 'task-id') : undefined;\n const chatId = args['chat-id'] !== undefined ? requireNumber(args, 'chat-id') : undefined;\n\n if (taskId === undefined && chatId === undefined) {\n throw new Error('Provide --task-id or --chat-id');\n }\n if (taskId !== undefined && chatId !== undefined) {\n throw new Error('Provide --task-id or --chat-id, not both');\n }\n\n const channel = (args.channel as string) || undefined;\n const turn = args.turn !== undefined ? requireNumber(args, 'turn') : undefined;\n\n const result = await requireAuth(ctx).apiClient.inspectPrompt(workspace, {\n ...(taskId !== undefined ? { taskId } : { chatId: chatId! }),\n ...(channel ? { channel } : {}),\n ...(turn !== undefined ? { turn } : {}),\n });\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import type { DomainDef, ParsedArgs } from '../lib/types';\nimport { requireString } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { COL, outputData, outputSingle } from '../lib/output';\nimport { requireAuth } from '../lib/context';\n\nconst SUPPORT_COLUMNS: TableColumn<unknown>[] = [\n COL.uuid(),\n { header: 'STATUS', getValue: (item: any) => item.status ?? '' },\n { header: 'TYPE', getValue: (item: any) => item.supportRequestType ?? '' },\n { header: 'SEVERITY', getValue: (item: any) => item.severity ?? '' },\n { header: 'SOURCE', getValue: (item: any) => item.source ?? '' },\n { header: 'CREATED', getValue: (item: any) => (item.createdAt ?? '').slice(0, 19) },\n { header: 'TITLE', getValue: (item: any) => item.title ?? '' },\n];\n\nconst CONTEXT_ARGS = [\n { name: 'workspace', aliases: ['w'], description: 'Workspace UUID' },\n { name: 'org-uuid', description: 'Organization UUID' },\n];\n\nfunction listParams(args: ParsedArgs) {\n return {\n page: args.page ? Number(args.page) : undefined,\n pageSize: args['page-size'] ? Number(args['page-size']) : undefined,\n status: args.status as any,\n supportRequestType: args.type as any,\n severity: args.severity as any,\n source: args.source as any,\n };\n}\n\nfunction requestPayload(data: unknown, args: ParsedArgs) {\n const input = (data ?? {}) as Record<string, unknown>;\n return {\n supportRequestType:\n (input.supportRequestType as string | undefined) ??\n (input.support_request_type as string | undefined) ??\n (args.type as string | undefined) ??\n 'question',\n title: (input.title as string | undefined) ?? requireString(args, 'title'),\n description: (input.description as string | undefined) ?? requireString(args, 'description'),\n severity: (input.severity as string | undefined) ?? (args.severity as string | undefined),\n } as any;\n}\n\nfunction commentPayload(data: unknown, args: ParsedArgs) {\n const input = (data ?? {}) as Record<string, unknown>;\n return {\n body: (input.body as string | undefined) ?? requireString(args, 'body'),\n };\n}\n\nexport const supportDomain: DomainDef = {\n name: 'support',\n description: 'Manage support requests',\n commands: [\n {\n path: ['support', 'list'],\n description: 'List support requests',\n args: [\n ...CONTEXT_ARGS,\n { name: 'status', description: 'Filter by status' },\n { name: 'type', description: 'Filter by type: bug, feature_request, question' },\n { name: 'severity', description: 'Filter by severity' },\n { name: 'source', description: 'Filter by source' },\n { name: 'page', description: 'Page number' },\n { name: 'page-size', description: 'Page size' },\n ],\n columns: SUPPORT_COLUMNS,\n handler: async ({ ctx, args, workspace }) => {\n const client = requireAuth(ctx).apiClient;\n const wid = (args.workspace as string | undefined) ?? workspace;\n const orgUuid = args['org-uuid'] as string | undefined;\n const result = wid\n ? await client.listWorkspaceSupportRequests(wid, listParams(args))\n : orgUuid\n ? await client.listOrgSupportRequests(orgUuid, listParams(args))\n : await client.listSupportRequests(listParams(args));\n outputData(result, ctx, SUPPORT_COLUMNS);\n },\n },\n {\n path: ['support', 'get'],\n description: 'Get a support request',\n args: [\n ...CONTEXT_ARGS,\n { name: 'id', aliases: ['uuid'], description: 'Support request UUID', required: true },\n ],\n handler: async ({ ctx, args, workspace }) => {\n const client = requireAuth(ctx).apiClient;\n const id = requireString(args, 'id');\n const wid = (args.workspace as string | undefined) ?? workspace;\n const orgUuid = args['org-uuid'] as string | undefined;\n const result = wid\n ? await client.getWorkspaceSupportRequest(wid, id)\n : orgUuid\n ? await client.getOrgSupportRequest(orgUuid, id)\n : await client.getSupportRequest(id);\n outputSingle(result, ctx, SUPPORT_COLUMNS);\n },\n },\n {\n path: ['support', 'create'],\n description: 'Create a support request',\n mutates: true,\n args: [\n ...CONTEXT_ARGS,\n { name: 'type', description: 'Request type: bug, feature_request, question' },\n { name: 'title', description: 'Support request title' },\n { name: 'description', description: 'Support request description' },\n { name: 'severity', description: 'Optional severity' },\n ],\n handler: async ({ ctx, args, workspace, data }) => {\n const client = requireAuth(ctx).apiClient;\n const wid = (args.workspace as string | undefined) ?? workspace;\n const orgUuid = args['org-uuid'] as string | undefined;\n const payload = requestPayload(data, args);\n const result = wid\n ? await client.createWorkspaceSupportRequest(wid, payload)\n : orgUuid\n ? await client.createOrgSupportRequest(orgUuid, payload)\n : await client.createSupportRequest(payload);\n outputSingle(result, ctx, SUPPORT_COLUMNS);\n },\n },\n {\n path: ['support', 'comment'],\n description: 'Add a customer comment to a support request',\n mutates: true,\n args: [\n ...CONTEXT_ARGS,\n { name: 'id', aliases: ['uuid'], description: 'Support request UUID', required: true },\n { name: 'body', description: 'Comment body' },\n ],\n handler: async ({ ctx, args, workspace, data }) => {\n const client = requireAuth(ctx).apiClient;\n const id = requireString(args, 'id');\n const wid = (args.workspace as string | undefined) ?? workspace;\n const orgUuid = args['org-uuid'] as string | undefined;\n const payload = commentPayload(data, args);\n const result = wid\n ? await client.commentOnWorkspaceSupportRequest(wid, id, payload)\n : orgUuid\n ? await client.commentOnOrgSupportRequest(orgUuid, id, payload)\n : await client.commentOnSupportRequest(id, payload);\n outputSingle(result, ctx, SUPPORT_COLUMNS);\n },\n },\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport { crudCommands } from '../lib/crud';\nimport { COL } from '../lib/output';\n\nconst COLUMNS = [\n COL.id(),\n COL.name(),\n { header: 'TYPE', getValue: (item: any) => item.type ?? '' },\n COL.status(),\n];\n\nexport const supervisorsDomain: DomainDef = {\n name: 'supervisors',\n description: 'Manage supervisors',\n commands: [\n ...crudCommands({\n prefix: ['supervisors'],\n entityName: 'supervisor',\n listMethod: 'getSupervisors',\n getMethod: 'getSupervisor',\n createMethod: 'createSupervisor',\n updateMethod: 'updateSupervisor',\n deleteMethod: 'deleteSupervisor',\n columns: COLUMNS,\n }),\n ],\n};\n","import type { DomainDef } from '../lib/types';\nimport type { TableColumn } from '../lib/output';\nimport { outputData, outputSingle } from '../lib/output';\nimport { requireNumber } from '../lib/types';\nimport { CLIError } from '../lib/errors';\nimport { requireAuth } from '../lib/context';\n\nconst RUN_COLUMNS: TableColumn<unknown>[] = [\n { header: 'RUN ID', getValue: (item: any) => item.runId ?? '' },\n { header: 'STATUS', getValue: (item: any) => item.status ?? '' },\n { header: 'MODE', getValue: (item: any) => item.mode ?? '' },\n { header: 'TOTAL', getValue: (item: any) => String(item.total ?? 0) },\n { header: 'SYNCED', getValue: (item: any) => String(item.synced ?? 0) },\n { header: 'FAILED', getValue: (item: any) => String(item.failed ?? 0) },\n { header: 'SKIPPED', getValue: (item: any) => String(item.skipped ?? 0) },\n { header: 'DRY RUN', getValue: (item: any) => (item.dryRun ? 'yes' : 'no') },\n { header: 'STARTED', getValue: (item: any) => item.startedAt ?? '' },\n];\n\nconst ITEM_COLUMNS: TableColumn<unknown>[] = [\n { header: 'INDEX', getValue: (item: any) => String(item.index ?? '') },\n { header: 'DIR', getValue: (item: any) => item.direction ?? '' },\n { header: 'STATUS', getValue: (item: any) => item.status ?? '' },\n { header: 'ENTITY', getValue: (item: any) => item.entityType ?? 'member' },\n {\n header: 'MEMBER',\n getValue: (item: any) => (item.memberId != null ? String(item.memberId) : ''),\n },\n { header: 'REMOTE', getValue: (item: any) => item.remoteRecordId ?? '' },\n { header: 'DETAIL', getValue: (item: any) => item.detail ?? '' },\n];\n\nasync function streamSyncRun(response: Response, verbose: boolean): Promise<void> {\n const reader = response.body?.getReader();\n if (!reader) {\n console.error('No response body');\n return;\n }\n\n const decoder = new TextDecoder();\n let buffer = '';\n let lastRun: any = null;\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (!line.startsWith('data: ')) continue;\n try {\n const data = JSON.parse(line.slice(6));\n if (data.type === 'sync_run') {\n lastRun = data;\n if (verbose) {\n const s = data;\n process.stderr.write(\n `\\r ${s.status} — ${s.synced} synced, ${s.failed} failed, ${s.skipped} skipped (${s.total} total)`\n );\n }\n } else if (data.type === 'sync_item') {\n if (verbose) {\n const i = data;\n const detail = i.detail ? ` — ${i.detail}` : '';\n const member = i.memberId != null ? ` member:${i.memberId}` : '';\n const remote = i.remoteRecordId ? ` remote:${i.remoteRecordId}` : '';\n console.error(`\\n [${i.status}] ${i.direction}${member}${remote}${detail}`);\n }\n }\n } catch {\n // Non-JSON line, skip\n }\n }\n }\n\n if (verbose) {\n console.error(''); // newline after progress\n }\n\n if (lastRun) {\n console.log(JSON.stringify(lastRun, null, 2));\n }\n}\n\nexport const syncDomain: DomainDef = {\n name: 'sync',\n description: 'Run and monitor connection syncs',\n commands: [\n {\n path: ['sync', 'run'],\n description: 'Start a sync run and stream progress (SSE)',\n args: [\n { name: 'connection-id', description: 'Connection ID', required: true },\n { name: 'dry-run', description: 'Test sync without making changes', isFlag: true },\n {\n name: 'full-resync',\n description: 'Clear checkpoints and re-sync all records',\n isFlag: true,\n },\n { name: 'quiet', description: 'Only output final result JSON', isFlag: true },\n { name: 'entity-type', description: 'Scope to entity type: member or record' },\n {\n name: 'board-id',\n description: 'Scope to a single board mapping (requires --entity-type)',\n },\n {\n name: 'record-limit',\n description:\n 'Cap the run to a preview sample (1..200). Requires --dry-run and --entity-type.',\n },\n ],\n examples: [\n 'sync run --connection-id 6',\n 'sync run --connection-id 6 --dry-run',\n 'sync run --connection-id 6 --full-resync',\n 'sync run --connection-id 6 --quiet',\n 'sync run --connection-id 6 --entity-type member',\n 'sync run --connection-id 6 --entity-type member --board-id 18406694561',\n 'sync run --connection-id 6 --dry-run --entity-type member --record-limit 20',\n ],\n mutates: true,\n handler: async ({ ctx, args, workspace }) => {\n const connectionId = requireNumber(args, 'connection-id');\n const dryRun = args['dry-run'] === true;\n const fullResync = args['full-resync'] === true;\n const quiet = args['quiet'] === true;\n const VALID_ENTITY_TYPES = ['member', 'record'] as const;\n type ValidEntityType = (typeof VALID_ENTITY_TYPES)[number];\n const rawEntityType = args['entity-type'] as string | undefined;\n let entityType: ValidEntityType | undefined;\n if (rawEntityType) {\n if (!VALID_ENTITY_TYPES.includes(rawEntityType as ValidEntityType)) {\n throw new CLIError(\n `Invalid --entity-type \"${rawEntityType}\". Allowed values: ${VALID_ENTITY_TYPES.join(', ')}`\n );\n }\n entityType = rawEntityType as ValidEntityType;\n }\n const boardId = args['board-id'] as string | undefined;\n const rawRecordLimit = args['record-limit'];\n let recordLimit: number | undefined;\n if (rawRecordLimit !== undefined && rawRecordLimit !== '') {\n const parsed = Number(rawRecordLimit);\n if (!Number.isInteger(parsed) || parsed < 1 || parsed > 200) {\n throw new CLIError(\n `Invalid --record-limit \"${rawRecordLimit}\". Must be an integer between 1 and 200.`\n );\n }\n if (!dryRun) {\n throw new CLIError(\n '--record-limit requires --dry-run: capped runs are preview-only.'\n );\n }\n // Round-2 review: mirror the route-level guard. The engine\n // can't apply a global record cap across heterogeneous\n // entities (member/record/file), so the API rejects a\n // capped run without ``entityType`` with 400. Surface the\n // same message client-side so the operator fails fast\n // before the request goes out.\n if (entityType === undefined) {\n throw new CLIError(\n '--record-limit requires --entity-type: capped previews must target a single entity type.'\n );\n }\n recordLimit = parsed;\n }\n\n // Round-11 review: the route rejects ``resetCheckpoints``\n // combined with ``dryRun`` or ``recordLimit`` (see\n // ``lib/routes/workspace/connection_sync.py`` —\n // \"resetCheckpoints is incompatible with dryRun/recordLimit\").\n // Without this guard ``gr sync run --dry-run --full-resync``\n // and capped previews + ``--full-resync`` always 400 after a\n // network roundtrip. The UI mirrors the same constraint via\n // ``resetCheckpoints: !dryRun && fullResync`` in\n // ``useSyncRunner.ts``; fail fast here so operators see a\n // clear local error instead.\n if (fullResync && (dryRun || recordLimit !== undefined)) {\n throw new CLIError(\n '--full-resync is incompatible with --dry-run / --record-limit: ' +\n 'checkpoint reset must happen on a non-preview run.'\n );\n }\n\n if (!quiet) {\n const flags = [\n dryRun && '(dry run)',\n fullResync && '(full re-sync)',\n entityType && `(${entityType} only)`,\n boardId && `(board ${boardId})`,\n recordLimit !== undefined && `(limit ${recordLimit})`,\n ]\n .filter(Boolean)\n .join(' ');\n console.error(\n `Starting sync for connection ${connectionId}${flags ? ` ${flags}` : ''}...`\n );\n }\n\n const response = await requireAuth(ctx).apiClient.startSyncRun(\n workspace,\n connectionId,\n {\n dryRun,\n resetCheckpoints: fullResync,\n entityType,\n boardId,\n recordLimit,\n }\n );\n\n if (!response.ok) {\n const text = await response.text();\n console.error(`Sync failed: ${response.status} ${text}`);\n process.exit(1);\n }\n\n await streamSyncRun(response, !quiet);\n },\n },\n {\n path: ['sync', 'runs'],\n description: 'List recent sync runs for a connection',\n args: [\n { name: 'connection-id', description: 'Connection ID', required: true },\n { name: 'limit', description: 'Max runs to return' },\n ],\n handler: async ({ ctx, args, workspace }) => {\n const connectionId = requireNumber(args, 'connection-id');\n const limit = args['limit'] ? Number(args['limit']) : 20;\n const runs = await requireAuth(ctx).apiClient.getSyncRuns(\n workspace,\n connectionId,\n limit\n );\n outputData(runs, ctx, RUN_COLUMNS);\n },\n },\n {\n path: ['sync', 'items'],\n description: 'List items for a specific sync run',\n args: [\n { name: 'connection-id', description: 'Connection ID', required: true },\n { name: 'run-id', description: 'Run ID', required: true },\n ],\n handler: async ({ ctx, args, workspace }) => {\n const connectionId = requireNumber(args, 'connection-id');\n const runId = args['run-id'] as string;\n if (!runId) throw new Error('Missing required argument: --run-id');\n const items = await requireAuth(ctx).apiClient.getSyncRunItems(\n workspace,\n connectionId,\n runId\n );\n outputData(items, ctx, ITEM_COLUMNS);\n },\n },\n {\n path: ['sync', 'config'],\n description: 'Get sync configuration for a connection',\n args: [{ name: 'connection-id', description: 'Connection ID', required: true }],\n handler: async ({ ctx, args, workspace }) => {\n const connectionId = requireNumber(args, 'connection-id');\n const config = await requireAuth(ctx).apiClient.getConnectionSyncConfig(\n workspace,\n connectionId\n );\n console.log(JSON.stringify(config, null, 2));\n },\n },\n {\n path: ['sync', 'update-config'],\n description: 'Update sync configuration for a connection',\n args: [{ name: 'connection-id', description: 'Connection ID', required: true }],\n mutates: true,\n examples: [\n 'sync update-config --connection-id 2 --data \\'{\"syncKey\":\"default\",\"entities\":[...]}\\'',\n 'sync update-config --connection-id 2 --file sync-config.json',\n ],\n handler: async ({ ctx, args, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const connectionId = requireNumber(args, 'connection-id');\n const result = await requireAuth(ctx).apiClient.updateConnectionSyncConfig(\n workspace,\n connectionId,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber, requireString } from '../../lib/types';\nimport { outputData, outputSingle, COL } from '../../lib/output';\nimport { requireAuth } from '../../lib/context';\n\nconst COLUMNS = [\n COL.id(),\n COL.name(),\n { header: 'TYPE', getValue: (item: any) => item.type ?? '' },\n COL.status(),\n];\n\nexport const appConnectionsDomain: DomainDef = {\n name: 'app-connections',\n description: 'Manage platform app connections',\n commands: [\n {\n path: ['app-connections', 'available'],\n description: 'List available app connections',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.listAvailableAppConnections(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['app-connections', 'list'],\n description: 'List enabled app connections',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.listAppConnections(workspace);\n outputData(result, ctx, COLUMNS);\n },\n },\n {\n path: ['app-connections', 'enable'],\n description: 'Enable a platform app',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'App connection ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.enablePlatformApp(workspace, {\n app_slug: requireString(args, 'id'),\n } as any);\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['app-connections', 'get'],\n description: 'Get a platform app',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'App connection ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getPlatformApp(\n workspace,\n requireString(args, 'id')\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['app-connections', 'update'],\n description: 'Update a platform app',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'App connection ID', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updatePlatformApp(\n workspace,\n requireString(args, 'id'),\n data as any\n );\n outputSingle(result, ctx, COLUMNS);\n },\n },\n {\n path: ['app-connections', 'delete'],\n description: 'Delete a platform app',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'App connection ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const id = requireString(args, 'id');\n await requireAuth(ctx).apiClient.deletePlatformApp(workspace, id);\n process.stdout.write(`Deleted app connection ${id}\\n`);\n },\n },\n {\n path: ['app-connections', 'sync-config'],\n description: 'Get sync configuration for a connection',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Connection ID (numeric)', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getConnectionSyncConfig(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['app-connections', 'update-sync-config'],\n description: 'Update sync configuration for a connection (pass raw config as --data)',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Connection ID (numeric)', required: true }],\n handler: async ({ ctx, workspace, args, data }) => {\n const result = await requireAuth(ctx).apiClient.updateConnectionSyncConfig(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['app-connections', 'relink-member'],\n description:\n 'Re-enable sync for a previously unlinked member by clearing ' +\n 'the manual-unlink exclusion on this connection. Idempotent: ' +\n 'returns cleared=false when no exclusion exists.',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'id', description: 'Connection ID (numeric)', required: true },\n { name: 'member-id', description: 'Member ID (numeric)', required: true },\n {\n name: 'board-id',\n description:\n 'Optional Monday board ID. Required for Monday connections ' +\n 'where exclusions are board-scoped; omit for single-scope ' +\n 'connectors.',\n },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const boardIdRaw = args['board-id'];\n const options =\n boardIdRaw !== undefined && boardIdRaw !== ''\n ? { boardId: String(boardIdRaw) }\n : undefined;\n const result = await requireAuth(ctx).apiClient.clearConnectionMemberExclusion(\n workspace,\n requireNumber(args, 'id'),\n requireNumber(args, 'member-id'),\n options\n );\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef } from '../../lib/types';\nimport { CLIError } from '../../lib/errors';\nimport { outputData, outputSingle } from '../../lib/output';\nimport { requireAuth } from '../../lib/context';\n\nexport const confluenceDomain: DomainDef = {\n name: 'confluence',\n description: 'Confluence knowledge base integration',\n commands: [\n {\n path: ['confluence', 'status'],\n description: 'Get Confluence connection status',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getConfluenceStatus(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'configure'],\n description: 'Configure Confluence OAuth credentials',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.configureConfluence(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'authorize'],\n description: 'Start Confluence OAuth flow',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.startConfluenceOAuth(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'disconnect'],\n description: 'Disconnect Confluence (clear tokens)',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disconnectConfluence(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'enable'],\n description: 'Enable Confluence connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.enableConfluence(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'disable'],\n description: 'Disable Confluence connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disableConfluence(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'delete'],\n description: 'Delete Confluence connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n await requireAuth(ctx).apiClient.deleteConfluence(workspace);\n process.stdout.write('Deleted Confluence connection\\n');\n },\n },\n {\n path: ['confluence', 'spaces'],\n description: 'List available Confluence spaces',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.listConfluenceSpaces(workspace);\n outputData(result.results, ctx);\n },\n },\n {\n path: ['confluence', 'pages'],\n description: 'List pages in a Confluence space',\n requiresWorkspace: true,\n args: [{ name: 'space-id', description: 'Confluence space ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const spaceId = args['space-id'];\n if (!spaceId || typeof spaceId !== 'string')\n throw new CLIError('--space-id is required');\n const result = await requireAuth(ctx).apiClient.listConfluencePages(workspace, spaceId);\n outputData(result.results, ctx);\n },\n },\n {\n path: ['confluence', 'sync-config'],\n description: 'Get Confluence sync configuration',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const conns = await requireAuth(ctx).apiClient.listAppConnections(workspace);\n const conn = conns.find((c: any) => c.connectionType === 'confluence_connection');\n if (!conn) throw new CLIError('No Confluence connection found');\n const result = await requireAuth(ctx).apiClient.getConnectionSyncConfig(\n workspace,\n conn.id\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['confluence', 'update-sync-config'],\n description: 'Update Confluence sync configuration',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const conns = await requireAuth(ctx).apiClient.listAppConnections(workspace);\n const conn = conns.find((c: any) => c.connectionType === 'confluence_connection');\n if (!conn) throw new CLIError('No Confluence connection found');\n const result = await requireAuth(ctx).apiClient.updateConnectionSyncConfig(\n workspace,\n conn.id,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../../lib/types';\nimport { crudCommands } from '../../lib/crud';\nimport { outputData, outputSingle, COL } from '../../lib/output';\nimport { requireAuth } from '../../lib/context';\n\nconst COLUMNS = [COL.id(), COL.name(), COL.status()];\n\nexport const discordBotsDomain: DomainDef = {\n name: 'discord-bots',\n description: 'Manage Discord bot integrations',\n commands: [\n ...crudCommands({\n prefix: ['discord-bots'],\n entityName: 'Discord bot',\n listMethod: 'getDiscordBots',\n getMethod: 'getDiscordBot',\n createMethod: 'createDiscordBot',\n updateMethod: 'updateDiscordBot',\n deleteMethod: 'deleteDiscordBot',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n {\n path: ['discord-bots', 'register-commands'],\n description: 'Register slash commands for a Discord bot',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Discord bot ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.registerDiscordSlashCommands(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['discord-bots', 'threads'],\n description: 'List Discord threads',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Discord bot ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getDiscordThreads(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['discord-bots', 'guilds'],\n description: 'List Discord guilds',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Discord bot ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getDiscordGuilds(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['discord-bots', 'accounts'],\n description: 'List Discord bot accounts',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Discord bot ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getDiscordBotAccounts(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../../lib/types';\nimport type { TableColumn } from '../../lib/output';\nimport { crudCommands } from '../../lib/crud';\nimport { outputSingle, COL } from '../../lib/output';\nimport { requireAuth } from '../../lib/context';\n\nconst COLUMNS: TableColumn<unknown>[] = [\n COL.id(),\n COL.name(),\n { header: 'URL', getValue: (item: any) => item.base_url ?? '' },\n COL.status(),\n];\n\nexport const fhirConnectionsDomain: DomainDef = {\n name: 'fhir-connections',\n description: 'Manage FHIR connections',\n commands: [\n ...crudCommands({\n prefix: ['fhir-connections'],\n entityName: 'FHIR connection',\n listMethod: 'getFhirConnections',\n getMethod: 'getFhirConnection',\n createMethod: 'createFhirConnection',\n updateMethod: 'updateFhirConnection',\n deleteMethod: 'deleteFhirConnection',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n {\n path: ['fhir-connections', 'test'],\n description: 'Test a FHIR connection',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'FHIR connection ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.testFhirConnection(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber, requireString } from '../../lib/types';\nimport { CLIError } from '../../lib/errors';\nimport { outputData, outputSingle } from '../../lib/output';\nimport {\n LIST_PAGINATION_ARGS,\n fetchAllPages,\n listResult,\n parsePaginationArgs,\n} from '../../lib/pagination';\nimport { requireAuth } from '../../lib/context';\n\nexport const hubspotDomain: DomainDef = {\n name: 'hubspot',\n description: 'HubSpot CRM integration',\n commands: [\n {\n path: ['hubspot', 'status'],\n description: 'Get HubSpot connection status',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getHubspotStatus(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'configure'],\n description: 'Configure HubSpot connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.configureHubspot(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'authorize'],\n description: 'Start HubSpot OAuth flow',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.startHubspotOAuth(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'disconnect'],\n description: 'Disconnect HubSpot',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disconnectHubspot(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'enable'],\n description: 'Enable HubSpot connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.enableHubspot(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'disable'],\n description: 'Disable HubSpot connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disableHubspot(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'delete'],\n description: 'Delete HubSpot connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n await requireAuth(ctx).apiClient.deleteHubspot(workspace);\n process.stdout.write('Deleted HubSpot connection\\n');\n },\n },\n {\n path: ['hubspot', 'sync-config'],\n description: 'Get HubSpot sync configuration',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n // Find hubspot connection ID\n const conns = await requireAuth(ctx).apiClient.listAppConnections(workspace);\n const conn = conns.find((c: any) => c.connectionType === 'hubspot_connection');\n if (!conn) throw new CLIError('No HubSpot connection found');\n const result = await requireAuth(ctx).apiClient.getConnectionSyncConfig(\n workspace,\n conn.id\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'update-sync-config'],\n description: 'Update HubSpot sync configuration',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const conns = await requireAuth(ctx).apiClient.listAppConnections(workspace);\n const conn = conns.find((c: any) => c.connectionType === 'hubspot_connection');\n if (!conn) throw new CLIError('No HubSpot connection found');\n const result = await requireAuth(ctx).apiClient.updateConnectionSyncConfig(\n workspace,\n conn.id,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'reconciliation'],\n description: 'Find matching HubSpot contacts for workspace members',\n requiresWorkspace: true,\n args: [\n { name: 'offset', description: 'Pagination offset' },\n { name: 'limit', description: 'Max results' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const offset = args['offset'] ? Number(args['offset']) : undefined;\n const limit = args['limit'] ? Number(args['limit']) : undefined;\n const result = await requireAuth(ctx).apiClient.getHubspotReconciliationMatches(\n workspace,\n {\n offset,\n limit,\n }\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['hubspot', 'linked-members'],\n description: 'List members linked to HubSpot contacts',\n requiresWorkspace: true,\n args: LIST_PAGINATION_ARGS,\n handler: async ({ ctx, workspace, args }) => {\n const pag = parsePaginationArgs(args);\n if (pag.all) {\n const allItems = await fetchAllPages(({ page, pageSize }) =>\n requireAuth(ctx).apiClient.getLinkedHubspotMembers(workspace, { page, pageSize })\n );\n outputData(allItems, ctx);\n return;\n }\n const options: { page?: number; pageSize?: number } = {};\n if (pag.page) options.page = pag.page;\n if (pag.pageSize) options.pageSize = pag.pageSize;\n const result = await requireAuth(ctx).apiClient.getLinkedHubspotMembers(\n workspace,\n options\n );\n outputData(listResult(result, true), ctx);\n },\n },\n {\n path: ['hubspot', 'link-member'],\n description: 'Link a member to a HubSpot contact',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'contact-id', description: 'HubSpot contact ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.linkMemberToHubspot(workspace, {\n memberId: requireNumber(args, 'member-id'),\n hubspotRecordId: requireString(args, 'contact-id'),\n });\n outputSingle(result, ctx);\n },\n },\n {\n path: ['hubspot', 'unlink-member'],\n description: 'Unlink a member from HubSpot',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.unlinkMemberFromHubspot(\n workspace,\n requireNumber(args, 'member-id')\n );\n process.stdout.write('Unlinked member from HubSpot\\n');\n },\n },\n {\n path: ['hubspot', 'contact-properties'],\n description: 'List available HubSpot contact properties',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getHubspotContactProperties(workspace);\n outputData(result, ctx);\n },\n },\n {\n path: ['hubspot', 'managed-rules'],\n description: 'List HubSpot managed sync rules and their status',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getHubspotManagedRules(workspace);\n outputData(result, ctx);\n },\n },\n {\n path: ['hubspot', 'transform-presets'],\n description: 'List available HubSpot field transform presets',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getHubspotTransformPresets(workspace);\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber, requireString } from '../../lib/types';\nimport { CLIError } from '../../lib/errors';\nimport { outputData, outputSingle } from '../../lib/output';\nimport {\n LIST_PAGINATION_ARGS,\n fetchAllPages,\n listResult,\n parsePaginationArgs,\n} from '../../lib/pagination';\nimport { requireAuth } from '../../lib/context';\n\nexport const mondayDomain: DomainDef = {\n name: 'monday',\n description: 'Monday.com integration',\n commands: [\n {\n path: ['monday', 'status'],\n description: 'Get Monday.com connection status',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMondayConnectionStatus(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'authorize'],\n description: 'Get Monday.com OAuth authorization URL',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.authorizeMondayConnection(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'configure'],\n description: 'Configure Monday.com connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.configureMondayConnection(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'disconnect'],\n description: 'Disconnect Monday.com',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disconnectMondayConnection(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'enable'],\n description: 'Enable Monday.com connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.enableMondayConnection(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'disable'],\n description: 'Disable Monday.com connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disableMondayConnection(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'delete'],\n description: 'Delete Monday.com connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n await requireAuth(ctx).apiClient.deleteMondayConnection(workspace);\n process.stdout.write('Deleted Monday.com connection\\n');\n },\n },\n {\n path: ['monday', 'sync-config'],\n description: 'Get Monday.com sync configuration',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMondaySyncConfig(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'update-sync-config'],\n description: 'Update Monday.com sync configuration',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n // Accept both the raw config and the full GET response shape\n // ({ syncConfig: {...} }). The API client wraps in { syncConfig },\n // so unwrap here to avoid double-wrapping.\n const syncConfig = (data as any).syncConfig ?? data;\n const result = await requireAuth(ctx).apiClient.updateMondaySyncConfig(\n workspace,\n syncConfig as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'reconciliation'],\n description: 'Find matching Monday.com items for workspace members',\n requiresWorkspace: true,\n args: [\n { name: 'offset', description: 'Pagination offset' },\n { name: 'limit', description: 'Max results' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const offset = args['offset'] ? Number(args['offset']) : undefined;\n const limit = args['limit'] ? Number(args['limit']) : undefined;\n const result = await requireAuth(ctx).apiClient.getMondayReconciliationMatches(\n workspace,\n {\n offset,\n limit,\n }\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['monday', 'linked-members'],\n description: 'List members linked to Monday.com items',\n requiresWorkspace: true,\n args: [{ name: 'board-id', description: 'Board ID' }, ...LIST_PAGINATION_ARGS],\n handler: async ({ ctx, workspace, args }) => {\n const boardId = (args['board-id'] as string) ?? undefined;\n const pag = parsePaginationArgs(args);\n if (pag.all) {\n const allItems = await fetchAllPages(({ page, pageSize }) =>\n requireAuth(ctx).apiClient.getLinkedMondayMembers(workspace, {\n board_id: boardId,\n page,\n pageSize,\n })\n );\n outputData(allItems, ctx);\n return;\n }\n const options: { board_id?: string; page?: number; pageSize?: number } = {};\n if (boardId) options.board_id = boardId;\n if (pag.page) options.page = pag.page;\n if (pag.pageSize) options.pageSize = pag.pageSize;\n const result = await requireAuth(ctx).apiClient.getLinkedMondayMembers(\n workspace,\n options\n );\n outputData(listResult(result, true), ctx);\n },\n },\n {\n path: ['monday', 'link-member'],\n description: 'Link a member to a Monday.com item',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'item-id', description: 'Monday item ID', required: true },\n { name: 'board-id', description: 'Monday board ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.linkMemberToMonday(workspace, {\n memberId: requireNumber(args, 'member-id'),\n mondayItemId: requireString(args, 'item-id'),\n boardId: requireString(args, 'board-id'),\n });\n outputSingle(result, ctx);\n },\n },\n {\n path: ['monday', 'unlink-member'],\n description: 'Unlink a member from Monday.com',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'board-id', description: 'Monday board ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.unlinkMemberFromMonday(\n workspace,\n requireNumber(args, 'member-id'),\n requireString(args, 'board-id')\n );\n process.stdout.write('Unlinked member from Monday.com\\n');\n },\n },\n {\n path: ['monday', 'boards'],\n description: 'List Monday.com boards',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMondayBoards(workspace);\n outputData(result, ctx);\n },\n },\n {\n path: ['monday', 'board-columns'],\n description: 'List columns for a Monday.com board',\n requiresWorkspace: true,\n args: [{ name: 'board-id', description: 'Board ID', required: true }],\n handler: async ({ ctx, args, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMondayBoardColumns(\n workspace,\n requireString(args, 'board-id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['monday', 'board-groups'],\n description: 'List groups for a Monday.com board',\n requiresWorkspace: true,\n args: [{ name: 'board-id', description: 'Board ID', required: true }],\n handler: async ({ ctx, args, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMondayBoardGroups(\n workspace,\n requireString(args, 'board-id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['monday', 'user-info'],\n description: 'Get current Monday.com user info',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getMondayCurrentUserInfo(workspace);\n outputSingle(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber, requireString } from '../../lib/types';\nimport { CLIError } from '../../lib/errors';\nimport { outputData, outputSingle } from '../../lib/output';\nimport {\n LIST_PAGINATION_ARGS,\n fetchAllPages,\n listResult,\n parsePaginationArgs,\n} from '../../lib/pagination';\nimport { requireAuth } from '../../lib/context';\n\nexport const salesforceDomain: DomainDef = {\n name: 'salesforce',\n description: 'Salesforce CRM integration',\n commands: [\n {\n path: ['salesforce', 'status'],\n description: 'Get Salesforce connection status',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getSalesforceStatus(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'configure'],\n description: 'Configure Salesforce connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.configureSalesforce(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'authorize'],\n description: 'Start Salesforce OAuth flow',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.startSalesforceOAuth(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'disconnect'],\n description: 'Disconnect Salesforce',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disconnectSalesforce(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'enable'],\n description: 'Enable Salesforce connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.enableSalesforce(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'disable'],\n description: 'Disable Salesforce connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.disableSalesforce(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'delete'],\n description: 'Delete Salesforce connection',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n await requireAuth(ctx).apiClient.deleteSalesforce(workspace);\n process.stdout.write('Deleted Salesforce connection\\n');\n },\n },\n {\n path: ['salesforce', 'sync-config'],\n description: 'Get Salesforce sync configuration',\n requiresWorkspace: true,\n handler: async ({ ctx, workspace }) => {\n const result = await requireAuth(ctx).apiClient.getSalesforceSyncConfig(workspace);\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'update-sync-config'],\n description: 'Update Salesforce sync configuration',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.updateSalesforceSyncConfig(\n workspace,\n data as any\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'reconciliation'],\n description: 'Find matching Salesforce records for workspace members',\n requiresWorkspace: true,\n args: [\n { name: 'offset', description: 'Pagination offset' },\n { name: 'limit', description: 'Max results' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const offset = args['offset'] ? Number(args['offset']) : undefined;\n const limit = args['limit'] ? Number(args['limit']) : undefined;\n const result = await requireAuth(ctx).apiClient.getSalesforceReconciliationMatches(\n workspace,\n {\n offset,\n limit,\n }\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['salesforce', 'linked-members'],\n description: 'List members linked to Salesforce records',\n requiresWorkspace: true,\n args: LIST_PAGINATION_ARGS,\n handler: async ({ ctx, workspace, args }) => {\n const pag = parsePaginationArgs(args);\n if (pag.all) {\n const allItems = await fetchAllPages(({ page, pageSize }) =>\n requireAuth(ctx).apiClient.getLinkedSalesforceMembers(workspace, {\n page,\n pageSize,\n })\n );\n outputData(allItems, ctx);\n return;\n }\n const options: { page?: number; pageSize?: number } = {};\n if (pag.page) options.page = pag.page;\n if (pag.pageSize) options.pageSize = pag.pageSize;\n const result = await requireAuth(ctx).apiClient.getLinkedSalesforceMembers(\n workspace,\n options\n );\n outputData(listResult(result, true), ctx);\n },\n },\n {\n path: ['salesforce', 'link-member'],\n description: 'Link a member to a Salesforce record',\n mutates: true,\n requiresWorkspace: true,\n args: [\n { name: 'member-id', description: 'Member ID', required: true },\n { name: 'record-id', description: 'Salesforce record ID', required: true },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.linkMemberToSalesforce(workspace, {\n memberId: requireNumber(args, 'member-id'),\n salesforceRecordId: requireString(args, 'record-id'),\n });\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'unlink-member'],\n description: 'Unlink a member from Salesforce',\n mutates: true,\n requiresWorkspace: true,\n args: [{ name: 'member-id', description: 'Member ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n await requireAuth(ctx).apiClient.unlinkMemberFromSalesforce(\n workspace,\n requireNumber(args, 'member-id')\n );\n process.stdout.write('Unlinked member from Salesforce\\n');\n },\n },\n {\n path: ['salesforce', 'describe'],\n description: 'Describe a Salesforce object schema',\n requiresWorkspace: true,\n args: [\n {\n name: 'object-type',\n description: 'Salesforce object type (e.g., Contact)',\n required: true,\n },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.describeSalesforceObject(\n workspace,\n requireString(args, 'object-type')\n );\n outputSingle(result, ctx);\n },\n },\n {\n path: ['salesforce', 'search'],\n description: 'Search Salesforce records',\n requiresWorkspace: true,\n args: [\n { name: 'query', description: 'Search query', required: true },\n { name: 'object-type', description: 'Salesforce object type' },\n ],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.searchSalesforceRecords(workspace, {\n query: requireString(args, 'query'),\n objectType: (args['object-type'] as string) ?? undefined,\n } as any);\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../../lib/types';\nimport { crudCommands } from '../../lib/crud';\nimport { CLIError } from '../../lib/errors';\nimport { outputData, outputSingle, COL } from '../../lib/output';\nimport { requireAuth } from '../../lib/context';\n\nconst COLUMNS = [COL.id(), COL.name(), COL.status()];\n\n/** Inject computed Slack integration URLs into the response object. */\nfunction addSlackUrls(\n data: Record<string, unknown>,\n apiUrl: string,\n workspaceUuid: string\n): Record<string, unknown> {\n const base = `${apiUrl}/api/v2/w/${workspaceUuid}/app-connections/slack`;\n return {\n ...data,\n _urls: {\n eventsEndpoint: `${base}/routines`,\n oauthBotCallback: `${base}/oauth/callback`,\n oauthUserCallback: `${base}/oauth/user/callback`,\n oauthInstall: `${base}/oauth/install?app_uuid=${data.uuid ?? ''}`,\n },\n };\n}\n\nexport const slackAppsDomain: DomainDef = {\n name: 'slack-apps',\n description: 'Manage Slack app integrations',\n commands: [\n // List + delete from CRUD; get/create/update are custom to inject URLs\n ...crudCommands({\n prefix: ['slack-apps'],\n entityName: 'Slack app',\n listMethod: 'getSlackApps',\n deleteMethod: 'deleteSlackApp',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n {\n path: ['slack-apps', 'get'],\n description: 'Get a Slack app by ID',\n args: [{ name: 'id', description: 'Slack app ID', required: true }],\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getSlackApp(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(addSlackUrls(result as any, ctx.envConfig.apiUrl, workspace), ctx);\n },\n },\n {\n path: ['slack-apps', 'create'],\n description: 'Create a Slack app',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.createSlackApp(workspace, data as any);\n outputSingle(addSlackUrls(result as any, ctx.envConfig.apiUrl, workspace), ctx);\n },\n },\n {\n path: ['slack-apps', 'update'],\n description: 'Update a Slack app',\n mutates: true,\n args: [{ name: 'id', description: 'Slack app ID', required: true }],\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.updateSlackApp(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(addSlackUrls(result as any, ctx.envConfig.apiUrl, workspace), ctx);\n },\n },\n {\n path: ['slack-apps', 'threads'],\n description: 'List Slack threads',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Slack app ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getSlackThreads(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['slack-apps', 'installations'],\n description: 'List Slack installations',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Slack app ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getSlackInstallations(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['slack-apps', 'accounts'],\n description: 'List Slack app accounts',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Slack app ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getSlackAppAccounts(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n ],\n};\n","import { type DomainDef, requireNumber } from '../../lib/types';\nimport { crudCommands } from '../../lib/crud';\nimport { CLIError } from '../../lib/errors';\nimport { outputData, outputSingle, COL } from '../../lib/output';\nimport { requireAuth } from '../../lib/context';\n\nconst COLUMNS = [COL.id(), COL.name(), COL.status()];\n\n/** Inject computed Teams integration URLs into the response object. */\nfunction addTeamsUrls(\n data: Record<string, unknown>,\n apiUrl: string,\n workspaceUuid: string\n): Record<string, unknown> {\n const base = `${apiUrl}/api/v2/w/${workspaceUuid}/app-connections/teams`;\n return {\n ...data,\n _urls: {\n eventsEndpoint: `${base}/events`,\n oauthUserAuthorize: `${base}/oauth/user/authorize?app_id=${data.id ?? ''}`,\n oauthUserCallback: `${base}/oauth/user/callback`,\n },\n };\n}\n\nexport const teamsAppsDomain: DomainDef = {\n name: 'teams-apps',\n description: 'Manage Microsoft Teams app integrations',\n commands: [\n ...crudCommands({\n prefix: ['teams-apps'],\n entityName: 'Teams app',\n listMethod: 'getTeamsApps',\n deleteMethod: 'deleteTeamsApp',\n columns: COLUMNS,\n paginationSupport: 'full',\n }),\n {\n path: ['teams-apps', 'get'],\n description: 'Get a Teams app by ID',\n args: [{ name: 'id', description: 'Teams app ID', required: true }],\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getTeamsApp(\n workspace,\n requireNumber(args, 'id')\n );\n outputSingle(addTeamsUrls(result as any, ctx.envConfig.apiUrl, workspace), ctx);\n },\n },\n {\n path: ['teams-apps', 'create'],\n description: 'Create a Teams app',\n mutates: true,\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.createTeamsApp(workspace, data as any);\n outputSingle(addTeamsUrls(result as any, ctx.envConfig.apiUrl, workspace), ctx);\n },\n },\n {\n path: ['teams-apps', 'update'],\n description: 'Update a Teams app',\n mutates: true,\n args: [{ name: 'id', description: 'Teams app ID', required: true }],\n requiresWorkspace: true,\n handler: async ({ ctx, workspace, args, data }) => {\n if (!data) throw new CLIError('JSON data required (--data, --file, or stdin)');\n const result = await requireAuth(ctx).apiClient.updateTeamsApp(\n workspace,\n requireNumber(args, 'id'),\n data as any\n );\n outputSingle(addTeamsUrls(result as any, ctx.envConfig.apiUrl, workspace), ctx);\n },\n },\n {\n path: ['teams-apps', 'conversations'],\n description: 'List Teams conversations linked to chats',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Teams app ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getTeamsConversations(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['teams-apps', 'installations'],\n description: 'List per-tenant Teams installations',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Teams app ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getTeamsInstallations(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n {\n path: ['teams-apps', 'accounts'],\n description: 'List linked Teams (Entra) accounts for this app',\n requiresWorkspace: true,\n args: [{ name: 'id', description: 'Teams app ID', required: true }],\n handler: async ({ ctx, workspace, args }) => {\n const result = await requireAuth(ctx).apiClient.getTeamsAppAccounts(\n workspace,\n requireNumber(args, 'id')\n );\n outputData(result, ctx);\n },\n },\n ],\n};\n","import type { CommandRegistry } from '../lib/registry';\n\n// Core domains — Phase 2a\nimport { agentTasksDomain } from './agent-tasks';\nimport { agentsDomain } from './agents';\nimport { chatsDomain } from './chats';\nimport { membersDomain } from './members';\nimport { tasksDomain } from './tasks';\nimport { workflowsDomain } from './workflows';\nimport { workflowVersionsDomain } from './workflow-versions';\nimport { workspacesDomain } from './workspaces';\n\n// Core domains — Phase 2b\nimport { assignmentsDomain } from './assignments';\nimport { calendarsDomain } from './calendars';\nimport { dataTypesDomain } from './data-types';\nimport { eventsDomain } from './events';\nimport { filesDomain } from './files';\nimport { journeysDomain } from './journeys';\nimport { personasDomain } from './personas';\nimport { qualificationsDomain } from './qualifications';\nimport { sitesDomain } from './sites';\n\n// Secondary domains — Phase 3\nimport { accessGrantsDomain } from './access-grants';\nimport { aiModelsDomain } from './ai-models';\nimport { apiKeysDomain } from './api-keys';\nimport { appsDomain } from './apps';\nimport { authManageDomain } from './auth-manage';\nimport { billingPortalDomain } from './billing-portal';\nimport { conciergeDomain } from './concierge';\nimport { customToolkitsDomain } from './custom-toolkits';\nimport { featuresDomain } from './features';\nimport { inboxesDomain } from './inboxes';\nimport { mcpServersDomain } from './mcp-servers';\nimport { memberMemoriesDomain } from './member-memories';\nimport { milestonesDomain } from './milestones';\nimport { notificationRulesDomain } from './notification-rules';\nimport { oauthDomain } from './oauth';\nimport { operatorGroupsDomain } from './operator-groups';\nimport { orgDomain } from './org';\nimport { orgPhoneNumbersDomain } from './org-phone-numbers';\nimport { phoneNumbersDomain } from './phone-numbers';\nimport { pronunciationsDomain } from './pronunciations';\nimport { reportsDomain } from './reports';\nimport { subscriptionsDomain } from './subscriptions';\nimport { promptsDomain } from './prompts';\nimport { supportDomain } from './support';\nimport { supervisorsDomain } from './supervisors';\nimport { syncDomain } from './sync';\n\n// Integration domains — Phase 4\nimport { appConnectionsDomain } from './integrations/app-connections';\nimport { confluenceDomain } from './integrations/confluence';\nimport { discordBotsDomain } from './integrations/discord-bots';\nimport { fhirConnectionsDomain } from './integrations/fhir-connections';\nimport { hubspotDomain } from './integrations/hubspot';\nimport { mondayDomain } from './integrations/monday';\nimport { salesforceDomain } from './integrations/salesforce';\nimport { slackAppsDomain } from './integrations/slack-apps';\nimport { teamsAppsDomain } from './integrations/teams-apps';\n\n/**\n * Register the full set of public CLI domains on a registry.\n *\n * This file intentionally does NOT import any admin or infrastructure domains\n * (deploy, rollback, railgun, admin/*). Those live in `@gravity-rail/gr-cli`\n * and are layered on top via its own `registerAllDomains`.\n */\nexport function registerPublicDomains(registry: CommandRegistry): void {\n // Core\n registry.register(tasksDomain);\n registry.register(chatsDomain);\n registry.register(membersDomain);\n registry.register(workspacesDomain);\n registry.register(workflowsDomain);\n registry.register(workflowVersionsDomain);\n registry.register(agentsDomain);\n registry.register(agentTasksDomain);\n registry.register(assignmentsDomain);\n registry.register(dataTypesDomain);\n registry.register(sitesDomain);\n registry.register(filesDomain);\n registry.register(eventsDomain);\n registry.register(calendarsDomain);\n registry.register(qualificationsDomain);\n registry.register(personasDomain);\n registry.register(journeysDomain);\n\n // Secondary\n registry.register(phoneNumbersDomain);\n registry.register(inboxesDomain);\n registry.register(operatorGroupsDomain);\n registry.register(accessGrantsDomain);\n registry.register(notificationRulesDomain);\n registry.register(supervisorsDomain);\n registry.register(promptsDomain);\n registry.register(milestonesDomain);\n registry.register(customToolkitsDomain);\n registry.register(mcpServersDomain);\n registry.register(apiKeysDomain);\n registry.register(subscriptionsDomain);\n registry.register(supportDomain);\n registry.register(reportsDomain);\n registry.register(aiModelsDomain);\n registry.register(featuresDomain);\n registry.register(pronunciationsDomain);\n registry.register(orgDomain);\n registry.register(orgPhoneNumbersDomain);\n registry.register(authManageDomain);\n registry.register(appsDomain);\n registry.register(oauthDomain);\n registry.register(conciergeDomain);\n registry.register(memberMemoriesDomain);\n registry.register(syncDomain);\n\n // Integrations\n registry.register(confluenceDomain);\n registry.register(discordBotsDomain);\n registry.register(slackAppsDomain);\n registry.register(teamsAppsDomain);\n registry.register(fhirConnectionsDomain);\n registry.register(appConnectionsDomain);\n registry.register(hubspotDomain);\n registry.register(mondayDomain);\n registry.register(salesforceDomain);\n\n // Billing portal (non-admin)\n registry.register(billingPortalDomain);\n}\n","import { execFile } from 'child_process';\nimport { stderr } from '../lib/output';\nimport type { AuthenticatedContext } from '../lib/context';\n\n/**\n * Open an authenticated browser session using the CLI's existing credentials.\n *\n * Flow:\n * 1. Get the current account's email from the CLI session\n * 2. Request a magic link via the API (token returned directly since caller is authenticated)\n * 3. Open the magic link URL in the default browser (or print it with --no-open)\n */\nexport async function authBrowserCommand(\n ctx: AuthenticatedContext,\n args: Record<string, unknown>\n): Promise<void> {\n const noOpen = Boolean(args['no-open']);\n\n // Get current account email\n const account = await ctx.apiClient.getUserAccount();\n if (!account.email) {\n process.stderr.write('Error: No email associated with current account\\n');\n process.exit(1);\n }\n\n // Request magic link — since we're authenticated, the API returns the token directly\n const response = await ctx.apiClient.requestMagicLink(account.email);\n\n if (!response.success || !response.magicLinkUrl) {\n process.stderr.write('Error: Failed to create magic link\\n');\n process.exit(1);\n }\n\n const url = response.magicLinkUrl;\n\n if (noOpen) {\n // Just print the URL to stdout for scripting/manual use\n process.stdout.write(url + '\\n');\n return;\n }\n\n // Open in default browser\n stderr(`Opening browser for ${account.email} (${ctx.env})...`);\n openUrl(url);\n stderr('Browser opened. Link expires in 15 minutes.');\n}\n\n/** Open a URL in the default browser (cross-platform). Uses execFile to avoid shell injection. */\nfunction openUrl(url: string): void {\n const platform = process.platform;\n\n let command: string;\n let args: string[];\n\n if (platform === 'darwin') {\n command = 'open';\n args = [url];\n } else if (platform === 'win32') {\n command = 'cmd.exe';\n args = ['/c', 'start', '', url];\n } else {\n command = 'xdg-open';\n args = [url];\n }\n\n execFile(command, args, (err) => {\n if (err) {\n // Non-fatal — user can copy the URL from --no-open output\n process.stderr.write('Warning: Could not open browser automatically\\n');\n }\n });\n}\n","import path from 'path';\n\nexport interface ConciergeAppContextPayload {\n clientSurface: 'cli';\n cliContext: {\n shell?: string;\n os: string;\n cwdBasename: string;\n };\n channel: 'text';\n}\n\n/** Build ConciergeAppContext for AG-UI requests from the CLI. */\nexport function buildCliConciergeAppContext(): ConciergeAppContextPayload {\n const shell = process.env.SHELL ? path.basename(process.env.SHELL) : undefined;\n return {\n clientSurface: 'cli',\n channel: 'text',\n cliContext: {\n shell,\n os: process.platform,\n cwdBasename: path.basename(process.cwd()),\n },\n };\n}\n","/**\n * Handle concierge HITL interrupts in the CLI (local file ops, etc.).\n */\n\nimport readline from 'readline';\nimport {\n executeCliLocalFileAction,\n isCliLocalFileInterrupt,\n type CliLocalFileInterrupt,\n} from './local-files';\nimport { resolveDirectoryTrust } from './trusted-dirs';\n\nexport type { CliLocalFileInterrupt };\n\nexport interface HitlResumePayload {\n resumeValue: string;\n resumeInterruptId?: string;\n}\n\nexport function extractHumanInputRequest(event: Record<string, unknown>): unknown | null {\n const type = String(event.type ?? '').toUpperCase();\n if (type === 'CUSTOM' && event.name === 'human_input_request') {\n return event.value;\n }\n if (event.name === 'human_input_request') {\n return event.value;\n }\n return null;\n}\n\nexport async function handleCliHitlInterrupt(\n value: unknown,\n opts: {\n allowWrite: boolean;\n autoApprove: boolean;\n trustCwd?: boolean;\n trustDir?: string;\n /** When true, skip the trust prompt and fail if the directory is untrusted. */\n nonInteractive?: boolean;\n }\n): Promise<HitlResumePayload | null> {\n if (!value || typeof value !== 'object') return null;\n const payload = value as Record<string, unknown>;\n\n if (isCliLocalFileInterrupt(payload)) {\n const interrupt = payload as CliLocalFileInterrupt;\n if (typeof payload.interrupt_id === 'string') {\n interrupt.interrupt_id = payload.interrupt_id;\n }\n return handleCliLocalFile(interrupt, opts);\n }\n\n if (payload.type === 'present_choice') {\n return handlePresentChoiceTerminal(payload);\n }\n\n return null;\n}\n\nasync function handleCliLocalFile(\n interrupt: CliLocalFileInterrupt,\n opts: {\n allowWrite: boolean;\n trustCwd?: boolean;\n trustDir?: string;\n nonInteractive?: boolean;\n }\n): Promise<HitlResumePayload> {\n const trust = await resolveDirectoryTrust({\n cwd: process.cwd(),\n trustCwd: opts.trustCwd,\n trustDir: opts.trustDir,\n // Interactive sessions: prompt on first local-file use (review feedback).\n nonInteractive: opts.nonInteractive ?? process.stdin.isTTY !== true,\n });\n if (trust !== 'trusted') {\n return {\n resumeValue: JSON.stringify({\n ok: false,\n error: 'Directory not trusted for local file access. Re-run with --trust-cwd or --trust-dir <path>, or approve trust interactively when prompted.',\n }),\n resumeInterruptId: interrupt.interrupt_id,\n };\n }\n\n process.stderr.write(`\\n[local ${interrupt.action}] ${interrupt.path}\\n`);\n const result = executeCliLocalFileAction(process.cwd(), interrupt, {\n allowWrite: opts.allowWrite,\n });\n return {\n resumeValue: JSON.stringify(result),\n resumeInterruptId: interrupt.interrupt_id,\n };\n}\n\nasync function handlePresentChoiceTerminal(\n payload: Record<string, unknown>\n): Promise<HitlResumePayload | null> {\n const prompt =\n (typeof payload.user_prompt === 'string' && payload.user_prompt) ||\n (typeof payload.description === 'string' && payload.description) ||\n 'Choose an option';\n const markup = typeof payload.openui_markup === 'string' ? payload.openui_markup : '';\n process.stderr.write(`\\n${prompt}\\n`);\n if (markup) {\n process.stderr.write(`${markup.slice(0, 2000)}\\n`);\n }\n if (!process.stdin.isTTY) {\n return {\n resumeValue: '',\n resumeInterruptId:\n typeof payload.interrupt_id === 'string' ? payload.interrupt_id : undefined,\n };\n }\n const rl = readline.createInterface({ input: process.stdin, output: process.stderr });\n const answer = await new Promise<string>((resolve) => {\n rl.question('Your choice (value): ', resolve);\n });\n rl.close();\n return {\n resumeValue: answer.trim(),\n resumeInterruptId:\n typeof payload.interrupt_id === 'string' ? payload.interrupt_id : undefined,\n };\n}\n","/**\n * Sandboxed local filesystem operations for CLI-executed concierge tools.\n */\n\nimport fs from 'fs';\nimport path from 'path';\n\nconst DEFAULT_MAX_READ_BYTES = 50_000;\nconst ABSOLUTE_MAX_READ_BYTES = 1_000_000;\n\nexport interface CliLocalFileInterrupt {\n type: 'cli_local_file';\n action: 'read_file' | 'list_dir' | 'write_file';\n path: string;\n content?: string;\n max_bytes?: number;\n interrupt_id?: string;\n}\n\nexport interface CliLocalFileResult {\n ok: boolean;\n content?: string;\n error?: string;\n}\n\nfunction resolveSafePath(root: string, relativePath: string): string | null {\n const rootResolved = path.resolve(root);\n const target = path.resolve(rootResolved, relativePath || '.');\n if (target !== rootResolved && !target.startsWith(rootResolved + path.sep)) {\n return null;\n }\n // Reject any component along the path that is a symlink — `path.resolve`\n // does not follow symlinks but `fs.statSync`/`readFileSync` do, so a\n // symlink inside the trusted dir could otherwise read or write a file\n // outside of it. ``lstatSync`` reports the link itself and never the\n // target.\n let cursor = rootResolved;\n const rest = path.relative(rootResolved, target);\n if (rest && rest !== '.') {\n for (const segment of rest.split(path.sep)) {\n cursor = path.join(cursor, segment);\n try {\n const lstat = fs.lstatSync(cursor);\n if (lstat.isSymbolicLink()) {\n return null;\n }\n } catch {\n // Missing path components are fine — the caller decides what to do\n // with a non-existent target.\n break;\n }\n }\n }\n return target;\n}\n\nexport function executeCliLocalFileAction(\n root: string,\n interrupt: CliLocalFileInterrupt,\n opts: { allowWrite: boolean }\n): CliLocalFileResult {\n const safe = resolveSafePath(root, interrupt.path);\n if (!safe) {\n return { ok: false, error: 'Path escapes trusted directory' };\n }\n\n try {\n switch (interrupt.action) {\n case 'read_file': {\n if (!fs.existsSync(safe)) {\n return { ok: false, error: 'File not found' };\n }\n const stat = fs.lstatSync(safe);\n if (stat.isSymbolicLink()) {\n return { ok: false, error: 'Path escapes trusted directory' };\n }\n if (!stat.isFile()) {\n return { ok: false, error: 'Not a file' };\n }\n const requested = Number.isFinite(interrupt.max_bytes)\n ? Math.max(1, Math.min(Number(interrupt.max_bytes), ABSOLUTE_MAX_READ_BYTES))\n : DEFAULT_MAX_READ_BYTES;\n if (stat.size > requested) {\n const buf = fs.readFileSync(safe, { encoding: 'utf8' });\n return {\n ok: true,\n content: buf.slice(0, requested) + `\\n\\n[truncated at ${requested} bytes]`,\n };\n }\n return { ok: true, content: fs.readFileSync(safe, 'utf8') };\n }\n case 'list_dir': {\n if (!fs.existsSync(safe)) {\n return { ok: false, error: 'Directory not found' };\n }\n const entries = fs.readdirSync(safe, { withFileTypes: true });\n const lines = entries\n .slice(0, 200)\n .map((e) => (e.isDirectory() ? `${e.name}/` : e.name));\n if (entries.length > 200) {\n lines.push(`... and ${entries.length - 200} more`);\n }\n return { ok: true, content: lines.join('\\n') };\n }\n case 'write_file': {\n if (!opts.allowWrite) {\n return { ok: false, error: 'Write requires --allow-write' };\n }\n if (interrupt.content === undefined) {\n return { ok: false, error: 'Missing content for write_file' };\n }\n fs.mkdirSync(path.dirname(safe), { recursive: true });\n fs.writeFileSync(safe, interrupt.content, 'utf8');\n return { ok: true, content: 'written' };\n }\n default:\n return { ok: false, error: `Unknown action: ${interrupt.action}` };\n }\n } catch (e) {\n return { ok: false, error: sanitizeLocalFileError(e) };\n }\n}\n\nfunction sanitizeLocalFileError(e: unknown): string {\n if (e && typeof e === 'object' && 'code' in e) {\n const code = (e as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') return 'File or directory not found';\n if (code === 'EACCES' || code === 'EPERM') return 'Permission denied';\n if (code === 'EISDIR') return 'Not a file';\n if (code === 'ENOTDIR') return 'Not a directory';\n }\n return 'Local file operation failed';\n}\n\nexport function isCliLocalFileInterrupt(value: unknown): value is CliLocalFileInterrupt {\n if (typeof value !== 'object' || value === null) return false;\n const v = value as Record<string, unknown>;\n return v.type === 'cli_local_file' && typeof v.action === 'string' && typeof v.path === 'string';\n}\n","/**\n * Directory-trust store for CLI file-capable surfaces.\n *\n * Separates input trust from --allow-write (output mutations). Trust is\n * path-keyed (VS Code workspace-trust model): a grant applies to the directory\n * path, not to individual file contents — new files dropped into a trusted path\n * are readable without re-prompting.\n *\n * See docs/public/cli-get-started.md and gr-feedback trust-directory spec.\n */\n\nimport fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport readline from 'readline';\n\nexport type DirectoryTrustDecision = 'once' | 'always' | 'denied';\n\nexport type DirectoryTrustStatus = 'trusted' | 'denied';\n\nexport interface TrustedDirsStore {\n version: 1;\n /** Absolute paths the user chose \"trust always\" for. */\n always: string[];\n}\n\nconst STORE_VERSION = 1 as const;\n\nfunction storePath(): string {\n const base =\n process.env.XDG_CONFIG_HOME ??\n (process.platform === 'win32'\n ? path.join(process.env.APPDATA ?? os.homedir(), 'gravityrail')\n : path.join(os.homedir(), '.config', 'gravityrail'));\n return path.join(base, 'trusted-dirs.json');\n}\n\nexport function loadTrustedDirsStore(): TrustedDirsStore {\n const file = storePath();\n try {\n const raw = JSON.parse(fs.readFileSync(file, 'utf8')) as TrustedDirsStore;\n if (raw?.version === STORE_VERSION && Array.isArray(raw.always)) {\n return { version: STORE_VERSION, always: raw.always.map((p) => path.resolve(p)) };\n }\n } catch {\n // Missing or corrupt — treat as empty.\n }\n return { version: STORE_VERSION, always: [] };\n}\n\nfunction saveTrustedDirsStore(store: TrustedDirsStore): void {\n const file = storePath();\n const dir = path.dirname(file);\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n fs.writeFileSync(file, JSON.stringify(store, null, 2) + '\\n', { mode: 0o600 });\n}\n\nexport function isDirectoryTrusted(dirPath: string, opts?: { trustCwdFlag?: boolean }): boolean {\n if (opts?.trustCwdFlag) return true;\n const resolved = path.resolve(dirPath);\n const store = loadTrustedDirsStore();\n return store.always.includes(resolved);\n}\n\nasync function promptTrustInteractive(dirPath: string): Promise<DirectoryTrustDecision> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stderr });\n const question = (q: string) => new Promise<string>((resolve) => rl.question(q, resolve));\n\n process.stderr.write(\n `\\nGravity Rail may read files in:\\n ${dirPath}\\n\\n` +\n `File contents can influence the assistant. Do you trust the files in this directory?\\n` +\n ` [1] Trust once (this session)\\n` +\n ` [2] Trust always (remember for this path)\\n` +\n ` [3] No — do not read local files\\n\\n` +\n `Choice [1/2/3] (default 3): `\n );\n const answer = (await question('')).trim() || '3';\n rl.close();\n\n if (answer === '1') return 'once';\n if (answer === '2') return 'always';\n return 'denied';\n}\n\nconst sessionTrusted = new Set<string>();\n\nexport interface DirectoryTrustOptions {\n cwd?: string;\n /** Explicit grant for CI/headless — trust files in this absolute path. */\n trustDir?: string;\n /** Explicit grant — trust process.cwd(). */\n trustCwd?: boolean;\n nonInteractive?: boolean;\n}\n\n/**\n * Resolve directory trust before local file tools run. Does not throw — callers\n * return a tool error to the model when status is `denied`.\n */\nexport async function resolveDirectoryTrust(\n opts: DirectoryTrustOptions\n): Promise<DirectoryTrustStatus> {\n const dir = path.resolve(opts.trustDir ?? opts.cwd ?? process.cwd());\n\n if (isDirectoryTrusted(dir, { trustCwdFlag: opts.trustCwd })) return 'trusted';\n if (sessionTrusted.has(dir)) return 'trusted';\n\n // --trust-dir <path> grants trust for that path (headless escape hatch).\n if (opts.trustDir && path.resolve(opts.trustDir) === dir) {\n sessionTrusted.add(dir);\n return 'trusted';\n }\n\n if (opts.trustCwd) {\n sessionTrusted.add(dir);\n return 'trusted';\n }\n\n if (!process.stdin.isTTY || opts.nonInteractive) {\n return 'denied';\n }\n\n const decision = await promptTrustInteractive(dir);\n if (decision === 'denied') {\n return 'denied';\n }\n if (decision === 'always') {\n const store = loadTrustedDirsStore();\n if (!store.always.includes(dir)) {\n store.always.push(dir);\n saveTrustedDirsStore(store);\n }\n }\n sessionTrusted.add(dir);\n return 'trusted';\n}\n\n/** @deprecated Use resolveDirectoryTrust — kept for tests migrating off session-start gates. */\nexport async function requireDirectoryTrust(opts: DirectoryTrustOptions): Promise<void> {\n const { CLIError } = await import('./errors');\n const dir = path.resolve(opts.trustDir ?? opts.cwd ?? process.cwd());\n const status = await resolveDirectoryTrust(opts);\n if (status === 'trusted') return;\n\n throw new CLIError(\n `Directory not trusted: ${dir}\\n\\n` +\n `Re-run with --trust-cwd (or --trust-dir <path>) after reviewing files in that directory, ` +\n `or run interactively to approve trust when a local file tool is first used.`\n );\n}\n","/**\n * Concierge AG-UI turn loop with HITL resume (local files, present_choice).\n */\n\nimport {\n AGUIClient,\n getErrorMessage,\n getTextDelta,\n type AGUIEvent,\n type ChatMessage as AGUIChatMessage,\n} from '../cli-utils/agui';\nimport { extractHumanInputRequest, handleCliHitlInterrupt } from './cli-hitl';\n\nconst MAX_HITL_ROUNDS = 25;\n\nexport async function runConciergeAguiLoop(\n client: AGUIClient,\n initialMessages: AGUIChatMessage[],\n onEvent: (event: AGUIEvent) => void,\n opts: {\n autoApprove: boolean;\n allowWrite: boolean;\n debug?: boolean;\n trustCwd?: boolean;\n trustDir?: string;\n nonInteractive?: boolean;\n }\n): Promise<{ streamText: string; hasToolCalls: boolean }> {\n let streamText = '';\n let hasToolCalls = false;\n let resume: { resumeValue: string; resumeInterruptId?: string } | undefined;\n\n for (let round = 0; round < MAX_HITL_ROUNDS; round++) {\n let hitlPayload: unknown = null;\n\n await client.streamRequest(\n resume\n ? {\n messages: [],\n resumeValue: resume.resumeValue,\n resumeInterruptId: resume.resumeInterruptId,\n }\n : { messages: initialMessages },\n (event) => {\n onEvent(event);\n const delta = getTextDelta(event);\n if (delta) streamText += delta;\n const type = event.type?.toLowerCase() ?? '';\n if (type === 'tool_call_start') hasToolCalls = true;\n const errorMsg = getErrorMessage(event);\n if (errorMsg) process.stderr.write(`\\x1B[31mError: ${errorMsg}\\x1B[0m\\n`);\n const hitl = extractHumanInputRequest(event as Record<string, unknown>);\n if (hitl) hitlPayload = hitl;\n },\n { autoApprove: opts.autoApprove }\n );\n\n if (!hitlPayload) {\n break;\n }\n\n const next = await handleCliHitlInterrupt(hitlPayload, {\n allowWrite: opts.allowWrite,\n autoApprove: opts.autoApprove,\n trustCwd: opts.trustCwd,\n trustDir: opts.trustDir,\n nonInteractive: opts.nonInteractive,\n });\n if (!next) {\n process.stderr.write(\n ' [HITL] Unsupported interrupt in CLI — open app.gravityrail.com/setup to continue.\\n'\n );\n break;\n }\n resume = next;\n streamText = '';\n }\n\n return { streamText, hasToolCalls };\n}\n","/**\n * Shared chat session infrastructure.\n *\n * Defines the ChatSession abstraction consumed by all chat modes (text, realtime, voice).\n * Entry points (manage, chat, concierge) construct a ChatSession and pass it here.\n */\n\nimport {\n AGUIClient,\n clearScreen,\n getErrorMessage,\n getTextDelta,\n printMessage,\n type AGUIChatMessage,\n} from '../cli-utils';\nimport type { ConciergeAppContextPayload } from './cli-client-context';\nimport { runConciergeAguiLoop } from './concierge-agui-loop';\nimport * as readline from 'readline';\nimport { CLIError } from './errors';\nimport type { AuthenticatedContext } from './context';\nimport { RealtimeClient } from './realtime-client';\nimport { ChatTUI, type ChatItem } from './chat-tui';\nimport {\n checkSoxAvailable,\n listInputDevices,\n listOutputDevices,\n selectDevice,\n MicCapture,\n AudioPlayer,\n} from './audio';\n\n// ─── ChatSession abstraction ─────────────────────────────────────────────────\n\n/** Everything a chat mode needs — constructed differently per entry point. */\nexport interface ChatSession {\n ctx: AuthenticatedContext;\n workspaceUuid: string;\n chatId: number;\n chatUuid: string;\n chatTitle: string;\n aguiEndpointUrl: string;\n wsUrl: string;\n loadMessages: () => Promise<any[]>;\n /** Display label: \"Workspace Manager\", \"Concierge\", etc. */\n label: string;\n /** AGUI request model field. Undefined = omit from body. */\n model?: string;\n /** Concierge client context (CLI surface, etc.). */\n appContext?: ConciergeAppContextPayload;\n /** Whether --allow-write was passed (local file writes). */\n allowWrite?: boolean;\n /** Directory-trust flags for lazy local-file HITL. */\n trustCwd?: boolean;\n trustDir?: string;\n}\n\n// ─── Mode dispatcher ─────────────────────────────────────────────────────────\n\nexport async function runChatSession(\n session: ChatSession,\n args: Record<string, any>\n): Promise<void> {\n const debug = !!args.debug;\n const isVoice = !!args.voice;\n const isRealtime = !!args.realtime || isVoice;\n const message = typeof args.message === 'string' ? args.message : undefined;\n const autoApprove = !!args['auto-approve'];\n\n if (args['list-devices']) {\n await listAudioDevices();\n return;\n }\n\n if (!message && !process.stdin.isTTY) {\n throw new CLIError(\n 'Interactive mode requires a TTY. Use --message for non-interactive mode.'\n );\n }\n\n const allowWrite = !!args['allow-write'] || !!session.allowWrite;\n if (message) {\n await singleTurnChatSession(session, message, debug, autoApprove, allowWrite);\n } else if (isVoice) {\n await voiceChatSession(session, vadMode(args), args, debug);\n } else if (isRealtime) {\n await realtimeChatSession(session, vadMode(args), debug);\n } else {\n await interactiveChatSession(session, debug, autoApprove, allowWrite);\n }\n}\n\nexport function vadMode(args: Record<string, any>): 'client' | 'server' {\n return (typeof args.vad === 'string' ? args.vad : 'server') as 'client' | 'server';\n}\n\n// ─── Single-turn text mode (SSE) ────────────────────────────────────────────\n\nasync function singleTurnChatSession(\n session: ChatSession,\n message: string,\n debug: boolean,\n autoApprove: boolean = false,\n allowWrite: boolean = false\n): Promise<void> {\n const aguiClient = new AGUIClient({\n baseUrl: session.ctx.envConfig.apiUrl,\n workspaceUuid: session.workspaceUuid,\n chatId: session.chatId,\n endpointUrl: session.aguiEndpointUrl,\n accessToken: session.ctx.accessToken,\n debug,\n model: session.model,\n appContext: session.appContext,\n });\n\n // Stream all SSE events. The AGUI stream includes tool calls, tool\n // results, and text content across all inference turns. We accumulate\n // text and show tool call progress, then poll for final text if the\n // stream ended mid-turn (e.g. after tool calls with no final text).\n const onEvent = (event: { type?: string; name?: string }) => {\n const type = event.type?.toLowerCase() ?? '';\n if (type === 'tool_call_start') {\n const name =\n (event as Record<string, any>).toolCallName ??\n (event as Record<string, any>).name ??\n '';\n process.stderr.write(` [${name}]\\n`);\n }\n };\n\n const { streamText, hasToolCalls } = await runConciergeAguiLoop(\n aguiClient,\n [{ role: 'user', content: message }],\n onEvent,\n {\n autoApprove,\n allowWrite: allowWrite || !!session.allowWrite,\n debug,\n trustCwd: session.trustCwd,\n trustDir: session.trustDir,\n nonInteractive: true,\n }\n );\n\n // If we got text from the stream, print it\n if (streamText) {\n process.stdout.write(`\\x1B[32mAssistant:\\x1B[0m ${streamText}\\n`);\n return;\n }\n\n // No text in stream (tool calls only) — poll for the final response\n if (hasToolCalls) {\n process.stderr.write(' (waiting for completion...)\\n');\n const maxWaitMs = 180_000;\n const pollIntervalMs = 2000;\n const startTime = Date.now();\n let finalText = '';\n\n while (Date.now() - startTime < maxWaitMs) {\n await new Promise((r) => setTimeout(r, pollIntervalMs));\n try {\n const msgs = await session.loadMessages();\n // Find the last assistant message with actual text\n for (let i = msgs.length - 1; i >= 0; i--) {\n const m = msgs[i];\n if (m.role === 'assistant' && m.content && !m.tool_calls?.length) {\n finalText = m.content;\n break;\n }\n }\n if (finalText) break;\n } catch {\n // keep polling\n }\n }\n\n process.stdout.write(`\\x1B[32mAssistant:\\x1B[0m ${finalText || '(no text response)'}\\n`);\n } else {\n process.stdout.write(`\\x1B[32mAssistant:\\x1B[0m (no response)\\n`);\n }\n}\n\n// ─── Interactive text mode (SSE) ─────────────────────────────────────────────\n\nasync function interactiveChatSession(\n session: ChatSession,\n debug: boolean,\n autoApprove: boolean,\n allowWrite: boolean\n): Promise<void> {\n const aguiClient = new AGUIClient({\n baseUrl: session.ctx.envConfig.apiUrl,\n workspaceUuid: session.workspaceUuid,\n chatId: session.chatId,\n endpointUrl: session.aguiEndpointUrl,\n accessToken: session.ctx.accessToken,\n debug,\n model: session.model,\n appContext: session.appContext,\n });\n\n clearScreen();\n console.log('='.repeat(60));\n console.log(session.label);\n console.log('='.repeat(60));\n console.log(`Chat: ${session.chatTitle}`);\n console.log(\"Type your message and press Enter. Type 'exit' or Ctrl+C to quit.\");\n console.log('='.repeat(60));\n console.log('');\n\n const existingMessages = await session.loadMessages();\n if (existingMessages.length > 0) {\n console.log('\\x1B[90m--- Previous messages ---\\x1B[0m\\n');\n for (const msg of existingMessages.slice(-10)) {\n const text = typeof msg.content === 'string' ? msg.content : '';\n if (text && text.trim()) {\n printMessage(text, msg.role as 'user' | 'assistant' | 'system');\n }\n }\n console.log('\\x1B[90m--- End of history ---\\x1B[0m\\n');\n }\n\n const conversationMessages: AGUIChatMessage[] = [];\n for (const msg of existingMessages.slice(-10)) {\n const text = typeof msg.content === 'string' ? msg.content : '';\n if (text && text.trim() && (msg.role === 'user' || msg.role === 'assistant')) {\n conversationMessages.push({ role: msg.role, content: text });\n }\n }\n\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n\n return new Promise<void>((resolve) => {\n const prompt = (): void => {\n rl.question('\\x1B[34mYou:\\x1B[0m ', async (input) => {\n const trimmed = input.trim();\n if (!trimmed) {\n prompt();\n return;\n }\n if (trimmed.toLowerCase() === 'exit' || trimmed.toLowerCase() === 'quit') {\n console.log('\\nGoodbye!');\n rl.close();\n return;\n }\n\n conversationMessages.push({ role: 'user', content: trimmed });\n process.stdout.write('\\n\\x1B[32mAssistant:\\x1B[0m ');\n let assistantContent = '';\n\n try {\n const { streamText } = await runConciergeAguiLoop(\n aguiClient,\n conversationMessages,\n (event) => {\n const delta = getTextDelta(event);\n if (delta) {\n process.stdout.write(delta);\n assistantContent += delta;\n }\n const errorMsg = getErrorMessage(event);\n if (errorMsg) console.log(`\\n\\x1B[31mError: ${errorMsg}\\x1B[0m`);\n },\n {\n autoApprove,\n allowWrite: allowWrite || !!session.allowWrite,\n debug,\n trustCwd: session.trustCwd,\n trustDir: session.trustDir,\n }\n );\n if (streamText && !assistantContent) {\n assistantContent = streamText;\n process.stdout.write(streamText);\n }\n if (assistantContent) {\n conversationMessages.push({ role: 'assistant', content: assistantContent });\n }\n console.log('\\n');\n } catch (error) {\n console.log(\n `\\n\\x1B[31mError: ${error instanceof Error ? error.message : error}\\x1B[0m\\n`\n );\n }\n\n prompt();\n });\n };\n\n rl.on('close', () => {\n console.log('\\nGoodbye!');\n resolve();\n });\n prompt();\n });\n}\n\n// ─── Shared helpers for realtime modes ───────────────────────────────────────\n\nexport function buildHistory(messages: any[]): ChatItem[] {\n const history: ChatItem[] = [];\n for (const msg of messages.slice(-30)) {\n const text = typeof msg.content === 'string' ? msg.content : '';\n if (msg.role === 'user' || msg.role === 'assistant') {\n if (text.trim()) {\n history.push({ role: msg.role, content: text });\n }\n if (msg.role === 'assistant' && msg.tool_calls) {\n for (const tc of msg.tool_calls) {\n history.push({\n kind: 'tool_call',\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments || '',\n done: true,\n });\n }\n }\n } else if (msg.role === 'tool') {\n const toolName = (msg as any).name || 'tool';\n history.push({\n kind: 'tool_result',\n toolCallId: (msg as any).tool_call_id || '',\n toolName,\n content: text,\n });\n }\n }\n return history;\n}\n\nexport function wireRealtimeEvents(client: RealtimeClient, tui: ChatTUI): void {\n client.on('text_start', () => tui.streamStart());\n client.on('text_delta', (data: any) => tui.streamDelta(data.delta));\n client.on('text_end', () => tui.streamEnd());\n\n client.on('tool_call_start', (data: any) => {\n tui.toolCallStart(data.toolCallId, data.toolCallName);\n });\n client.on('tool_call_args', (data: any) => {\n tui.toolCallArgs(data.toolCallId, data.delta);\n });\n client.on('tool_call_end', (data: any) => {\n tui.toolCallEnd(data.toolCallId);\n });\n client.on('tool_call_result', (data: any) => {\n const toolName = tui.findToolCallName(data.toolCallId);\n const content = typeof data.result === 'string' ? data.result : JSON.stringify(data.result);\n tui.toolCallResult(data.toolCallId, toolName, content);\n });\n\n client.on('run_error', (data: any) => {\n tui.showError(data.message);\n });\n\n client.on('error', (err: Error) => {\n tui.showError(`Connection: ${err.message}`);\n });\n\n client.on('ws_recv', (msg: any) => tui.logDebug('in', msg));\n client.on('ws_send', (msg: any) => tui.logDebug('out', msg));\n}\n\n// ─── Realtime text mode (WebSocket + TUI) ────────────────────────────────────\n\nasync function realtimeChatSession(\n session: ChatSession,\n vad: 'client' | 'server',\n debug: boolean\n): Promise<void> {\n const client = new RealtimeClient({\n url: session.wsUrl,\n token: session.ctx.accessToken,\n chatId: session.chatId,\n vadMode: vad,\n debug,\n });\n\n process.stderr.write(`Connecting to ${session.label.toLowerCase()}...\\n`);\n\n try {\n await client.connect();\n } catch (err) {\n throw new CLIError(`Failed to connect: ${err instanceof Error ? err.message : err}`);\n }\n\n const existingMessages = await session.loadMessages();\n const history = buildHistory(existingMessages);\n\n const tui = new ChatTUI({\n onSend: (text) => {\n client.sendTextMessage(text);\n },\n onExit: () => {\n client.close();\n },\n debug,\n env: session.ctx.env,\n });\n\n wireRealtimeEvents(client, tui);\n\n client.on('closed', () => {\n tui.stop();\n console.log('Disconnected.');\n });\n\n tui.loadHistory(history);\n tui.start();\n\n await new Promise<void>((resolve) => {\n client.once('closed', resolve);\n });\n}\n\n// ─── Voice mode (WebSocket + mic + speaker + TUI) ────────────────────────────\n\nasync function voiceChatSession(\n session: ChatSession,\n vad: 'client' | 'server',\n args: Record<string, string | boolean | undefined>,\n debug: boolean\n): Promise<void> {\n if (!checkSoxAvailable()) {\n throw new CLIError(\n 'Voice mode requires SoX. Install it:\\n' +\n ' macOS: brew install sox\\n' +\n ' Linux: apt install sox\\n' +\n ' Windows: choco install sox'\n );\n }\n\n const inputDeviceName =\n typeof args['input-device'] === 'string' ? args['input-device'] : undefined;\n const outputDeviceName =\n typeof args['output-device'] === 'string' ? args['output-device'] : undefined;\n\n let inputDeviceId: string | undefined;\n let outputDeviceId: string | undefined;\n\n if (!inputDeviceName || !outputDeviceName) {\n process.stderr.write('\\n Audio Devices\\n');\n }\n\n if (inputDeviceName) {\n inputDeviceId = inputDeviceName;\n } else {\n const inputDevices = await listInputDevices();\n const selected = await selectDevice(inputDevices, 'Input (microphone)');\n inputDeviceId = selected.id;\n }\n\n if (outputDeviceName) {\n outputDeviceId = outputDeviceName;\n } else {\n const outputDevices = await listOutputDevices();\n const selected = await selectDevice(outputDevices, 'Output (speaker)');\n outputDeviceId = selected.id;\n }\n\n const client = new RealtimeClient({\n url: session.wsUrl,\n token: session.ctx.accessToken,\n chatId: session.chatId,\n vadMode: vad,\n debug,\n });\n\n process.stderr.write(`\\nConnecting to ${session.label.toLowerCase()}...\\n`);\n\n try {\n await client.connect();\n } catch (err) {\n throw new CLIError(`Failed to connect: ${err instanceof Error ? err.message : err}`);\n }\n\n const existingMessages = await session.loadMessages();\n const history = buildHistory(existingMessages);\n\n const mic = new MicCapture((pcm16) => {\n if (!client.isConnected()) return;\n client.sendAudio(pcm16);\n });\n const player = new AudioPlayer(outputDeviceId);\n\n function cleanup(): void {\n mic.stop();\n player.stop();\n client.close();\n }\n\n const tui = new ChatTUI({\n onSend: (text) => {\n client.sendTextMessage(text);\n },\n onExit: () => {\n cleanup();\n },\n debug,\n env: session.ctx.env,\n });\n\n wireRealtimeEvents(client, tui);\n\n client.on('audio', (data: any) => {\n player.write(data.pcm16);\n });\n\n client.on('audio_end', (data: any) => {\n player.endResponse(data?.messageId);\n });\n\n client.on('interrupt', () => {\n const playbackMs = player.getPlaybackTimeMs();\n const messageId = player.playingMessageId;\n\n if (playbackMs !== null && playbackMs > 0 && player.isPlaying) {\n client.sendInterrupt(playbackMs, messageId);\n player.stop();\n\n if (debug) {\n tui.logDebug('in', {\n type: 'CUSTOM',\n name: 'voice.interrupt',\n value: { action: 'echoed', audioEndMs: playbackMs, messageId },\n });\n }\n } else if (debug) {\n tui.logDebug('in', {\n type: 'CUSTOM',\n name: 'voice.interrupt',\n value: { action: 'ignored', wasPlaying: player.isPlaying },\n });\n }\n });\n\n client.on('truncate', (data: any) => {\n player.stop();\n tui.truncateAssistant(\n data.content ?? '',\n data.originalContent,\n data.truncationReason ?? 'barge_in',\n data.truncatedAtMs\n );\n });\n\n client.on('response_message', (data: any) => {\n if (data.role === 'user' && data.content) {\n tui.addTranscription(data.content);\n }\n });\n\n client.on('closed', () => {\n tui.stop();\n cleanup();\n console.log('Disconnected.');\n });\n\n tui.loadHistory(history);\n tui.start();\n\n mic.start(inputDeviceId);\n\n await new Promise<void>((resolve) => {\n client.once('closed', resolve);\n });\n}\n\n// ─── Device listing ──────────────────────────────────────────────────────────\n\nexport async function listAudioDevices(): Promise<void> {\n if (!checkSoxAvailable()) {\n throw new CLIError(\n 'Device listing requires SoX. Install it:\\n' +\n ' macOS: brew install sox\\n' +\n ' Linux: apt install sox\\n' +\n ' Windows: choco install sox'\n );\n }\n\n const inputs = await listInputDevices();\n const outputs = await listOutputDevices();\n\n console.log('Input devices (microphone):');\n for (const dev of inputs) {\n const marker = dev.isDefault ? ' (default)' : '';\n console.log(` ${dev.id}: ${dev.name}${marker}`);\n }\n\n console.log('\\nOutput devices (speaker):');\n for (const dev of outputs) {\n const marker = dev.isDefault ? ' (default)' : '';\n console.log(` ${dev.id}: ${dev.name}${marker}`);\n }\n}\n","/**\n * WebSocket-based AG-UI Realtime Client for CLI\n *\n * Handles the AG-UI protocol over WebSocket for realtime voice and text\n * interactions with the Workspace Manager. Adapted from the browser\n * implementation in src/components/voice/ws-unified.ts.\n *\n * Uses the native WebSocket global (Node.js 22+).\n */\n\nimport { EventEmitter } from 'events';\n\n// AG-UI event format over WebSocket\ninterface AGUIWebSocketEvent {\n type: string;\n name?: string;\n value?: any;\n messageId?: string;\n delta?: string;\n role?: string;\n message?: string;\n code?: string;\n toolCallId?: string;\n toolCallName?: string;\n [key: string]: any;\n}\n\nexport interface RealtimeClientOptions {\n /** WebSocket URL (wss://...) */\n url: string;\n /** JWT access token for authentication */\n token: string;\n /** Chat ID to connect to (null to create a new chat) */\n chatId: number | null;\n /** VAD mode: 'server' (default) or 'client' */\n vadMode?: 'client' | 'server';\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * Realtime WebSocket client for AG-UI protocol.\n *\n * Events:\n * - connected: Login success with chat/member/assistant IDs\n * - audio: Received audio PCM16 buffer\n * - text_start/text_delta/text_end: Streaming text message\n * - transcription: User speech transcription\n * - response_message: Full message object\n * - tool_call_start/tool_call_args/tool_call_end: Tool calls\n * - run_error: Run error from server\n * - error: Connection/protocol error\n * - closed: WebSocket closed\n */\nexport class RealtimeClient extends EventEmitter {\n private ws: WebSocket | null = null;\n private connected = false;\n private options: Required<RealtimeClientOptions>;\n\n constructor(options: RealtimeClientOptions) {\n super();\n this.options = {\n vadMode: 'server',\n debug: false,\n ...options,\n };\n }\n\n /** Connect to the realtime WebSocket endpoint */\n connect(): Promise<void> {\n if (typeof globalThis.WebSocket === 'undefined') {\n return Promise.reject(\n new Error('WebSocket not available. Node.js 22+ is required for realtime mode.')\n );\n }\n\n return new Promise((resolve, reject) => {\n const params = new URLSearchParams();\n if (this.options.vadMode) {\n params.append('vad', this.options.vadMode);\n }\n const url = params.toString()\n ? `${this.options.url}?${params.toString()}`\n : this.options.url;\n\n if (this.options.debug) {\n process.stderr.write(`[debug] Connecting to ${url}\\n`);\n }\n\n this.ws = new WebSocket(url);\n\n this.ws.onerror = (event: Event) => {\n const msg = event instanceof ErrorEvent ? event.message : 'WebSocket connection failed';\n if (!this.connected) {\n reject(new Error(msg));\n } else {\n this.emit('error', new Error(msg));\n }\n };\n\n this.ws.onclose = (event: CloseEvent) => {\n const reason = event.code === 1006 ? 'Connection lost' : event.reason || 'Closed';\n this.connected = false;\n this.emit('closed', { reason, code: event.code });\n };\n\n this.ws.onmessage = (event: MessageEvent) => {\n try {\n const data = typeof event.data === 'string' ? event.data : event.data.toString();\n const parsed: AGUIWebSocketEvent = JSON.parse(data);\n this.emit('ws_recv', parsed);\n this.handleEvent(parsed);\n } catch {\n if (this.options.debug) {\n process.stderr.write(`[debug] Failed to parse message\\n`);\n }\n }\n };\n\n this.ws.onopen = () => {\n if (this.options.debug) {\n process.stderr.write('[debug] WebSocket connected, sending login\\n');\n }\n this.sendCustom('voice.login', {\n token: this.options.token,\n chat_id: this.options.chatId,\n vad: this.options.vadMode,\n });\n };\n\n // Wait for login_success or timeout\n const timeout = setTimeout(() => {\n if (!this.connected) {\n this.close();\n reject(new Error('Connection timeout - no login response within 10s'));\n }\n }, 10000);\n\n this.once('connected', () => {\n clearTimeout(timeout);\n resolve();\n });\n\n this.once('error', () => {\n clearTimeout(timeout);\n });\n });\n }\n\n private handleEvent(event: AGUIWebSocketEvent): void {\n switch (event.type) {\n case 'CUSTOM':\n this.handleCustomEvent(event.name || '', event.value);\n break;\n\n case 'TEXT_MESSAGE_START':\n this.emit('text_start', { messageId: event.messageId || '' });\n break;\n case 'TEXT_MESSAGE_CONTENT':\n this.emit('text_delta', {\n messageId: event.messageId || '',\n delta: event.delta || '',\n });\n break;\n case 'TEXT_MESSAGE_END':\n this.emit('text_end', { messageId: event.messageId || '' });\n break;\n\n case 'TOOL_CALL_START':\n this.emit('tool_call_start', {\n toolCallId: event.toolCallId || '',\n toolCallName: event.toolCallName || '',\n });\n break;\n case 'TOOL_CALL_ARGS':\n this.emit('tool_call_args', {\n toolCallId: event.toolCallId || '',\n delta: event.delta || '',\n });\n break;\n case 'TOOL_CALL_END':\n this.emit('tool_call_end', { toolCallId: event.toolCallId || '' });\n break;\n case 'TOOL_CALL_RESULT':\n this.emit('tool_call_result', {\n toolCallId: event.toolCallId || '',\n result: event.result,\n });\n break;\n\n case 'RUN_STARTED':\n this.emit('run_started', { runId: event.runId });\n break;\n case 'RUN_FINISHED':\n this.emit('run_finished', { runId: event.runId });\n break;\n case 'RUN_ERROR':\n this.emit('run_error', {\n message: event.message || 'Unknown error',\n code: event.code,\n });\n break;\n\n default:\n if (this.options.debug) {\n process.stderr.write(`[debug] Unknown event type: ${event.type}\\n`);\n }\n }\n }\n\n private handleCustomEvent(name: string, value: any): void {\n switch (name) {\n case 'voice.login_success':\n this.connected = true;\n this.emit('connected', {\n chatId: value?.chat_id,\n memberId: value?.member_id,\n assistantId: value?.assistant_id,\n });\n break;\n\n case 'voice.audio':\n if (value?.data) {\n const pcm16 = Buffer.from(value.data, 'base64');\n this.emit('audio', { pcm16, messageId: value.message_id });\n }\n break;\n\n case 'voice.audio_begin':\n this.emit('audio_begin', { messageId: value?.message_id });\n break;\n case 'voice.audio_end':\n this.emit('audio_end', { messageId: value?.message_id });\n break;\n\n case 'voice.interrupt':\n this.emit('interrupt', { messageId: value?.message_id });\n break;\n\n case 'voice.response_message':\n if (value) {\n this.emit('response_message', value);\n }\n break;\n\n case 'voice.transcription':\n if (value) {\n this.emit('transcription', { text: value.text, role: value.role });\n }\n break;\n\n case 'voice.truncate':\n if (value) {\n this.emit('truncate', {\n messageId: value.message_id,\n content: value.content,\n originalContent: value.original_content,\n truncationReason: value.truncation_reason || 'barge_in',\n truncatedAtMs: value.audio_end_ms,\n });\n }\n break;\n\n case 'app.data_update':\n case 'app.navigation':\n case 'app.notification':\n break;\n\n default:\n if (this.options.debug) {\n process.stderr.write(`[debug] Unknown CUSTOM event: ${name}\\n`);\n }\n }\n }\n\n private sendCustom(name: string, value?: any): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n return;\n }\n const event: AGUIWebSocketEvent = { type: 'CUSTOM', name };\n if (value !== undefined) {\n event.value = value;\n }\n this.emit('ws_send', event);\n this.ws.send(JSON.stringify(event));\n }\n\n /** Send raw PCM16 audio data (will be base64-encoded) */\n sendAudio(pcm16: Buffer): void {\n this.sendCustom('voice.audio', {\n data: pcm16.toString('base64'),\n format: 'pcm16',\n sample_rate: 24000,\n });\n }\n\n /** Signal the start of an audio utterance */\n sendAudioBegin(messageId: string): void {\n this.sendCustom('voice.audio_begin', { message_id: messageId });\n }\n\n /** Signal the end of an audio utterance */\n sendAudioEnd(): void {\n this.sendCustom('voice.audio_end');\n }\n\n /** Send a text message (triggers AI inference) */\n sendTextMessage(content: string): void {\n this.sendCustom('voice.user_message', {\n message: { role: 'user', content },\n });\n }\n\n /** Send interrupt signal with playback position */\n sendInterrupt(audioEndMs: number, messageId?: string): void {\n this.sendCustom('voice.interrupt', {\n audio_end_ms: audioEndMs,\n message_id: messageId,\n });\n }\n\n /** Check if the client is connected */\n isConnected(): boolean {\n return this.connected && this.ws?.readyState === WebSocket.OPEN;\n }\n\n /** Close the connection */\n close(): void {\n this.connected = false;\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n }\n}\n","/**\n * Chat TUI — terminal chat interface using ANSI escape codes.\n *\n * Layout (normal):\n * Rows 1..R-2: Message area (full width)\n * Row R-1: Separator + hints\n * Row R: Input (\"You: ...\")\n *\n * Layout (debug):\n * Rows 1..R-2: Chat (left) │ Debug log (right)\n * Row R-1: Separator + hints\n * Row R: Input (\"You: ...\")\n *\n * Keyboard:\n * Up/Down Scroll 1 line\n * Page Up/Down Scroll 1 page\n * Ctrl+B Page up (less-style)\n * Ctrl+F Page down (less-style)\n * Home/End Top / bottom\n * Ctrl+O Toggle detail expansion (tool calls + debug messages)\n * Ctrl+D Toggle debug panel (when --debug)\n * Ctrl+C / exit Quit\n *\n * Mouse:\n * Scroll wheel Scroll 3 lines\n *\n * Zero external dependencies — only Node.js built-ins.\n */\n\nimport { createWriteStream, type WriteStream } from 'fs';\n\n// ─── Public types ─────────────────────────────────────────────────────────────\n\nexport interface ChatMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n /** Reason the message was truncated (voice interruption) */\n truncationReason?: string;\n /** Ms offset where truncation occurred */\n truncatedAtMs?: number;\n /** The full original content before truncation */\n originalContent?: string;\n}\n\nexport interface ChatTUIOptions {\n /** Called when the user sends a message */\n onSend: (text: string) => void;\n /** Called when the user exits (Ctrl+C, 'exit', 'quit') */\n onExit: () => void;\n /** Enable debug panel showing WebSocket traffic */\n debug?: boolean;\n /** Environment name (e.g. 'dev', 'staging', 'prod') — controls debug log file creation */\n env?: string;\n}\n\n// ─── Item types ───────────────────────────────────────────────────────────────\n\nexport interface ToolCallItem {\n kind: 'tool_call';\n id: string;\n name: string;\n args: string;\n done: boolean;\n}\n\nexport interface ToolResultItem {\n kind: 'tool_result';\n toolCallId: string;\n toolName: string;\n content: string;\n}\n\nexport type ChatItem = ChatMessage | ToolCallItem | ToolResultItem;\n\nfunction isToolCall(item: ChatItem): item is ToolCallItem {\n return 'kind' in item && (item as ToolCallItem).kind === 'tool_call';\n}\n\nfunction isToolResult(item: ChatItem): item is ToolResultItem {\n return 'kind' in item && (item as ToolResultItem).kind === 'tool_result';\n}\n\n/** Friendly label for truncation reason */\nfunction getTruncationLabel(reason: string, truncatedAtMs?: number): string {\n const timeStr = truncatedAtMs ? ` at ${(truncatedAtMs / 1000).toFixed(1)}s` : '';\n switch (reason) {\n case 'barge_in':\n return `interrupted: user spoke${timeStr}`;\n case 'client_interrupt':\n return `interrupted${timeStr}`;\n case 'user_cancel':\n return `cancelled by user${timeStr}`;\n case 'error':\n return `error${timeStr}`;\n default:\n return `interrupted${timeStr}`;\n }\n}\n\n/** Extract the unspoken portion of a truncated message */\nfunction getExtraContent(\n content: string | undefined,\n originalContent: string | undefined\n): string | null {\n if (!content || !originalContent) return null;\n const stripped = content.replace(/—interrupted$/, '');\n if (originalContent.startsWith(stripped)) {\n const extra = originalContent.slice(stripped.length);\n return extra.length > 0 ? extra : null;\n }\n return originalContent !== content ? originalContent : null;\n}\n\n// ─── Debug log entry ──────────────────────────────────────────────────────────\n\ninterface DebugEntry {\n direction: 'in' | 'out';\n summary: string; // one-line summary (always shown)\n detail: string; // full JSON (shown when expanded)\n ts: string; // HH:MM:SS\n}\n\n// ─── ANSI helpers ─────────────────────────────────────────────────────────────\n\nconst CSI = '\\x1B[';\nconst HIDE_CURSOR = `${CSI}?25l`;\nconst SHOW_CURSOR = `${CSI}?25h`;\nconst ALT_SCREEN_ON = `${CSI}?1049h`;\nconst ALT_SCREEN_OFF = `${CSI}?1049l`;\nconst CLEAR_EOL = `${CSI}K`;\nconst RESET = `${CSI}0m`;\nconst MOUSE_ON = `${CSI}?1000h${CSI}?1006h`; // Button events + SGR extended\nconst MOUSE_OFF = `${CSI}?1000l${CSI}?1006l`;\n\nconst BLUE = `${CSI}34m`;\nconst GREEN = `${CSI}32m`;\nconst GRAY = `${CSI}90m`;\nconst YELLOW = `${CSI}33m`;\nconst ORANGE = `${CSI}38;5;208m`; // 256-color orange — inbound\nconst LIGHT_BLUE = `${CSI}38;5;117m`; // 256-color light blue — outbound\nconst DIM = `${CSI}2m`;\nconst DIM_ITALIC_GRAY = `${CSI}2;3;90m`; // dim + italic + gray\n\nfunction moveTo(row: number, col: number): string {\n return `${CSI}${row};${col}H`;\n}\n\n// ─── ChatTUI ──────────────────────────────────────────────────────────────────\n\nexport class ChatTUI {\n private items: ChatItem[] = [];\n private inputBuffer = '';\n private isStreaming = false;\n private streamContent = '';\n private scrollOffset = 0;\n private expandDetails = false;\n private rows = 24;\n private cols = 80;\n private started = false;\n private renderTimer: ReturnType<typeof setTimeout> | null = null;\n private displayLinesCache: string[] | null = null;\n private debugLinesCache: string[] | null = null;\n private options: ChatTUIOptions;\n\n // Debug panel state\n private debugEntries: DebugEntry[] = [];\n private debugPanelVisible = false;\n private debugLogStream: WriteStream | null = null;\n\n // Escape sequence accumulator for raw stdin parsing\n private escBuf = '';\n private escTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(options: ChatTUIOptions) {\n this.options = options;\n this.debugPanelVisible = !!options.debug;\n }\n\n /** Whether the debug panel is currently being rendered */\n private get debugVisible(): boolean {\n return this.debugPanelVisible;\n }\n\n // ─── Lifecycle ──────────────────────────────────────────────────────\n\n start(): void {\n this.updateDimensions();\n process.stdout.write(ALT_SCREEN_ON + MOUSE_ON);\n process.stdout.write(`${CSI}1;${Math.max(1, this.rows - 2)}r`);\n\n // Raw mode + direct data handler (not readline — we parse escape seqs ourselves)\n process.stdin.setEncoding('utf8');\n if (process.stdin.isTTY) process.stdin.setRawMode(true);\n process.stdin.on('data', this.onData);\n process.stdin.resume();\n\n process.stdout.on('resize', this.onResize);\n process.on('exit', this.restoreTerminal);\n\n // Debug log file — only write to disk in dev/staging (never in prod to avoid PHI on disk)\n if (this.options.debug && this.options.env !== 'prod') {\n this.debugLogStream = createWriteStream('gr-cli-realtime-debug.log', { flags: 'a' });\n this.debugLogStream.write(`\\n--- session ${new Date().toISOString()} ---\\n`);\n }\n\n this.started = true;\n this.render();\n }\n\n stop(): void {\n if (!this.started) return;\n this.started = false;\n if (this.renderTimer) {\n clearTimeout(this.renderTimer);\n this.renderTimer = null;\n }\n this.clearEsc();\n if (this.debugLogStream) {\n this.debugLogStream.end();\n this.debugLogStream = null;\n }\n this.restoreTerminal();\n process.stdout.removeListener('resize', this.onResize);\n process.stdin.removeListener('data', this.onData);\n if (process.stdin.isTTY) process.stdin.setRawMode(false);\n process.stdin.pause();\n process.removeListener('exit', this.restoreTerminal);\n }\n\n // ─── Chat state ────────────────────────────────────────────────────\n\n loadHistory(items: ChatItem[]): void {\n this.items = items.filter((item) => (isToolCall(item) ? true : item.content?.trim()));\n this.dirty();\n }\n\n streamStart(): void {\n this.isStreaming = true;\n this.streamContent = '';\n this.scrollOffset = 0;\n this.dirty();\n }\n\n streamDelta(delta: string): void {\n this.streamContent += delta;\n this.dirty();\n }\n\n streamEnd(): void {\n if (this.streamContent.trim()) {\n this.items.push({ role: 'assistant', content: this.streamContent });\n }\n this.isStreaming = false;\n this.streamContent = '';\n this.dirty();\n }\n\n toolCallStart(id: string, name: string): void {\n this.items.push({ kind: 'tool_call', id, name, args: '', done: false });\n this.dirty();\n }\n\n toolCallArgs(id: string, delta: string): void {\n const tc = this.findToolCall(id);\n if (tc) {\n tc.args += delta;\n this.dirty();\n }\n }\n\n toolCallEnd(id: string): void {\n const tc = this.findToolCall(id);\n if (tc) {\n tc.done = true;\n this.dirty();\n }\n }\n\n /** Add a transcription of the user's spoken words (voice mode) */\n addTranscription(text: string): void {\n this.items.push({ role: 'user', content: text });\n this.scrollOffset = 0;\n this.dirty();\n }\n\n /**\n * Truncate the most recent assistant message (voice interruption).\n * Replaces its content with the spoken portion and stores the original.\n */\n truncateAssistant(\n content: string,\n originalContent: string | undefined,\n reason: string,\n truncatedAtMs?: number\n ): void {\n // If currently streaming, commit the stream first\n if (this.isStreaming) {\n this.isStreaming = false;\n this.streamContent = '';\n }\n\n // Find the last assistant message and update it\n for (let i = this.items.length - 1; i >= 0; i--) {\n const item = this.items[i]!;\n if ('role' in item && item.role === 'assistant') {\n item.content = content;\n item.truncationReason = reason;\n item.truncatedAtMs = truncatedAtMs;\n item.originalContent = originalContent;\n this.dirty();\n return;\n }\n }\n\n // No existing assistant message — push the truncated content\n this.items.push({\n role: 'assistant',\n content,\n truncationReason: reason,\n truncatedAtMs: truncatedAtMs,\n originalContent,\n });\n this.dirty();\n }\n\n toolCallResult(toolCallId: string, toolName: string, content: string): void {\n this.items.push({ kind: 'tool_result', toolCallId, toolName, content });\n this.dirty();\n }\n\n /** Find the tool name for a given tool call ID */\n findToolCallName(toolCallId: string): string {\n for (let i = this.items.length - 1; i >= 0; i--) {\n const item = this.items[i]!;\n if (isToolCall(item) && item.id === toolCallId) return item.name;\n }\n return 'tool';\n }\n\n showError(msg: string): void {\n this.items.push({ role: 'system', content: `Error: ${msg}` });\n this.dirty();\n }\n\n // ─── Debug panel ──────────────────────────────────────────────────\n\n /** Log a WebSocket message to the debug panel and (optionally) log file */\n logDebug(direction: 'in' | 'out', raw: any): void {\n const redacted = redactAudio(raw);\n const now = new Date();\n const ts = `${pad2(now.getHours())}:${pad2(now.getMinutes())}:${pad2(now.getSeconds())}`;\n\n // Write to log file (JSON lines, with full redacted payload)\n if (this.debugLogStream) {\n const logLine = JSON.stringify({ ts: now.toISOString(), dir: direction, ...redacted });\n this.debugLogStream.write(logLine + '\\n');\n }\n\n // Add to in-memory debug panel\n const summary = buildDebugSummary(direction, redacted);\n let detail: string;\n try {\n detail = JSON.stringify(redacted, null, 2);\n } catch {\n detail = String(redacted);\n }\n this.debugEntries.push({ direction, summary, detail, ts });\n // Cap at 500 entries to prevent memory growth\n if (this.debugEntries.length > 500) {\n this.debugEntries = this.debugEntries.slice(-300);\n }\n this.debugLinesCache = null;\n this.dirty();\n }\n\n // ─── Private helpers ──────────────────────────────────────────────\n\n private findToolCall(id: string): ToolCallItem | undefined {\n for (let i = this.items.length - 1; i >= 0; i--) {\n const item = this.items[i]!;\n if (isToolCall(item) && item.id === id) return item;\n }\n return undefined;\n }\n\n private dirty(): void {\n this.displayLinesCache = null;\n this.debugLinesCache = null;\n this.scheduleRender();\n }\n\n private restoreTerminal = (): void => {\n process.stdout.write(`${MOUSE_OFF}${CSI}r${ALT_SCREEN_OFF}${SHOW_CURSOR}`);\n };\n\n private updateDimensions(): void {\n this.rows = process.stdout.rows || 24;\n this.cols = process.stdout.columns || 80;\n }\n\n /** Width of the chat (left) panel */\n private chatWidth(): number {\n if (!this.debugVisible) return this.cols;\n // 60% for chat, 40% for debug, with 1 col for divider\n return Math.max(30, Math.floor(this.cols * 0.6) - 1);\n }\n\n /** Width of the debug (right) panel */\n private debugWidth(): number {\n if (!this.debugVisible) return 0;\n return this.cols - this.chatWidth() - 1; // -1 for divider\n }\n\n private scrollHeight(): number {\n return Math.max(1, this.rows - 2);\n }\n\n private pageSize(): number {\n return Math.max(1, this.rows - 4);\n }\n\n // ─── Scroll ───────────────────────────────────────────────────────\n\n private scrollUp(lines: number): void {\n const total = this.getDisplayLines().length;\n const max = Math.max(0, total - this.scrollHeight());\n this.scrollOffset = Math.min(max, this.scrollOffset + lines);\n this.render();\n }\n\n private scrollDown(lines: number): void {\n this.scrollOffset = Math.max(0, this.scrollOffset - lines);\n this.render();\n }\n\n private scrollToTop(): void {\n const total = this.getDisplayLines().length;\n this.scrollOffset = Math.max(0, total - this.scrollHeight());\n this.render();\n }\n\n private scrollToBottom(): void {\n this.scrollOffset = 0;\n this.render();\n }\n\n // ─── Raw stdin parsing ────────────────────────────────────────────\n //\n // We parse stdin directly instead of using readline.emitKeypressEvents\n // because readline doesn't understand SGR mouse sequences and leaks\n // their contents into keypress events as regular characters.\n\n private onData = (data: string): void => {\n for (let i = 0; i < data.length; i++) {\n const ch = data[i]!;\n\n // Accumulating an escape sequence\n if (this.escBuf) {\n this.escBuf += ch;\n\n if (this.escBuf.length === 2) {\n if (ch !== '[') {\n // Not a CSI sequence (Alt+key etc.) — discard\n this.clearEsc();\n }\n continue;\n }\n\n // \\x1B[... — wait for a terminating character (letter or ~)\n if (/[A-Za-z~]/.test(ch)) {\n this.handleCSI(this.escBuf.slice(2, -1), ch);\n this.clearEsc();\n } else if (this.escBuf.length > 32) {\n this.clearEsc(); // safety bail\n }\n continue;\n }\n\n // Start of escape sequence\n if (ch === '\\x1B') {\n this.escBuf = '\\x1B';\n this.escTimer = setTimeout(() => {\n // Bare ESC with no follow-up — ignore\n this.escBuf = '';\n this.escTimer = null;\n }, 100);\n continue;\n }\n\n // Regular byte\n this.handleByte(ch);\n }\n };\n\n private clearEsc(): void {\n this.escBuf = '';\n if (this.escTimer) {\n clearTimeout(this.escTimer);\n this.escTimer = null;\n }\n }\n\n /** Handle a parsed CSI sequence: params is everything between \\x1B[ and the final char */\n private handleCSI(params: string, code: string): void {\n // Mouse SGR: \\x1B[<button;col;rowM (press) or m (release)\n if (params.startsWith('<') && (code === 'M' || code === 'm')) {\n if (code === 'm') return; // ignore button release\n const parts = params.slice(1).split(';');\n if (parts.length >= 1) {\n const button = parseInt(parts[0]!, 10);\n if (button === 64) this.scrollUp(3);\n else if (button === 65) this.scrollDown(3);\n }\n return;\n }\n\n // Arrow keys (no params)\n if (!params) {\n if (code === 'A') {\n this.scrollUp(1);\n return;\n }\n if (code === 'B') {\n this.scrollDown(1);\n return;\n }\n // Home/End (xterm-style)\n if (code === 'H') {\n this.scrollToTop();\n return;\n }\n if (code === 'F') {\n this.scrollToBottom();\n return;\n }\n }\n\n // Tilde sequences: Page Up (5~), Page Down (6~), Home (1~), End (4~)\n if (code === '~') {\n if (params === '5') {\n this.scrollUp(this.pageSize());\n return;\n }\n if (params === '6') {\n this.scrollDown(this.pageSize());\n return;\n }\n if (params === '1') {\n this.scrollToTop();\n return;\n }\n if (params === '4') {\n this.scrollToBottom();\n return;\n }\n }\n }\n\n /** Handle a single non-escape byte */\n private handleByte(ch: string): void {\n const code = ch.charCodeAt(0);\n\n // Ctrl+C → exit\n if (code === 0x03) {\n this.stop();\n this.options.onExit();\n return;\n }\n\n // Ctrl+B → page up (less-style)\n if (code === 0x02) {\n this.scrollUp(this.pageSize());\n return;\n }\n\n // Ctrl+F → page down (less-style)\n if (code === 0x06) {\n this.scrollDown(this.pageSize());\n return;\n }\n\n // Ctrl+D → toggle debug panel visibility (always available)\n if (code === 0x04) {\n this.debugPanelVisible = !this.debugPanelVisible;\n this.displayLinesCache = null;\n this.debugLinesCache = null;\n this.render();\n return;\n }\n\n // Ctrl+O → toggle detail expansion (tool calls + debug messages)\n if (code === 0x0f) {\n this.expandDetails = !this.expandDetails;\n this.displayLinesCache = null;\n this.debugLinesCache = null;\n this.render();\n return;\n }\n\n // Enter\n if (code === 0x0d) {\n this.handleEnter();\n return;\n }\n\n // Backspace (0x7F on most terminals, 0x08 on some)\n if (code === 0x7f || code === 0x08) {\n if (this.inputBuffer.length > 0) {\n this.inputBuffer = this.inputBuffer.slice(0, -1);\n this.renderInputLine();\n }\n return;\n }\n\n // Ignore other control characters\n if (code < 0x20) return;\n\n // Printable character → add to input\n this.inputBuffer += ch;\n this.renderInputLine();\n }\n\n private handleEnter(): void {\n const text = this.inputBuffer.trim();\n this.inputBuffer = '';\n if (!text) {\n this.renderInputLine();\n return;\n }\n if (text.toLowerCase() === 'exit' || text.toLowerCase() === 'quit') {\n this.stop();\n this.options.onExit();\n return;\n }\n this.items.push({ role: 'user', content: text });\n this.scrollOffset = 0;\n this.displayLinesCache = null;\n this.render();\n this.options.onSend(text);\n }\n\n // ─── Events ───────────────────────────────────────────────────────\n\n private onResize = (): void => {\n this.updateDimensions();\n process.stdout.write(`${CSI}1;${Math.max(1, this.rows - 2)}r`);\n this.displayLinesCache = null;\n this.debugLinesCache = null;\n this.render();\n };\n\n // ─── Rendering ────────────────────────────────────────────────────\n\n private scheduleRender(): void {\n if (!this.started || this.renderTimer) return;\n this.renderTimer = setTimeout(() => {\n this.renderTimer = null;\n this.render();\n }, 30);\n }\n\n private getDisplayLines(): string[] {\n if (!this.displayLinesCache) {\n this.displayLinesCache = this.buildDisplayLines();\n }\n return this.displayLinesCache;\n }\n\n private getDebugLines(): string[] {\n if (!this.debugLinesCache) {\n this.debugLinesCache = this.buildDebugLines();\n }\n return this.debugLinesCache;\n }\n\n private render(): void {\n if (!this.started) return;\n this.updateDimensions();\n\n const sh = this.scrollHeight();\n const displayLines = this.getDisplayLines();\n const total = displayLines.length;\n\n // Clamp scroll offset\n const maxOff = Math.max(0, total - sh);\n if (this.scrollOffset > maxOff) this.scrollOffset = maxOff;\n\n // Select visible slice for chat\n let visible: string[];\n if (total <= sh) {\n visible = [...new Array<string>(sh - total).fill(''), ...displayLines];\n } else {\n const end = total - this.scrollOffset;\n const start = end - sh;\n visible = displayLines.slice(start, end);\n }\n\n const buf: string[] = [HIDE_CURSOR];\n\n if (this.debugVisible) {\n this.renderSplitScreen(buf, visible, sh);\n } else {\n for (let i = 0; i < sh; i++) {\n buf.push(moveTo(i + 1, 1), visible[i] || '', CLEAR_EOL);\n }\n }\n\n // Separator with hints (row R-1)\n buf.push(moveTo(this.rows - 1, 1), this.buildSeparator(), CLEAR_EOL);\n\n // Input (row R)\n buf.push(moveTo(this.rows, 1), `${BLUE}You:${RESET} ${this.inputBuffer}${CLEAR_EOL}`);\n\n buf.push(SHOW_CURSOR);\n process.stdout.write(buf.join(''));\n }\n\n private renderSplitScreen(buf: string[], chatVisible: string[], sh: number): void {\n const cw = this.chatWidth();\n const dw = this.debugWidth();\n const divCol = cw + 1;\n\n // Debug panel: auto-scroll to bottom (always show latest)\n const debugLines = this.getDebugLines();\n const debugTotal = debugLines.length;\n let debugVisible: string[];\n if (debugTotal <= sh) {\n debugVisible = [...new Array<string>(sh - debugTotal).fill(''), ...debugLines];\n } else {\n debugVisible = debugLines.slice(debugTotal - sh);\n }\n\n for (let i = 0; i < sh; i++) {\n const chatLine = truncateAnsi(chatVisible[i] || '', cw);\n const debugLine = truncateAnsi(debugVisible[i] || '', dw);\n buf.push(\n moveTo(i + 1, 1),\n chatLine,\n CLEAR_EOL, // clear to end handles rest, but we need to position divider\n moveTo(i + 1, divCol),\n `${DIM}\\u2502${RESET}`,\n debugLine\n );\n // Clear remainder of the debug area\n buf.push(CLEAR_EOL);\n }\n }\n\n private renderInputLine(): void {\n process.stdout.write(\n `${moveTo(this.rows, 1)}${BLUE}You:${RESET} ${this.inputBuffer}${CLEAR_EOL}`\n );\n }\n\n // ─── Separator ────────────────────────────────────────────────────\n\n private buildSeparator(): string {\n const hints: string[] = [];\n\n if (this.scrollOffset > 0) {\n hints.push(`\\u2191${this.scrollOffset}`);\n }\n\n const hasDetails =\n this.items.some((i) => isToolCall(i) || isToolResult(i)) || this.options.debug;\n if (hasDetails) {\n hints.push(`^O ${this.expandDetails ? 'collapse' : 'details'}`);\n }\n\n if (this.options.debug) {\n hints.push(`^D ${this.debugPanelVisible ? 'hide' : 'show'} debug`);\n }\n\n const lineWidth = Math.min(this.cols, 60);\n\n if (!hints.length) {\n return `${GRAY}${'\\u2500'.repeat(lineWidth)}${RESET}`;\n }\n\n const hintStr = ` ${hints.join(' ')} `;\n const dashes = Math.max(0, lineWidth - hintStr.length);\n const left = Math.max(2, Math.floor(dashes / 2));\n const right = Math.max(2, dashes - left);\n return `${GRAY}${'\\u2500'.repeat(left)}${hintStr}${'\\u2500'.repeat(right)}${RESET}`;\n }\n\n // ─── Chat display line building ───────────────────────────────────\n\n private buildDisplayLines(): string[] {\n const lines: string[] = [];\n const w = this.chatWidth();\n\n for (const item of this.items) {\n if (isToolCall(item)) {\n this.appendToolCallLines(lines, item, w);\n } else if (isToolResult(item)) {\n this.appendToolResultLines(lines, item, w);\n } else {\n this.appendMessageLines(lines, item, w);\n }\n lines.push('');\n }\n\n if (this.isStreaming) {\n this.appendStreamLines(lines, w);\n }\n\n return lines;\n }\n\n private appendToolCallLines(lines: string[], tc: ToolCallItem, width: number): void {\n const status = tc.done ? 'Called' : 'Calling';\n const summary = ` ${GRAY}${status} ${tc.name}${tc.done ? '' : '...'}${RESET}`;\n\n if (!this.expandDetails) {\n lines.push(summary);\n return;\n }\n\n lines.push(summary);\n if (tc.args) {\n let formatted = tc.args;\n try {\n formatted = JSON.stringify(JSON.parse(tc.args), null, 2);\n } catch {\n // use raw\n }\n const indent = ' ';\n for (const argLine of formatted.split('\\n')) {\n for (const wl of this.wrapText(argLine, width - indent.length)) {\n lines.push(`${indent}${GRAY}${wl}${RESET}`);\n }\n }\n }\n }\n\n private appendToolResultLines(lines: string[], tr: ToolResultItem, width: number): void {\n if (!this.expandDetails) {\n // Collapsed: show truncated one-liner\n const maxLen = width - 10;\n const preview = tr.content.replace(/\\n/g, ' ').slice(0, maxLen);\n const truncated = preview.length < tr.content.length ? '...' : '';\n lines.push(` ${GRAY}\\u2192 ${tr.toolName}: ${preview}${truncated}${RESET}`);\n return;\n }\n\n lines.push(` ${GRAY}\\u2192 ${tr.toolName} result:${RESET}`);\n let formatted = tr.content;\n try {\n formatted = JSON.stringify(JSON.parse(tr.content), null, 2);\n } catch {\n // use raw\n }\n const indent = ' ';\n for (const resultLine of formatted.split('\\n')) {\n for (const wl of this.wrapText(resultLine, width - indent.length)) {\n lines.push(`${indent}${GRAY}${wl}${RESET}`);\n }\n }\n }\n\n private appendMessageLines(lines: string[], msg: ChatMessage, width: number): void {\n if (msg.role === 'system') {\n for (const para of msg.content.split('\\n')) {\n for (const wl of this.wrapText(para, width - 2)) {\n lines.push(` ${GRAY}${wl}${RESET}`);\n }\n }\n return;\n }\n\n const isUser = msg.role === 'user';\n const label = isUser ? `${BLUE}You:${RESET} ` : `${GREEN}Assistant:${RESET} `;\n const labelWidth = isUser ? 5 : 12;\n const indent = ' '.repeat(labelWidth);\n let first = true;\n\n // Strip the \"—interrupted\" suffix from content for display\n const displayContent = msg.truncationReason\n ? msg.content.replace(/—interrupted$/, '')\n : msg.content;\n\n for (const para of displayContent.split('\\n')) {\n for (const wl of this.wrapText(para, width - labelWidth)) {\n lines.push(first ? label + wl : indent + wl);\n first = false;\n }\n }\n\n // Truncation indicator\n if (msg.truncationReason) {\n const reasonLabel = getTruncationLabel(msg.truncationReason, msg.truncatedAtMs);\n lines.push(`${indent}${YELLOW}[${reasonLabel}]${RESET}`);\n\n // Show unspoken text in dim italic gray\n const extra = getExtraContent(msg.content, msg.originalContent);\n if (extra) {\n for (const para of extra.split('\\n')) {\n for (const wl of this.wrapText(para, width - labelWidth)) {\n lines.push(`${indent}${DIM_ITALIC_GRAY}${wl}${RESET}`);\n }\n }\n }\n }\n }\n\n private appendStreamLines(lines: string[], width: number): void {\n const label = `${GREEN}Assistant:${RESET} `;\n const labelWidth = 12;\n const indent = ' '.repeat(labelWidth);\n\n if (!this.streamContent) {\n lines.push(label);\n return;\n }\n\n let first = true;\n for (const para of this.streamContent.split('\\n')) {\n for (const wl of this.wrapText(para, width - labelWidth)) {\n lines.push(first ? label + wl : indent + wl);\n first = false;\n }\n }\n }\n\n // ─── Debug display line building ──────────────────────────────────\n\n private buildDebugLines(): string[] {\n const lines: string[] = [];\n const dw = this.debugWidth();\n if (dw <= 0) return lines;\n\n for (const entry of this.debugEntries) {\n const color = entry.direction === 'in' ? ORANGE : LIGHT_BLUE;\n const arrow = entry.direction === 'in' ? '\\u25bc' : '\\u25b2'; // ▼ in, ▲ out\n const prefix = `${DIM}${entry.ts}${RESET} ${color}${arrow}${RESET} `;\n const prefixWidth = entry.ts.length + 3; // \"HH:MM:SS ▼ \"\n\n if (!this.expandDetails) {\n // Collapsed: single summary line, truncated\n const maxSummary = dw - prefixWidth;\n const summaryText = entry.summary.slice(0, maxSummary);\n lines.push(`${prefix}${color}${summaryText}${RESET}`);\n } else {\n // Expanded: summary + full detail\n lines.push(`${prefix}${color}${entry.summary}${RESET}`);\n const indent = ' '.repeat(prefixWidth);\n for (const detailLine of entry.detail.split('\\n')) {\n for (const wl of this.wrapText(detailLine, dw - prefixWidth)) {\n lines.push(`${indent}${color}${DIM}${wl}${RESET}`);\n }\n }\n lines.push(''); // blank line between expanded entries\n }\n }\n\n return lines;\n }\n\n // ─── Text utilities ───────────────────────────────────────────────\n\n private wrapText(text: string, maxWidth: number): string[] {\n if (maxWidth <= 0) maxWidth = 1;\n if (!text) return [''];\n if (text.length <= maxWidth) return [text];\n\n const words = text.split(' ');\n const result: string[] = [];\n let current = '';\n\n for (const word of words) {\n if (!current) {\n current = word;\n } else if (current.length + 1 + word.length <= maxWidth) {\n current += ' ' + word;\n } else {\n result.push(current);\n current = word;\n }\n }\n if (current) result.push(current);\n\n return result.length ? result : [''];\n }\n}\n\n// ─── Module-level helpers ─────────────────────────────────────────────────────\n\nfunction pad2(n: number): string {\n return n < 10 ? `0${n}` : String(n);\n}\n\n/** Truncate a string (which may contain ANSI codes) to fit in maxCols visible characters */\nfunction truncateAnsi(s: string, maxCols: number): string {\n if (maxCols <= 0) return '';\n let visible = 0;\n let i = 0;\n while (i < s.length && visible < maxCols) {\n if (s[i] === '\\x1B') {\n // Skip ANSI sequence\n const end = s.indexOf('m', i);\n if (end !== -1) {\n i = end + 1;\n } else {\n i++;\n }\n } else {\n visible++;\n i++;\n }\n }\n // Append RESET to close any open ANSI sequences\n return s.slice(0, i) + RESET;\n}\n\n/** Redact audio PCM buffers from WebSocket messages for debug display (does not redact text content) */\nfunction redactAudio(msg: any): any {\n if (!msg || typeof msg !== 'object') return msg;\n const clone = { ...msg };\n // Redact voice.audio CUSTOM events\n if (clone.type === 'CUSTOM' && clone.value && typeof clone.value === 'object') {\n const name = clone.name || '';\n if (name === 'voice.audio' && clone.value.data) {\n clone.value = { ...clone.value, data: '[audio]' };\n }\n }\n return clone;\n}\n\n/** Build a one-line summary of a WebSocket message for the collapsed debug view */\nfunction buildDebugSummary(_direction: 'in' | 'out', msg: any): string {\n if (!msg || typeof msg !== 'object') return String(msg);\n\n if (msg.type === 'CUSTOM') {\n const name = msg.name || '?';\n // For audio, just show the event name\n if (name === 'voice.audio') return name;\n // For other CUSTOM events, show name + compact value hint\n if (msg.value && typeof msg.value === 'object') {\n const keys = Object.keys(msg.value);\n if (keys.length <= 3) {\n return `${name} {${keys.join(', ')}}`;\n }\n return `${name} {${keys.length} keys}`;\n }\n return name;\n }\n\n // Standard AG-UI events: TEXT_MESSAGE_CONTENT, TOOL_CALL_START, etc.\n const type = msg.type || '?';\n if (msg.delta) {\n const preview = msg.delta.length > 30 ? msg.delta.slice(0, 30) + '...' : msg.delta;\n return `${type} \"${preview}\"`;\n }\n if (msg.toolCallName) {\n return `${type} ${msg.toolCallName}`;\n }\n return type;\n}\n","/**\n * Audio I/O for CLI using SoX (Sound eXchange)\n *\n * Uses the `rec` command for microphone capture and `play` for audio playback.\n * SoX is cross-platform and available via:\n * macOS: brew install sox\n * Linux: apt install sox\n * Windows: choco install sox\n */\n\nimport { spawn, execSync, spawnSync, type ChildProcess } from 'child_process';\nimport { EventEmitter } from 'events';\nimport * as readline from 'readline';\n\nconst SAMPLE_RATE = 24000;\n// 100ms of PCM16 audio at 24kHz mono = 4800 bytes\nconst MIC_CHUNK_BYTES = 4800;\n\nexport interface AudioDevice {\n id: string;\n name: string;\n isDefault: boolean;\n}\n\n/** Check if SoX is installed and available */\nexport function checkSoxAvailable(): boolean {\n try {\n execSync('which sox', { stdio: 'pipe' });\n return true;\n } catch {\n return false;\n }\n}\n\n/** List audio input devices via SoX */\nexport async function listInputDevices(): Promise<AudioDevice[]> {\n return listDevices('rec');\n}\n\n/** List audio output devices via SoX */\nexport async function listOutputDevices(): Promise<AudioDevice[]> {\n return listDevices('play');\n}\n\nfunction listDevices(command: string): Promise<AudioDevice[]> {\n return new Promise((resolve) => {\n try {\n // spawnSync avoids shell interpolation — command and args are always separate\n const proc = spawnSync(command, ['--list-devices'], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'pipe'],\n timeout: 5000,\n });\n // SoX outputs device list to stderr; combine both streams to be safe\n const output = (proc.stdout ?? '') + (proc.stderr ?? '');\n\n const devices: AudioDevice[] = [];\n const lines = output.split('\\n');\n for (const line of lines) {\n // Parse lines like: \" Input Device 0 : Built-in Microphone\"\n // or \" Output Device 0 : Built-in Output\"\n const match = line.match(/(?:Input|Output)\\s+Device\\s+(\\d+)\\s*:\\s*(.+)/i);\n if (match && match[1] && match[2]) {\n devices.push({\n id: match[1],\n name: match[2].trim(),\n isDefault: devices.length === 0, // First device is typically the default\n });\n }\n }\n\n // If SoX didn't give us devices, return a default entry\n if (devices.length === 0) {\n devices.push({ id: 'default', name: 'System Default', isDefault: true });\n }\n\n resolve(devices);\n } catch {\n // Fallback to system default\n resolve([{ id: 'default', name: 'System Default', isDefault: true }]);\n }\n });\n}\n\n/** Interactively select an audio device */\nexport async function selectDevice(devices: AudioDevice[], label: string): Promise<AudioDevice> {\n if (devices.length <= 1) {\n return devices[0]!;\n }\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stderr,\n terminal: true,\n });\n\n process.stderr.write(`\\n ${label}:\\n`);\n for (let i = 0; i < devices.length; i++) {\n const dev = devices[i]!;\n const marker = dev.isDefault ? ' (default)' : '';\n process.stderr.write(` ${i + 1}. ${dev.name}${marker}\\n`);\n }\n\n return new Promise((resolve) => {\n const defaultIdx = devices.findIndex((d) => d.isDefault);\n const defaultNum = defaultIdx >= 0 ? defaultIdx + 1 : 1;\n\n rl.question(` Select [${defaultNum}]: `, (answer) => {\n rl.close();\n const num = answer.trim() ? parseInt(answer.trim(), 10) : defaultNum;\n const idx = Math.max(0, Math.min(devices.length - 1, num - 1));\n resolve(devices[idx]!);\n });\n });\n}\n\n/**\n * Microphone capture via SoX `rec`.\n * Streams raw PCM16 signed 16-bit LE mono audio at 24kHz.\n */\nexport class MicCapture {\n private process: ChildProcess | null = null;\n private onData: (pcm16: Buffer) => void;\n private buffer = Buffer.alloc(0);\n\n constructor(onData: (pcm16: Buffer) => void) {\n this.onData = onData;\n }\n\n /** Start recording from the microphone */\n start(deviceId?: string): void {\n const args = [\n '-q', // quiet\n '-t',\n 'raw', // raw PCM output\n '-r',\n String(SAMPLE_RATE),\n '-e',\n 'signed-integer',\n '-b',\n '16', // 16-bit\n '-c',\n '1', // mono\n '-L', // little-endian\n '-', // stdout\n ];\n\n const env = { ...process.env };\n if (deviceId && deviceId !== 'default') {\n env.AUDIODEV = deviceId;\n }\n\n this.process = spawn('rec', args, {\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n this.process.stdout?.on('data', (data: Buffer) => {\n // Accumulate data and emit in consistent chunk sizes\n this.buffer = Buffer.concat([this.buffer, data]);\n while (this.buffer.length >= MIC_CHUNK_BYTES) {\n const chunk = this.buffer.subarray(0, MIC_CHUNK_BYTES);\n this.buffer = this.buffer.subarray(MIC_CHUNK_BYTES);\n this.onData(Buffer.from(chunk));\n }\n });\n\n this.process.stderr?.on('data', (data: Buffer) => {\n // SoX outputs warnings/errors to stderr - ignore unless debugging\n const msg = data.toString().trim();\n if (msg && !msg.includes('WARN')) {\n process.stderr.write(`[mic] ${msg}\\n`);\n }\n });\n\n this.process.on('error', (err) => {\n process.stderr.write(`[mic] Process error: ${err.message}\\n`);\n });\n }\n\n /** Stop recording */\n stop(): void {\n if (this.process) {\n this.process.kill('SIGTERM');\n this.process = null;\n }\n this.buffer = Buffer.alloc(0);\n }\n}\n\n/**\n * Audio playback via SoX `play`.\n * Accepts raw PCM16 signed 16-bit LE mono audio at 24kHz.\n *\n * Streams audio to SoX's stdin so playback begins immediately on the first\n * chunk — no waiting for the full response. Queues back-to-back responses\n * so a second response never kills the first mid-playback.\n *\n * Events:\n * - 'playing': SoX process spawned for a response\n * - 'done': All queued responses finished (or playback was stopped)\n */\nexport class AudioPlayer extends EventEmitter {\n private process: ChildProcess | null = null;\n private deviceId?: string;\n\n // When true, we own the SoX process's stdin and are actively streaming to it.\n // When false with a process, the stdin has been closed and SoX is draining.\n private streaming = false;\n\n // Buffer chunks when another response is already playing\n private pendingChunks: Buffer[] = [];\n private pendingBytes = 0;\n\n // Queue of complete response buffers waiting to play\n private queue: { audio: Buffer; messageId?: string }[] = [];\n\n // Playback position tracking for barge-in\n private currentMessageId?: string;\n private playbackStartTime = 0; // Date.now() when SoX started\n private bytesWritten = 0; // total bytes piped to SoX for duration estimation\n\n constructor(deviceId?: string) {\n super();\n this.deviceId = deviceId;\n }\n\n /** Check if audio is currently playing or queued */\n get isPlaying(): boolean {\n return this.process !== null || this.queue.length > 0;\n }\n\n /** Get the message ID of the currently playing audio */\n get playingMessageId(): string | undefined {\n return this.currentMessageId;\n }\n\n /** Duration of audio written so far in ms */\n private get currentDurationMs(): number {\n // PCM16 mono 24kHz = 48000 bytes/sec\n return (this.bytesWritten / (SAMPLE_RATE * 2)) * 1000;\n }\n\n /**\n * Estimate current playback position in milliseconds.\n * Uses wall-clock time since SoX started playing.\n */\n getPlaybackTimeMs(): number | null {\n if (!this.process || this.playbackStartTime === 0) return null;\n const elapsed = Date.now() - this.playbackStartTime;\n return Math.min(elapsed, this.currentDurationMs);\n }\n\n /**\n * Stream PCM16 audio data for playback.\n * On the first chunk, spawns SoX and begins playback immediately.\n */\n write(pcm16: Buffer): void {\n if (this.process && !this.streaming) {\n // A previous response is still playing/draining — buffer for later\n this.pendingChunks.push(pcm16);\n this.pendingBytes += pcm16.length;\n return;\n }\n\n if (!this.process) {\n this.spawnSoxProcess();\n }\n\n this.process!.stdin!.write(pcm16);\n this.bytesWritten += pcm16.length;\n }\n\n /**\n * End the current audio response.\n * If streaming, closes stdin to let SoX finish playing.\n * If buffering behind another response, adds to the queue.\n */\n endResponse(messageId?: string): void {\n if (this.streaming && this.process) {\n this.currentMessageId = messageId;\n this.streaming = false;\n this.process.stdin!.end();\n } else if (this.pendingChunks.length > 0) {\n const audio = Buffer.concat(this.pendingChunks);\n this.pendingChunks = [];\n this.pendingBytes = 0;\n this.queue.push({ audio, messageId });\n }\n }\n\n /** Stop current playback, discard all queued audio */\n stop(): void {\n this.pendingChunks = [];\n this.pendingBytes = 0;\n this.queue = [];\n this.streaming = false;\n\n const wasPlaying = this.process !== null;\n if (this.process) {\n try {\n this.process.stdin?.destroy();\n this.process.kill('SIGTERM');\n } catch {\n // Ignore\n }\n this.process = null;\n }\n this.currentMessageId = undefined;\n this.playbackStartTime = 0;\n this.bytesWritten = 0;\n if (wasPlaying) {\n this.emit('done');\n }\n }\n\n /** Spawn a SoX `play` process reading raw PCM from stdin */\n private spawnSoxProcess(): void {\n this.bytesWritten = 0;\n this.currentMessageId = undefined;\n\n const args = [\n '-q', // quiet\n '-t',\n 'raw',\n '-r',\n String(SAMPLE_RATE),\n '-e',\n 'signed-integer',\n '-b',\n '16',\n '-c',\n '1',\n '-L', // little-endian\n '-', // read from stdin\n ];\n\n const env = { ...process.env };\n if (this.deviceId && this.deviceId !== 'default') {\n env.AUDIODEV = this.deviceId;\n }\n\n const proc = spawn('play', args, {\n env,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n proc.on('error', (err) => {\n process.stderr.write(`[player] Process error: ${err.message}\\n`);\n });\n\n proc.on('exit', (code, _signal) => {\n // 143 = SIGTERM (normal stop/interrupt)\n if (code !== null && code !== 0 && code !== 143) {\n process.stderr.write(`[player] SoX exited with code ${code}\\n`);\n }\n if (this.process === proc) {\n this.process = null;\n this.streaming = false;\n if (this.queue.length > 0) {\n const next = this.queue.shift()!;\n this.playQueued(next.audio, next.messageId);\n } else {\n this.emit('done');\n }\n }\n });\n\n proc.stderr?.on('data', (data: Buffer) => {\n const msg = data.toString().trim();\n if (msg) {\n process.stderr.write(`[player:sox] ${msg}\\n`);\n }\n });\n\n proc.stdout?.resume();\n\n this.process = proc;\n this.streaming = true;\n this.playbackStartTime = Date.now();\n this.emit('playing');\n }\n\n /** Play a complete pre-buffered response (from the queue) */\n private playQueued(audio: Buffer, messageId?: string): void {\n this.spawnSoxProcess();\n this.currentMessageId = messageId;\n this.process!.stdin!.write(audio);\n this.bytesWritten = audio.length;\n this.process!.stdin!.end();\n this.streaming = false;\n }\n}\n","/**\n * Concierge chat command — interactive chat with the global concierge agent.\n *\n * Supports the same modes as workspace manager chat (text, realtime, voice)\n * but without requiring a workspace.\n */\n\nimport { formatTimestamp, selectFromList } from '../cli-utils';\nimport {\n createConciergeChat,\n getConciergeChat,\n getConciergeChatMessages,\n listConciergeChats,\n type ConciergeChat,\n} from '../lib/concierge-api';\nimport { requireAuth, type AuthenticatedContext } from '../lib/context';\nimport { CLIError } from '../lib/errors';\nimport type { CommandHandlerContext } from '../lib/types';\nimport { buildCliConciergeAppContext } from '../lib/cli-client-context';\nimport { runChatSession, type ChatSession } from '../lib/chat-session';\n\nexport async function conciergeCommand(hctx: CommandHandlerContext): Promise<void> {\n const ctx = requireAuth(hctx.ctx);\n const { args } = hctx;\n\n const chatIdArg = typeof args['chat-id'] === 'string' ? args['chat-id'] : undefined;\n const message = typeof args.message === 'string' ? args.message : undefined;\n\n const chat = await getOrCreateConciergeChat(ctx, chatIdArg, !!message);\n const session = buildConciergeSession(ctx, chat, args);\n await runChatSession(session, args);\n}\n\nfunction buildConciergeSession(\n ctx: AuthenticatedContext,\n chat: ConciergeChat,\n args: Record<string, unknown>\n): ChatSession {\n const wsBase = ctx.envConfig.apiUrl.replace(/^https:/, 'wss:').replace(/^http:/, 'ws:');\n return {\n ctx,\n workspaceUuid: '',\n chatId: chat.id,\n chatUuid: chat.uuid,\n chatTitle: chat.title || chat.uuid,\n aguiEndpointUrl: `${ctx.envConfig.apiUrl}/api/v2/concierge/chats/${chat.id}/chat/agui`,\n wsUrl: `${wsBase}/api/v2/concierge/voice/stream-ws`,\n loadMessages: () => getConciergeChatMessages(ctx, chat.id).catch(() => []),\n label: 'Concierge',\n model: undefined, // concierge doesn't send model field\n appContext: buildCliConciergeAppContext(),\n allowWrite: true,\n trustCwd: !!args['trust-cwd'],\n trustDir: typeof args['trust-dir'] === 'string' ? args['trust-dir'] : undefined,\n };\n}\n\nasync function getOrCreateConciergeChat(\n ctx: AuthenticatedContext,\n chatIdArg: string | undefined,\n skipSelection: boolean\n): Promise<ConciergeChat> {\n if (chatIdArg) {\n const id = Number(chatIdArg);\n if (isNaN(id)) throw new CLIError('--chat-id must be a number');\n return getConciergeChat(ctx, id);\n }\n\n if (skipSelection) {\n const chat = await createConciergeChat(ctx);\n process.stderr.write(`Created concierge chat #${chat.id}\\n`);\n return chat;\n }\n\n const chats = await listConciergeChats(ctx);\n\n const { item: selectedChat, isNew } = await selectFromList(chats, {\n title: 'Select a concierge chat or create a new one',\n labelFn: (c) => c.title || `Chat ${c.uuid.slice(0, 8)}...`,\n detailFn: (c) => formatTimestamp(c.updatedAt),\n emptyMessage: 'No existing concierge chats.',\n allowNew: true,\n newLabel: '+ Start new chat',\n });\n\n if (!selectedChat && !isNew) {\n throw new CLIError('No chat selected.');\n }\n\n if (isNew) {\n const chat = await createConciergeChat(ctx);\n process.stderr.write(`Created concierge chat #${chat.id}\\n`);\n return chat;\n }\n return selectedChat!;\n}\n","/**\n * `gr get-started` / `gr setup` — bootstrap instructions for humans and LLM agents.\n */\n\nimport type { CommandHandlerContext } from '../lib/types';\nimport { requireAuth } from '../lib/context';\n\nconst WEB_SETUP = 'https://app.gravityrail.com/setup';\nconst WEB_GET_STARTED = 'https://app.gravityrail.com/get-started';\n\nconst HUMAN_GUIDE = `Gravity Rail — getting started\n\n1. Authenticate: gr login --env prod\n Confirm: gr whoami\n\n2. Recommended path — concierge (no workspace required):\n gr concierge chat --allow-write\n The concierge can create your org (auto-created on first login), list products,\n start Stripe checkout, and create your first workspace.\n\n3. Verify workspaces: gr workspaces list\n\n4. Web wizards (human-friendly): ${WEB_SETUP} and ${WEB_GET_STARTED}\n\nHeadless boundary: Stripe checkout needs a human in a browser — the concierge returns\na checkout URL; an agent should hand that link to the user, not loop on payment.\n\nAgent-readable steps: gr get-started --format llm\n`;\n\nconst LLM_GUIDE = `# Gravity Rail CLI bootstrap (agent instructions)\n\n## Preconditions\n- Install: \\`npm install -g @gravity-rail/cli\\` or \\`npx @gravity-rail/cli\\`\n- Authenticate: \\`gr login --env prod\\` (interactive OAuth). Verify with \\`gr whoami\\`.\n- **Monorepo dev:** from gravity-team with Docker dev up, use \\`yarn gr <cmd> --realm superadmin\\` (reads \\`dev-realms.json\\`; no browser). Rebuild: \\`yarn workspace @gravity-rail/gr-cli build\\`.\n\n## Important facts\n- **Agents/CI:** do not leave stdin open on read-only commands; use \\`GRAVITY_RAIL_API_KEY\\` or redirect stdin from /dev/null. Commands only read stdin when \\`--data\\`/\\`--file\\` is passed.\n- Use \\`--env dev|staging|prod\\` (default prod) so credentials match the target; \\`gr whoami\\` shows the active env.\n- After login, an **organization is created automatically** — do not create a duplicate org unless \\`gr organizations list\\` is empty.\n- **Workspace is required** for workflow/agent/task commands (\\`-w <workspace-uuid>\\`).\n- **Concierge does not require \\`-w\\`** — use it for first-run setup.\n\n## Recommended path (concierge-driven)\n\\`\\`\\`bash\ngr concierge chat --allow-write --message \"Help me set up my first Gravity Rail workspace\"\n\\`\\`\\`\nFlags for unattended turns:\n- \\`--message\\` / \\`-m\\`: single-turn (non-interactive)\n- \\`--auto-approve\\`: skip HITL tool approval where policy allows\n- \\`--allow-write\\`: required for create/update tools\n\nThe concierge can: list/create orgs, list org/workspace products, create Stripe checkout sessions, create workspace specs, and \\`create_workspace\\`.\n\n## Manual CLI path (if not using concierge)\n1. \\`gr whoami\\` — confirm account\n2. \\`gr organizations list\\` — note org slug/UUID\n3. \\`gr concierge chat\\` OR web: ${WEB_GET_STARTED}\n4. Product purchase: concierge returns Stripe checkout URL → **human must complete in browser**\n5. \\`gr workspaces list\\` — pick workspace UUID for \\`-w\\`\n\n## Support (account-level, no workspace)\n\\`\\`\\`bash\ngr support create --type question --title \"...\" --description \"...\" --allow-write\ngr support list\n\\`\\`\\`\n\n## Web fallbacks\n- Concierge / setup: ${WEB_SETUP}\n- Wizard: ${WEB_GET_STARTED}\n\n## Headless limits (do not retry forever)\n- Stripe payment / checkout: requires human browser\n- OAuth login: requires human browser\n- Directory trust for future local-file tools: use \\`--trust-cwd\\` only after user confirms files are safe\n\n## Local project files (CLI only)\nAfter directory trust + \\`--allow-write\\`, the concierge can use \\`read_local_file\\`, \\`list_local_dir\\`, \\`write_local_file\\` (client-executed via HITL).\n\n## Verify success\n\\`gr workspaces list\\` then \\`gr workflows list -w <uuid>\\` or \\`gr agents list -w <uuid>\\`\n`;\n\nexport async function getStartedCommand(hctx: CommandHandlerContext): Promise<void> {\n const format = hctx.args.format ?? hctx.args.agent;\n const isLlm =\n format === 'llm' || format === 'agent' || hctx.args['format'] === 'llm' || !!hctx.args.agent;\n\n if (!isLlm) {\n try {\n requireAuth(hctx.ctx);\n } catch {\n // Pre-login users can still read the guide.\n }\n process.stdout.write(HUMAN_GUIDE);\n return;\n }\n\n process.stdout.write(LLM_GUIDE);\n}\n","import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';\nimport { execSync } from 'child_process';\nimport { join } from 'path';\nimport type { AuthenticatedContext } from '../lib/context';\nimport { CLIError } from '../lib/errors';\nimport { stderr } from '../lib/output';\n\nexport async function devImportLocalCommand(\n ctx: AuthenticatedContext,\n workspace: string\n): Promise<void> {\n stderr(`Exporting workspace ${workspace}...`);\n const exportData = await ctx.apiClient.exportWorkspace(workspace);\n\n stderr('Export successful!');\n stderr(` Workflows: ${(exportData.workflows || []).length}`);\n stderr(` Tasks: ${(exportData.tasks || []).length}`);\n stderr(` Data Types: ${(exportData.dataTypes || []).length}`);\n stderr(` Sites: ${(exportData.sites || []).length}`);\n\n const slug = workspace.slice(0, 8);\n const importCacheDir = join(ctx.credentialsManager.getCacheDir(), 'imports');\n if (!existsSync(importCacheDir)) {\n mkdirSync(importCacheDir, { recursive: true });\n }\n const filename = `ws-${slug}-${workspace}.json`;\n const filepath = join(importCacheDir, filename);\n writeFileSync(filepath, JSON.stringify(exportData, null, 2));\n stderr(`Saved to: ${filepath}`);\n\n stderr('Running dev:restore...');\n const rootDir = findProjectRoot();\n const relativePath = filepath.replace(rootDir + '/', '');\n\n try {\n const result = execSync(`yarn dev:restore ${relativePath}`, {\n cwd: rootDir,\n stdio: 'pipe',\n encoding: 'utf-8',\n });\n process.stderr.write(result);\n\n const failed =\n (result.includes('Failed/Skipped: ') && !result.includes('Failed/Skipped: 0')) ||\n result.includes('Successfully restored: 0');\n\n if (failed) throw new CLIError('Import failed');\n } catch (error: unknown) {\n if (error instanceof CLIError) throw error;\n const execError = error as { stdout?: string; stderr?: string };\n if (execError.stdout) process.stderr.write(execError.stdout);\n if (execError.stderr) process.stderr.write(execError.stderr);\n throw new CLIError('dev:restore failed');\n }\n\n stderr(`Import complete: ${workspace}`);\n}\n\nfunction findProjectRoot(): string {\n let dir = process.cwd();\n while (dir !== '/') {\n const pkgPath = join(dir, 'package.json');\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n if (pkg.workspaces) return dir;\n } catch {\n // continue\n }\n }\n dir = join(dir, '..');\n }\n return process.cwd();\n}\n","import { GravityRailClient } from '@gravity-rail/sdk';\nimport { performOAuthFlow } from '../cli-utils';\nimport type { CommandContext } from '../lib/context';\nimport { stderr } from '../lib/output';\n\nexport async function loginCommand(ctx: CommandContext): Promise<void> {\n const { accessToken } = await performOAuthFlow({\n env: ctx.env,\n envConfig: ctx.envConfig,\n credentialsManager: ctx.credentialsManager,\n });\n\n const apiClient = new GravityRailClient(accessToken, ctx.envConfig.apiUrl);\n const account = await apiClient.getUserAccount();\n stderr(`Logged in as ${account.name} (${account.email})`);\n}\n\nexport async function logoutCommand(ctx: CommandContext): Promise<void> {\n ctx.credentialsManager.clear(ctx.env);\n stderr(`Credentials cleared for ${ctx.env}`);\n}\n","import type { ApiClient } from '@gravity-rail/client';\nimport type { Chat } from '@gravity-rail/sdk';\nimport { formatTimestamp, selectFromList } from '../cli-utils';\nimport { CLIError } from '../lib/errors';\nimport { requireAuth, type AuthenticatedContext } from '../lib/context';\nimport type { CommandHandlerContext } from '../lib/types';\nimport { buildCliConciergeAppContext } from '../lib/cli-client-context';\nimport { runChatSession, type ChatSession } from '../lib/chat-session';\n\n// ─── Entry point ─────────────────────────────────────────────────────────────\n\nexport async function manageCommand(hctx: CommandHandlerContext): Promise<void> {\n const ctx = requireAuth(hctx.ctx);\n const { workspace, args } = hctx;\n\n const asMember = typeof args['as-member'] === 'string' ? args['as-member'] : undefined;\n const chatIdArg = typeof args['chat-id'] === 'string' ? args['chat-id'] : undefined;\n const message = typeof args.message === 'string' ? args.message : undefined;\n\n const chat = await getOrCreateChat(ctx, workspace, chatIdArg, asMember, 'manager', !!message);\n const session = buildWorkspaceSession(ctx, workspace, chat, 'Workspace Manager', {\n appContext: buildCliConciergeAppContext(),\n allowWrite: true,\n trustCwd: !!args['trust-cwd'],\n trustDir: typeof args['trust-dir'] === 'string' ? args['trust-dir'] : undefined,\n });\n // Print the chat ID up-front so a user who Ctrl-Cs mid-stream can still\n // reattach with `gr manage --chat-id ${id}`. The post-session repeat\n // (after `runChatSession`) is intentional — a second \"Chat #N\" line on\n // clean exit gives copy/paste-friendly anchors at both ends of long\n // streams without any extra parsing.\n process.stderr.write(`Chat #${session.chatId}\\n`);\n await runChatSession(session, args);\n process.stderr.write(`Chat #${session.chatId}\\n`);\n}\n\nexport async function chatCommand(hctx: CommandHandlerContext): Promise<void> {\n const ctx = requireAuth(hctx.ctx);\n const { workspace, args } = hctx;\n const chatIdArg = typeof args['chat-id'] === 'string' ? args['chat-id'] : undefined;\n const workflowId = typeof args.workflow === 'string' ? args.workflow : undefined;\n const memberId = typeof args.member === 'string' ? args.member : undefined;\n\n let chat: Chat;\n if (chatIdArg) {\n const id = Number(chatIdArg);\n if (isNaN(id)) throw new CLIError('--chat-id must be a number');\n chat = await ctx.apiClient.getChat(workspace, id);\n } else if (workflowId) {\n chat = await createAssignmentChat(ctx.apiClient, workspace, Number(workflowId), memberId);\n } else if (memberId) {\n chat = await createMemberChat(ctx.apiClient, workspace, memberId);\n } else {\n throw new CLIError(\n 'Specify --workflow <id>, --member <id>, or --chat-id <id>.\\n' +\n 'Use \"gr manage\" for workspace manager chats.'\n );\n }\n\n const session = buildWorkspaceSession(ctx, workspace, chat, 'Chat');\n await runChatSession(session, args);\n}\n\n// ─── Session builder ─────────────────────────────────────────────────────────\n\nfunction buildWorkspaceSession(\n ctx: AuthenticatedContext,\n workspace: string,\n chat: Chat,\n label: string,\n extra?: Pick<ChatSession, 'appContext' | 'allowWrite' | 'trustCwd' | 'trustDir'>\n): ChatSession {\n const wsBase = ctx.envConfig.apiUrl.replace(/^https:/, 'wss:').replace(/^http:/, 'ws:');\n return {\n ctx,\n workspaceUuid: workspace,\n chatId: chat.id,\n chatUuid: chat.uuid,\n chatTitle: chat.title || chat.uuid,\n aguiEndpointUrl: `${ctx.envConfig.apiUrl}/api/v2/w/${workspace}/web-chat/${chat.id}/chat/agui`,\n wsUrl: `${wsBase}/api/v2/w/${workspace}/realtime/stream-ws`,\n loadMessages: () => ctx.apiClient.getChatMessages(workspace, chat.id, 50).catch(() => []),\n label,\n model: 'manager',\n ...extra,\n };\n}\n\n// ─── Chat selection ──────────────────────────────────────────────────────────\n\nasync function getOrCreateChat(\n ctx: AuthenticatedContext,\n workspace: string,\n chatIdArg: string | undefined,\n asMemberId: string | undefined,\n chatType: 'manager' | 'assignment' | 'member' | 'contributor' | 'developer',\n skipSelection: boolean = false\n): Promise<Chat> {\n if (chatIdArg) {\n const chatId = Number(chatIdArg);\n if (isNaN(chatId)) throw new CLIError('--chat-id must be a number');\n return ctx.apiClient.getChat(workspace, chatId);\n }\n\n if (skipSelection) {\n return createManagerChat(ctx.apiClient, workspace, asMemberId);\n }\n\n const chatsResponse = await ctx.apiClient.getChats(workspace, {\n chatType,\n sortBy: 'updatedAt',\n sortOrder: 'desc',\n pageSize: 20,\n });\n const chats = chatsResponse.items || [];\n\n const { item: selectedChat, isNew } = await selectFromList(chats, {\n title: 'Select a chat or create a new one',\n labelFn: (chat) => chat.title || `Chat ${chat.uuid.slice(0, 8)}...`,\n detailFn: (chat) => {\n const time = formatTimestamp(chat.updatedAt);\n const msgCount = chat.messageCount || 0;\n return `${msgCount} msg${msgCount !== 1 ? 's' : ''} - ${time}`;\n },\n emptyMessage: 'No existing chats.',\n allowNew: true,\n newLabel: '+ Start new chat',\n });\n\n if (!selectedChat && !isNew) {\n throw new CLIError('No chat selected.');\n }\n\n if (isNew) {\n return createManagerChat(ctx.apiClient, workspace, asMemberId);\n }\n return selectedChat!;\n}\n\nasync function createManagerChat(\n apiClient: ApiClient,\n workspace: string,\n asMemberId: string | undefined\n): Promise<Chat> {\n const data: Record<string, any> = {\n chatType: 'manager',\n channel: 'web-chat',\n };\n if (asMemberId) {\n data.memberId = Number(asMemberId);\n }\n const chat = await apiClient.createChat(workspace, data as any);\n process.stderr.write(`Created chat #${chat.id}\\n`);\n return chat;\n}\n\nasync function createAssignmentChat(\n apiClient: ApiClient,\n workspace: string,\n workflowId: number,\n asMemberId: string | undefined\n): Promise<Chat> {\n if (isNaN(workflowId)) throw new CLIError('--workflow must be a number');\n const data: Record<string, any> = {\n chatType: 'assignment',\n channel: 'web-chat',\n workflowId,\n };\n if (asMemberId) {\n data.memberId = Number(asMemberId);\n }\n const chat = await apiClient.createChat(workspace, data as any);\n process.stderr.write(`Created assignment chat #${chat.id} (workflow ${workflowId})\\n`);\n return chat;\n}\n\nasync function createMemberChat(\n apiClient: ApiClient,\n workspace: string,\n memberId: string\n): Promise<Chat> {\n const id = Number(memberId);\n if (isNaN(id)) throw new CLIError('--member must be a number');\n const data: Record<string, any> = {\n chatType: 'member',\n channel: 'web-chat',\n memberId: id,\n };\n const chat = await apiClient.createChat(workspace, data as any);\n process.stderr.write(`Created DM chat #${chat.id} (member ${memberId})\\n`);\n return chat;\n}\n","import type { AuthenticatedContext } from '../lib/context';\nimport { outputData, type TableColumn } from '../lib/output';\n\n// The return type of getMyOrganizations references the admin-only\n// AdminAccountOrgMembership type, which is not re-exported from the public\n// @gravity-rail/sdk surface. We infer the element shape from the runtime\n// method signature here.\ntype OrgMembership = Awaited<\n ReturnType<AuthenticatedContext['apiClient']['getMyOrganizations']>\n>[number];\n\nconst COLUMNS: TableColumn<OrgMembership>[] = [\n { header: 'NAME', getValue: (o) => o.organizationName || '', maxWidth: 35 },\n { header: 'SLUG', getValue: (o) => o.organizationSlug || '', maxWidth: 25 },\n { header: 'UUID', getValue: (o) => o.organizationUuid },\n { header: 'ROLE', getValue: (o) => o.role || '' },\n];\n\nexport async function organizationsListCommand(ctx: AuthenticatedContext): Promise<void> {\n const organizations = await ctx.apiClient.getMyOrganizations();\n outputData(organizations, ctx, COLUMNS);\n}\n","import type { Account } from '@gravity-rail/sdk';\nimport type { AuthenticatedContext } from '../lib/context';\nimport { outputSingle, type TableColumn } from '../lib/output';\n\nconst COLUMNS: TableColumn<Account>[] = [\n { header: 'NAME', getValue: (a) => a.name || '', maxWidth: 30 },\n { header: 'EMAIL', getValue: (a) => a.email || '', maxWidth: 40 },\n { header: 'UUID', getValue: (a) => a.uuid },\n { header: 'ENV', getValue: () => '' },\n { header: 'SUPERUSER', getValue: (a) => (a.isSuperuser ? 'yes' : 'no') },\n];\n\nexport async function whoamiCommand(ctx: AuthenticatedContext): Promise<void> {\n const account = await ctx.apiClient.getUserAccount();\n const columns = COLUMNS.map((col) =>\n col.header === 'ENV' ? { ...col, getValue: () => ctx.env } : col\n );\n outputSingle(account, ctx, columns);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2BO,SAAS,aAAa,MAAmC;AAC7D,MAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,EAAG,QAAO;AACrE,QAAM,MAAM;AACZ,SACG,MAAM,QAAQ,IAAI,KAAK,MACtB,iBAAiB,OACd,UAAU,QAAQ,IAAI,SAAS,UAAa,OAAO,IAAI,SAAS;AAE1E;AAOO,SAAS,wBAAwB,MAMtC;AACC,MAAI,CAAC,QAAQ,OAAO,SAAS,SAAU,QAAO;AAC9C,QAAM,MAAM;AACZ,MAAI,CAAC,MAAM,QAAQ,IAAI,KAAK,KAAK,OAAO,IAAI,SAAS,SAAU,QAAO;AAGtE,MAAI,OAAO,IAAI,eAAe,SAAU,QAAO;AAG/C,MAAI,OAAO,IAAI,UAAU,YAAY,OAAO,IAAI,aAAa,SAAU,QAAO;AAE9E,SAAO;AACV;AAGO,SAAS,0BAA0B,MAIxC;AACC,MAAI,CAAC,QAAQ,OAAO,SAAS,SAAU,QAAO;AAC9C,QAAM,MAAM;AACZ,SAAO,MAAM,QAAQ,IAAI,KAAK,KAAK,OAAO,IAAI,YAAY;AAC7D;AAGO,SAAS,o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A;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEU;EAEV,YAAY,QAA4BA,UAAiB,aAA4B;AAClF,UAAM,QAAQA,UAAS,WAAW;AAClC,SAAK,WAAW,IAAI,SAAS,QAAQA,UAAS,WAAW;AACzD,qBAAiB,MAAM,KAAK,QAAQ;EACvC;;;;EAKS,gBAAgB,YAAgC;AACtD,UAAM,gBAAgB,UAAU;AAChC,QAAI,OAAO,KAAK,SAAS,oBAAoB,YAAY;AACtD,WAAK,SAAS,gBAAgB,UAAU;IAC3C;EACH;;;;;AAMH;;;AErMA,SAAS,eAAe;;;ACcjB,SAAS,mBAAmB,UAAiC;AACjE,MAAI,SAAU,QAAO;AACrB,SAAO,QAAQ,OAAO,QAAQ,UAAU;AAC3C;AAgBO,SAAS,WACb,MACA,MACA,SACA,gBACA,aACK;A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EACtD,EAAE,QAAQ,QAAQ,UAAU,CAAC,MAAM,EAAE,QAAQ,GAAG;AACnD;AAEA,eAAsB,yBAAyB,KAA0C;AACtF,QAAM,gBAAgB,MAAM,IAAI,UAAU,mBAAmB;AAC7D,aAAW,eAAe,KAAKA,SAAO;AACzC;;;ACjBA,IAAMC,YAAkC;AAAA,EACrC,EAAE,QAAQ,QAAQ,UAAU,CAAC,MAAM,EAAE,QAAQ,IAAI,UAAU,GAAG;AAAA,EAC9D,EAAE,QAAQ,SAAS,UAAU,CAAC,MAAM,EAAE,SAAS,IAAI,UAAU,GAAG;AAAA,EAChE,EAAE,QAAQ,QAAQ,UAAU,CAAC,MAAM,EAAE,KAAK;AAAA,EAC1C,EAAE,QAAQ,OAAO,UAAU,MAAM,GAAG;AAAA,EACpC,EAAE,QAAQ,aAAa,UAAU,CAAC,MAAO,EAAE,cAAc,QAAQ,KAAM;AAC1E;AAEA,eAAsB,cAAc,KAA0C;AAC3E,QAAM,UAAU,MAAM,IAAI,UAAU,eAAe;AACnD,QAAM,UAAUA,UAAQ;AAAA,IAAI,CAAC,QAC1B,IAAI,WAAW,QAAQ,EAAE,GAAG,KAAK,UAAU,MAAM,IAAI,IAAI,IAAI;AAAA,EAChE;AACA,eAAa,SAAS,KAAK,OAAO;AACrC;","names":["baseUrl","readFileSync","readFileSync","COLUMNS","MESSAGE_COLUMNS","truncate","COLUMNS","LABEL_COLUMNS","FILTER_COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","MESSAGE_COLUMNS","COLUMNS","MESSAGE_COLUMNS","COLUMNS","COLUMNS","EVENT_COLUMNS","result","page","pageSize","COLUMNS","LABEL_COLUMNS","NOTE_COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","baseUrl","MESSAGE_COLUMNS","COLUMNS","TOOL_COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","path","commands","COLUMNS","COLUMNS","COLUMNS","COLUMNS","RUN_COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","COLUMNS","execFile","execFile","readline","path","fs","path","CLIError","readline","readline","execSync","EventEmitter","readline","existsSync","mkdirSync","writeFileSync","readFileSync","execSync","join","join","existsSync","mkdirSync","writeFileSync","execSync","readFileSync","GravityRailClient","GravityRailClient","COLUMNS","COLUMNS"]}