@getmagical/cli 0.1.5 → 0.1.6

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli-formatting.ts","../src/errors.ts","../../mcp-registry/src/operation-specs.ts","../../mcp-registry/src/operation-spec.ts","../src/program.ts","../src/api.ts","../src/command-presentation.ts","../src/config.ts","../src/keychain.ts","../src/open-url.ts","../src/self-update.ts","../src/state.ts","../src/workos-auth.ts","../src/index.ts"],"sourcesContent":["import { inspect, stripVTControlCharacters, styleText } from 'node:util';\nimport { Help } from 'commander';\nimport type { CliAccount, CliOrganization } from './state';\n\nconst EMPTY_VALUE = '-';\nconst TABLE_GAP = ' ';\ntype TerminalStyle = Parameters<typeof styleText>[0];\n\nfunction applyStyle(\n value: string,\n style: TerminalStyle,\n enabled = true,\n): string {\n if (!enabled) {\n return value;\n }\n\n return styleText(style, value);\n}\n\nfunction indent(text: string, level = 2): string {\n const padding = ' '.repeat(level);\n return text\n .split('\\n')\n .map((line) => `${padding}${line}`)\n .join('\\n');\n}\n\nfunction stripAnsi(value: string): string {\n return stripVTControlCharacters(value);\n}\n\nfunction displayWidth(value: string): number {\n return stripAnsi(value).length;\n}\n\nfunction padCell(value: string, width: number): string {\n return value.padEnd(width + value.length - displayWidth(value));\n}\n\nfunction formatHeading(title: string): string {\n return applyStyle(title, ['bold', 'cyan']);\n}\n\nfunction formatLabel(label: string): string {\n return applyStyle(label, 'dim');\n}\n\nfunction formatCommandSnippet(command: string): string {\n return applyStyle(command, ['bold', 'cyan']);\n}\n\nfunction formatFlag(flag: string): string {\n return applyStyle(flag, ['bold', 'yellow']);\n}\n\nfunction formatErrorLabel(label: string): string {\n return applyStyle(label, ['bold', 'red'], process.stderr.isTTY);\n}\n\nfunction splitWords(value: string): string[] {\n const tokens: string[] = [];\n\n for (const word of value\n .replaceAll('_', ' ')\n .replaceAll('-', ' ')\n .split(' ')) {\n if (word.length === 0) {\n continue;\n }\n\n let currentToken = word[0] ?? '';\n for (const character of word.slice(1)) {\n const previousCharacter = currentToken.at(-1) ?? '';\n const shouldBreak =\n character >= 'A' &&\n character <= 'Z' &&\n ((previousCharacter >= 'a' && previousCharacter <= 'z') ||\n (previousCharacter >= '0' && previousCharacter <= '9'));\n\n if (shouldBreak) {\n tokens.push(currentToken);\n currentToken = character;\n continue;\n }\n\n currentToken += character;\n }\n\n tokens.push(currentToken);\n }\n\n return tokens;\n}\n\nfunction startCase(value: string): string {\n return splitWords(value)\n .map((segment) => {\n const lowerSegment = segment.toLowerCase();\n if (lowerSegment === 'id') {\n return 'ID';\n }\n\n if (lowerSegment === 'url') {\n return 'URL';\n }\n\n if (lowerSegment === 'api') {\n return 'API';\n }\n\n return segment.charAt(0).toUpperCase() + segment.slice(1);\n })\n .join(' ');\n}\n\nfunction formatScalar(value: unknown): string {\n if (value === null || value === undefined) {\n return EMPTY_VALUE;\n }\n\n if (typeof value === 'string') {\n return value.length === 0 ? EMPTY_VALUE : value;\n }\n\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n\n return inspect(value, {\n breakLength: Infinity,\n colors: false,\n compact: true,\n depth: 2,\n });\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isPrimitiveLike(value: unknown): boolean {\n return (\n value === null ||\n value === undefined ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n );\n}\n\nfunction formatTable(options: {\n columns: readonly string[];\n rows: readonly (readonly string[])[];\n}): string {\n const widths = options.columns.map((column, columnIndex) =>\n Math.max(\n displayWidth(column),\n ...options.rows.map((row) => displayWidth(row[columnIndex] ?? '')),\n ),\n );\n\n const renderRow = (cells: readonly string[]): string =>\n cells\n .map((cell, columnIndex) => padCell(cell, widths[columnIndex] ?? 0))\n .join(TABLE_GAP)\n .trimEnd();\n\n const divider = widths.map((width) => '-'.repeat(width)).join(TABLE_GAP);\n\n return [\n renderRow(options.columns.map((column) => applyStyle(column, 'bold'))),\n divider,\n ...options.rows.map(renderRow),\n ].join('\\n');\n}\n\nfunction canRenderRecordArrayAsTable(\n items: readonly unknown[],\n): items is readonly Record<string, unknown>[] {\n if (items.length === 0 || !items.every(isRecord)) {\n return false;\n }\n\n const keys = [...new Set(items.flatMap((item) => Object.keys(item)))];\n\n if (keys.length === 0 || keys.length > 8) {\n return false;\n }\n\n return items.every((item) => keys.every((key) => isPrimitiveLike(item[key])));\n}\n\nfunction formatRecord(record: Record<string, unknown>): string {\n const entries = Object.entries(record);\n if (entries.length === 0) {\n return EMPTY_VALUE;\n }\n\n const labelWidth = Math.max(\n ...entries.map(([key]) => displayWidth(startCase(key))),\n );\n\n return entries\n .map(([key, value]) => {\n const label = `${startCase(key)}:`;\n if (isPrimitiveLike(value)) {\n return `${padCell(formatLabel(label), labelWidth + 1)} ${formatScalar(value)}`;\n }\n\n return `${formatLabel(label)}\\n${indent(formatHumanReadableOutput(value))}`;\n })\n .join('\\n');\n}\n\nfunction formatArray(items: readonly unknown[]): string {\n if (items.length === 0) {\n return 'No results.';\n }\n\n if (items.every(isPrimitiveLike)) {\n return items.map((item) => `- ${formatScalar(item)}`).join('\\n');\n }\n\n if (canRenderRecordArrayAsTable(items)) {\n const keys = [...new Set(items.flatMap((item) => Object.keys(item)))];\n\n return formatTable({\n columns: keys.map((key) => startCase(key)),\n rows: items.map((item) => keys.map((key) => formatScalar(item[key]))),\n });\n }\n\n return items\n .map((item, index) => {\n const title = formatHeading(`Item ${index + 1}`);\n return `${title}\\n${indent(formatHumanReadableOutput(item))}`;\n })\n .join('\\n\\n');\n}\n\nfunction renderKeyValueBlock(entries: readonly [string, string][]): string {\n const labelWidth = Math.max(...entries.map(([label]) => displayWidth(label)));\n return entries\n .map(\n ([label, value]) =>\n `${padCell(formatLabel(`${label}:`), labelWidth + 1)} ${value}`,\n )\n .join('\\n');\n}\n\nfunction renderSection(title: string, bodyLines: readonly string[]): string {\n return [formatHeading(title), '', ...bodyLines].join('\\n');\n}\n\nexport class MagicalHelp extends Help {\n private outputHasColors = process.stdout.isTTY;\n\n public constructor() {\n super();\n this.helpWidth = 96;\n this.showGlobalOptions = true;\n this.sortSubcommands = true;\n }\n\n public override prepareContext(contextOptions: {\n error?: boolean;\n helpWidth?: number;\n outputHasColors?: boolean;\n }): void {\n super.prepareContext(contextOptions);\n this.outputHasColors =\n contextOptions.outputHasColors ?? process.stdout.isTTY;\n }\n\n public override styleTitle(str: string): string {\n return applyStyle(str, ['bold', 'cyan'], this.outputHasColors);\n }\n\n public override styleCommandText(str: string): string {\n return applyStyle(str, ['bold', 'cyan'], this.outputHasColors);\n }\n\n public override styleSubcommandText(str: string): string {\n return applyStyle(str, ['bold', 'cyan'], this.outputHasColors);\n }\n\n public override styleOptionText(str: string): string {\n return applyStyle(str, ['bold', 'yellow'], this.outputHasColors);\n }\n\n public override styleArgumentText(str: string): string {\n return applyStyle(str, ['bold', 'green'], this.outputHasColors);\n }\n\n public override styleDescriptionText(str: string): string {\n return applyStyle(str, 'dim', this.outputHasColors);\n }\n}\n\nexport function formatAuthLoginPrompt(options: {\n userCode: string;\n verificationUrl: string;\n}): string {\n return renderSection('Sign In With Your Browser', [\n renderKeyValueBlock([\n ['Open', options.verificationUrl],\n ['Code', options.userCode],\n ]),\n ]);\n}\n\nexport function formatAuthLoginSuccess(options: {\n account: CliAccount;\n defaultOrganization: CliOrganization | null;\n organizationCount: number;\n}): string {\n return renderSection('Signed In', [\n renderKeyValueBlock([\n ['Account', options.account.email ?? options.account.userId],\n ['Organizations', String(options.organizationCount)],\n [\n 'Default org',\n options.defaultOrganization\n ? `${options.defaultOrganization.name} (${options.defaultOrganization.id})`\n : 'None selected',\n ],\n ]),\n ]);\n}\n\nexport function formatBrowserOpenFallback(): string {\n return 'Browser auto-open failed. Paste the URL above into any browser.';\n}\n\nexport function formatLogoutSuccess(): string {\n return renderSection('Signed Out', ['Saved CLI auth state was cleared.']);\n}\n\nexport function formatOrganizationList(options: {\n defaultOrgId: string | null;\n lastUsedOrgId: string | null;\n organizations: readonly CliOrganization[];\n}): string {\n if (options.organizations.length === 0) {\n return renderSection('Organizations', ['No organizations are available.']);\n }\n\n const rows = options.organizations.map((organization) => {\n const status = [\n options.defaultOrgId === organization.id ? 'default' : null,\n options.lastUsedOrgId === organization.id ? 'last used' : null,\n ]\n .filter((value) => value !== null)\n .join(', ');\n\n return [\n status || EMPTY_VALUE,\n organization.name,\n organization.id,\n organization.primaryDomain ?? EMPTY_VALUE,\n ];\n });\n\n return renderSection('Organizations', [\n formatTable({\n columns: ['Status', 'Name', 'ID', 'Primary domain'],\n rows,\n }),\n ]);\n}\n\nexport function formatDefaultOrganizationSelection(\n organization: CliOrganization,\n): string {\n return renderSection('Default Organization Updated', [\n `${organization.name} (${organization.id})`,\n ]);\n}\n\nexport function formatHumanReadableOutput(value: unknown): string {\n if (isPrimitiveLike(value)) {\n return formatScalar(value);\n }\n\n if (Array.isArray(value)) {\n return formatArray(value);\n }\n\n if (isRecord(value)) {\n return formatRecord(value);\n }\n\n return inspect(value, {\n colors: false,\n depth: null,\n });\n}\n\nexport function formatCliError(message: string): string {\n return `${formatErrorLabel('Error:')} ${message}`;\n}\n\nexport function formatExamples(\n title: string,\n examples: readonly string[],\n): string {\n return [\n formatHeading(title),\n '',\n ...examples.map((example) => ` ${formatCommandSnippet(example)}`),\n ].join('\\n');\n}\n\nexport function formatOutputModesNote(): string {\n return renderSection('Output', [\n `Human-readable by default.`,\n `Add ${formatFlag('--json')} before or after a command for stable machine-readable output.`,\n ]);\n}\n","export class CliError extends Error {\n public constructor(\n message: string,\n options?: {\n cause?: unknown;\n },\n ) {\n super(message, options);\n this.name = 'CliError';\n }\n}\n\nexport function getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n return 'Unknown CLI error';\n}\n","import { z } from 'zod';\nimport { createOperationSpec } from './operation-spec';\nimport type { CliOptionSpec, OperationSpec } from './operation-types';\n\nfunction stringOption({\n description,\n flagName,\n inputKey,\n required = false,\n}: {\n description: string;\n flagName: string;\n inputKey: string;\n required?: boolean;\n}): CliOptionSpec {\n return {\n description,\n flagName,\n inputKey,\n required,\n valueType: 'string',\n };\n}\n\nfunction numberOption({\n description,\n flagName,\n inputKey,\n required = false,\n}: {\n description: string;\n flagName: string;\n inputKey: string;\n required?: boolean;\n}): CliOptionSpec {\n return {\n description,\n flagName,\n inputKey,\n required,\n valueType: 'number',\n };\n}\n\nfunction booleanOption({\n description,\n flagName,\n inputKey,\n}: {\n description: string;\n flagName: string;\n inputKey: string;\n}): CliOptionSpec {\n return {\n description,\n flagName,\n inputKey,\n valueType: 'boolean',\n };\n}\n\nfunction stringArrayOption({\n description,\n flagName,\n inputKey,\n}: {\n description: string;\n flagName: string;\n inputKey: string;\n}): CliOptionSpec {\n return {\n description,\n flagName,\n inputKey,\n valueHint: 'comma-separated',\n valueType: 'string-array',\n };\n}\n\nfunction jsonOption({\n description,\n flagName,\n inputKey,\n required = false,\n}: {\n description: string;\n flagName: string;\n inputKey: string;\n required?: boolean;\n}): CliOptionSpec {\n return {\n description,\n flagName,\n inputKey,\n required,\n valueHint: 'JSON',\n valueType: 'json',\n };\n}\n\nconst jsonObjectSchema = z.record(z.string(), z.unknown());\n\nexport const operationSpecs = [\n createOperationSpec({\n operationName: 'GetAgent',\n kind: 'query',\n inputSchema: z.object({\n id: z.string().min(1),\n }),\n cli: {\n name: 'get-agent',\n path: ['agents', 'get'],\n description: 'Fetch a single agent with config and schema fields.',\n resultKey: 'agent',\n options: [\n stringOption({\n inputKey: 'id',\n flagName: 'id',\n description: 'Agent ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'agent.graphql' },\n document: `# Query to fetch a single agent with all fields\n# Config selection is limited to scalar/JSON fields to keep responses flat\nquery GetAgent($id: ID!) {\n agent(id: $id) {\n id\n name\n description\n instructions\n organizationId\n createdAt\n updatedAt\n sourceAgentId\n inputSchema\n outputSchema\n config {\n type\n language\n model\n tools\n maxSessionMessages\n commonParametersSchema\n taskQueue\n waitUponQueueing\n queueableAgentIds\n additionalSystemPrompt\n ignoreUnstableSessionState\n }\n childAgentIds\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAgentRun',\n kind: 'query',\n inputSchema: z.object({\n id: z.string().min(1),\n }),\n cli: {\n name: 'get-agent-run',\n path: ['agent-runs', 'get'],\n description: 'Fetch a single agent run.',\n resultKey: 'agentRun',\n options: [\n stringOption({\n inputKey: 'id',\n flagName: 'id',\n description: 'Agent run ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'agentRun.graphql' },\n document: `# Query a single agent run\nquery GetAgentRun($id: ID!) {\n agentRun(id: $id) {\n id\n agentVersionId\n agentName\n status\n statusDetail\n isChildAgent\n input\n startedAt\n finishedAt\n parentAgentRunId\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomationAgents',\n kind: 'query',\n inputSchema: z.object({\n id: z.string().min(1),\n }),\n cli: {\n name: 'get-automation-agents',\n path: ['automations', 'agents'],\n description: 'Fetch the agents attached to an automation.',\n resultKey: 'automation',\n options: [\n stringOption({\n inputKey: 'id',\n flagName: 'id',\n description: 'Automation ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'automationAgents.graphql' },\n document: `# Query to fetch automation agents with flat fields only\n# Excludes nested agent config and schemas for MCP tool simplicity\nquery GetAutomationAgents($id: ID!) {\n automation(id: $id) {\n id\n name\n agents {\n automationId\n agentId\n isTrigger\n agent {\n id\n name\n description\n instructions\n organizationId\n createdAt\n updatedAt\n sourceAgentId\n childAgentIds\n }\n }\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomationRun',\n kind: 'query',\n inputSchema: z.object({\n id: z.string().min(1),\n }),\n cli: {\n name: 'get-automation-run',\n path: ['automation-runs', 'get'],\n description: 'Fetch a single automation run.',\n resultKey: 'automationRun',\n options: [\n stringOption({\n inputKey: 'id',\n flagName: 'id',\n description: 'Automation run ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'automationRun.graphql' },\n document: `# Query a full automation run details payload\nquery GetAutomationRun($id: ID!) {\n automationRun(id: $id) {\n id\n automationId\n status\n statusDetail\n summary\n invocationType\n input\n additionalPrompt\n debugUrl\n createdAt\n startedAt\n pausedAt\n finishedAt\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomationRunAgentRuns',\n kind: 'query',\n inputSchema: z.object({\n automationRunId: z.string().min(1),\n }),\n cli: {\n name: 'get-automation-run-agent-runs',\n path: ['automation-runs', 'agent-runs'],\n description: 'Fetch ordered agent runs for an automation run.',\n resultKey: 'automationRunAgentRuns',\n options: [\n stringOption({\n inputKey: 'automationRunId',\n flagName: 'automation-run-id',\n description: 'Automation run ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'automationRunAgentRuns.graphql' },\n document: `# Query ordered agent runs for an automation run\nquery GetAutomationRunAgentRuns($automationRunId: ID!) {\n automationRunAgentRuns(automationRunId: $automationRunId) {\n id\n agentVersionId\n agentName\n status\n statusDetail\n isChildAgent\n input\n startedAt\n finishedAt\n parentAgentRunId\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomationRunIterations',\n kind: 'query',\n inputSchema: z.object({\n automationRunId: z.string().min(1),\n agentRunId: z.string().min(1).optional(),\n limit: z.number().int().positive().optional(),\n reverse: z.boolean().optional(),\n }),\n cli: {\n name: 'get-automation-run-iterations',\n path: ['automation-runs', 'iterations'],\n description: 'Fetch ordered iterations for an automation run.',\n resultKey: 'automationRunIterations',\n options: [\n stringOption({\n inputKey: 'automationRunId',\n flagName: 'automation-run-id',\n description: 'Automation run ID.',\n required: true,\n }),\n stringOption({\n inputKey: 'agentRunId',\n flagName: 'agent-run-id',\n description: 'Optional agent run ID to filter by.',\n }),\n numberOption({\n inputKey: 'limit',\n flagName: 'limit',\n description: 'Maximum number of iterations to return.',\n }),\n booleanOption({\n inputKey: 'reverse',\n flagName: 'reverse',\n description: 'Return newest iterations first.',\n }),\n ],\n },\n mcp: { fileName: 'automationRunIterations.graphql' },\n document: `# Query iterations for an automation run with optional filtering by agent run\nquery GetAutomationRunIterations(\n $automationRunId: ID!\n $agentRunId: ID\n $limit: Int\n $reverse: Boolean\n) {\n automationRunIterations(\n automationRunId: $automationRunId\n agentRunId: $agentRunId\n limit: $limit\n reverse: $reverse\n ) {\n id\n sequence\n agentRunId\n metadata\n startedAt\n finishedAt\n totalDurationMs\n llmResponseDurationMs\n withMarksScreenshotUrl\n withMarksMimeType\n memories {\n id\n type\n value\n sequence\n screenshotUrl\n screenshotMimeType\n }\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomationRuns',\n kind: 'query',\n inputSchema: z.object({\n automationId: z.string().min(1),\n status: z.array(z.string().min(1)).optional(),\n invocationType: z.array(z.string().min(1)).optional(),\n limit: z.number().int().positive().optional(),\n page: z.number().int().positive().optional(),\n }),\n cli: {\n name: 'get-automation-runs',\n path: ['automation-runs', 'list'],\n description: 'Fetch automation run history.',\n resultKey: 'automationRuns',\n options: [\n stringOption({\n inputKey: 'automationId',\n flagName: 'automation-id',\n description: 'Automation ID.',\n required: true,\n }),\n stringArrayOption({\n inputKey: 'status',\n flagName: 'status',\n description: 'Optional run statuses.',\n }),\n stringArrayOption({\n inputKey: 'invocationType',\n flagName: 'invocation-type',\n description: 'Optional invocation types.',\n }),\n numberOption({\n inputKey: 'limit',\n flagName: 'limit',\n description: 'Maximum number of runs to return.',\n }),\n numberOption({\n inputKey: 'page',\n flagName: 'page',\n description: 'Page number.',\n }),\n ],\n },\n mcp: { fileName: 'automationRuns.graphql' },\n document: `# Query automation run history for a specific automation with optional filters\nquery GetAutomationRuns(\n $automationId: ID!\n $status: [RunStatus!]\n $invocationType: [InvocationType!]\n $limit: Int\n $page: Int\n) {\n automationRuns(\n automationId: $automationId\n status: $status\n invocationType: $invocationType\n limit: $limit\n page: $page\n ) {\n id\n automationId\n status\n statusDetail\n invocationType\n summary\n createdAt\n startedAt\n pausedAt\n finishedAt\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomations',\n kind: 'query',\n inputSchema: z.object({\n limit: z.number().positive().optional(),\n order: jsonObjectSchema.optional(),\n where: jsonObjectSchema.optional(),\n }),\n cli: {\n name: 'get-automations',\n path: ['automations', 'list'],\n description: 'Fetch automations with optional list filters.',\n resultKey: 'automations',\n options: [\n numberOption({\n inputKey: 'limit',\n flagName: 'limit',\n description: 'Maximum number of automations to return.',\n }),\n jsonOption({\n inputKey: 'order',\n flagName: 'order-json',\n description: 'GraphQL order object.',\n }),\n jsonOption({\n inputKey: 'where',\n flagName: 'where-json',\n description: 'GraphQL filter object.',\n }),\n ],\n },\n mcp: { fileName: 'automations.graphql' },\n document: `# Query to fetch automations with flat fields only (no nested objects)\n# Excludes config and agents for MCP tool simplicity\nquery GetAutomations(\n $limit: Float\n $order: AutomationsOrder\n $where: AutomationsWhereInput\n) {\n automations(limit: $limit, order: $order, where: $where) {\n id\n name\n organizationId\n createdAt\n updatedAt\n environment\n lastSavedAt\n publishedVersionId\n draftVersionId\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomationWithConfigs',\n kind: 'query',\n inputSchema: z.object({\n id: z.string().min(1),\n }),\n cli: {\n name: 'get-automation-with-configs',\n path: ['automations', 'get'],\n description: 'Fetch a single automation with config fields.',\n resultKey: 'automation',\n options: [\n stringOption({\n inputKey: 'id',\n flagName: 'id',\n description: 'Automation ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'automationWithConfigs.graphql' },\n document: `# Query to fetch a single automation with config but excluding agents\n# Config selection is limited to scalar/JSON fields to keep responses flat\nquery GetAutomationWithConfigs($id: ID!) {\n automation(id: $id) {\n id\n name\n organizationId\n createdAt\n updatedAt\n environment\n lastSavedAt\n publishedVersionId\n draftVersionId\n config {\n cronExpression\n calendars\n interval\n enableVisualChangeChecks\n isCDPforSOM\n humanInterventionTimeoutSeconds\n availableSlots\n additionalSystemPrompt\n ignoreUnstableSessionState\n }\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAvailableCommands',\n kind: 'query',\n inputSchema: z.object({\n env: z.string().min(1),\n }),\n cli: {\n name: 'get-available-commands',\n path: ['catalog', 'commands'],\n description: 'Fetch available command definitions by environment.',\n resultKey: 'availableCommands',\n options: [\n stringOption({\n inputKey: 'env',\n flagName: 'env',\n description: 'Environment name.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'availableCommands.graphql' },\n document: `# Query to fetch available command definitions by environment\nquery GetAvailableCommands($env: AvailableCommandsEnv!) {\n availableCommands(env: $env) {\n id\n description\n inputSchema\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAvailableModels',\n kind: 'query',\n inputSchema: z.object({\n agentId: z.string().min(1),\n }),\n cli: {\n name: 'get-available-models',\n path: ['catalog', 'models'],\n description: 'Fetch available model definitions for an agent.',\n resultKey: 'availableModels',\n options: [\n stringOption({\n inputKey: 'agentId',\n flagName: 'agent-id',\n description: 'Agent ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'availableModels.graphql' },\n document: `# Query to fetch available model definitions and pools for a specific agent\nquery GetAvailableModels($agentId: String!) {\n availableModels(agentId: $agentId) {\n availableModelPools {\n name\n poolId\n models {\n id\n name\n description\n status\n provider\n }\n }\n allAvailableModels {\n id\n name\n description\n status\n provider\n }\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAvailableTools',\n kind: 'query',\n inputSchema: z.object({\n env: z.string().min(1),\n automationId: z.string().min(1).optional(),\n }),\n cli: {\n name: 'get-available-tools',\n path: ['catalog', 'tools'],\n description: 'Fetch available tool definitions by environment.',\n resultKey: 'availableTools',\n options: [\n stringOption({\n inputKey: 'env',\n flagName: 'env',\n description: 'Environment name.',\n required: true,\n }),\n stringOption({\n inputKey: 'automationId',\n flagName: 'automation-id',\n description: 'Optional automation ID.',\n }),\n ],\n },\n mcp: { fileName: 'availableTools.graphql' },\n document: `# Query to fetch available tool definitions by environment\nquery GetAvailableTools($env: AvailableCommandsEnv!, $automationId: String) {\n availableTools(env: $env, automationId: $automationId) {\n id\n description\n inputSchema\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'CreateAutomation',\n kind: 'mutation',\n inputSchema: z.object({\n input: jsonObjectSchema,\n }),\n cli: {\n name: 'create-automation',\n path: ['automations', 'create'],\n description: 'Create a draft automation.',\n resultKey: 'createAutomation',\n options: [\n jsonOption({\n inputKey: 'input',\n flagName: 'input-json',\n description: 'CreateAutomationInput payload.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'createAutomation.graphql' },\n document: `# Mutation to create a draft automation with optional initial values\n# Returns flat fields only for MCP tool simplicity\nmutation CreateAutomation($input: CreateAutomationInput!) {\n createAutomation(input: $input) {\n id\n name\n organizationId\n createdAt\n updatedAt\n environment\n lastSavedAt\n publishedVersionId\n draftVersionId\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetGraphqlSchema',\n kind: 'query',\n inputSchema: z.object({}),\n cli: {\n name: 'get-graphql-schema',\n path: ['graphql', 'schema'],\n description: 'Fetch GraphQL schema metadata.',\n resultKey: 'graphqlSchema',\n options: [],\n },\n mcp: { fileName: 'graphqlSchema.graphql' },\n document: `# Query to fetch full GraphQL schema metadata.\n# Uses the first-class graphqlSchema query field to avoid __schema validation\n# issues in MCP tool-load paths while still returning introspection JSON.\n# Response can be large: call sparingly (typically once per task/session) and\n# reuse cached results.\nquery GetGraphqlSchema {\n graphqlSchema\n}`,\n }),\n createOperationSpec({\n operationName: 'PauseAutomationRun',\n kind: 'mutation',\n inputSchema: z.object({\n automationRunId: z.string().min(1),\n }),\n cli: {\n name: 'pause-automation-run',\n path: ['automation-runs', 'pause'],\n description: 'Pause an automation run.',\n resultKey: 'pauseAutomationRun',\n options: [\n stringOption({\n inputKey: 'automationRunId',\n flagName: 'automation-run-id',\n description: 'Automation run ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'pauseAutomationRun.graphql' },\n document: `# Mutation to pause an automation run\nmutation PauseAutomationRun($automationRunId: ID!) {\n pauseAutomationRun(automationRunId: $automationRunId)\n}`,\n }),\n createOperationSpec({\n operationName: 'RerunAutomation',\n kind: 'mutation',\n inputSchema: z.object({\n automationRunId: z.string().min(1),\n additionalPrompt: z.string().min(1).optional(),\n idempotencyKey: z.string().min(1),\n }),\n cli: {\n name: 'rerun-automation',\n path: ['automation-runs', 'rerun'],\n description: 'Rerun an existing automation run.',\n resultKey: 'rerunAutomation',\n options: [\n stringOption({\n inputKey: 'automationRunId',\n flagName: 'automation-run-id',\n description: 'Automation run ID.',\n required: true,\n }),\n stringOption({\n inputKey: 'additionalPrompt',\n flagName: 'additional-prompt',\n description: 'Optional prompt appended to the rerun.',\n }),\n stringOption({\n inputKey: 'idempotencyKey',\n flagName: 'idempotency-key',\n description: 'Idempotency key for the rerun request.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'rerunAutomation.graphql' },\n document: `# Mutation to rerun an existing automation run\nmutation RerunAutomation(\n $automationRunId: ID!\n $additionalPrompt: String\n $idempotencyKey: String!\n) {\n rerunAutomation(\n automationRunId: $automationRunId\n additionalPrompt: $additionalPrompt\n idempotencyKey: $idempotencyKey\n ) {\n automationRunId\n workflowId\n workflowRunId\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'ResumeAutomationRun',\n kind: 'mutation',\n inputSchema: z.object({\n automationRunId: z.string().min(1),\n message: z.string().min(1).optional(),\n }),\n cli: {\n name: 'resume-automation-run',\n path: ['automation-runs', 'resume'],\n description: 'Resume a paused automation run.',\n resultKey: 'resumeAutomationRun',\n options: [\n stringOption({\n inputKey: 'automationRunId',\n flagName: 'automation-run-id',\n description: 'Automation run ID.',\n required: true,\n }),\n stringOption({\n inputKey: 'message',\n flagName: 'message',\n description: 'Optional resume message.',\n }),\n ],\n },\n mcp: { fileName: 'resumeAutomationRun.graphql' },\n document: `# Mutation to resume an automation run\nmutation ResumeAutomationRun($automationRunId: ID!, $message: String) {\n resumeAutomationRun(automationRunId: $automationRunId, message: $message)\n}`,\n }),\n createOperationSpec({\n operationName: 'RunDraftAutomation',\n kind: 'mutation',\n inputSchema: z.object({\n draftAutomationId: z.string().min(1),\n agentId: z.string().min(1),\n idempotencyKey: z.string().min(1),\n input: z.unknown().optional(),\n additionalPrompt: z.string().min(1).optional(),\n }),\n cli: {\n name: 'run-draft-automation',\n path: ['automations', 'run-draft'],\n description: 'Run a draft automation with an explicit trigger agent.',\n resultKey: 'runDraftAutomation',\n options: [\n stringOption({\n inputKey: 'draftAutomationId',\n flagName: 'draft-automation-id',\n description: 'Draft automation ID.',\n required: true,\n }),\n stringOption({\n inputKey: 'agentId',\n flagName: 'agent-id',\n description: 'Trigger agent ID.',\n required: true,\n }),\n stringOption({\n inputKey: 'idempotencyKey',\n flagName: 'idempotency-key',\n description: 'Idempotency key for the run request.',\n required: true,\n }),\n jsonOption({\n inputKey: 'input',\n flagName: 'input-json',\n description: 'Optional JSON input payload.',\n }),\n stringOption({\n inputKey: 'additionalPrompt',\n flagName: 'additional-prompt',\n description: 'Optional prompt appended to the run.',\n }),\n ],\n },\n mcp: { fileName: 'runDraftAutomation.graphql' },\n document: `# Mutation to run a draft automation with an explicit agent.\n# \\`draftAutomationId\\` is the draft automation entity ID (\\`Automation.id\\`), not \\`draftVersionId\\`.\nmutation RunDraftAutomation(\n $draftAutomationId: ID!\n $agentId: ID!\n $idempotencyKey: String!\n $input: JSON\n $additionalPrompt: String\n) {\n runDraftAutomation(\n draftAutomationId: $draftAutomationId\n agentId: $agentId\n idempotencyKey: $idempotencyKey\n input: $input\n additionalPrompt: $additionalPrompt\n ) {\n automationRunId\n workflowId\n workflowRunId\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'StopAutomationRun',\n kind: 'mutation',\n inputSchema: z.object({\n automationRunId: z.string().min(1),\n }),\n cli: {\n name: 'stop-automation-run',\n path: ['automation-runs', 'stop'],\n description: 'Stop an automation run.',\n resultKey: 'stopAutomationRun',\n options: [\n stringOption({\n inputKey: 'automationRunId',\n flagName: 'automation-run-id',\n description: 'Automation run ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'stopAutomationRun.graphql' },\n document: `# Mutation to stop an automation run\nmutation StopAutomationRun($automationRunId: ID!) {\n stopAutomationRun(automationRunId: $automationRunId)\n}`,\n }),\n createOperationSpec({\n operationName: 'UpdateAutomationById',\n kind: 'mutation',\n inputSchema: z.object({\n id: z.string().min(1),\n input: jsonObjectSchema,\n }),\n cli: {\n name: 'update-automation-by-id',\n path: ['automations', 'update'],\n description: 'Update an automation.',\n resultKey: 'updateAutomation',\n options: [\n stringOption({\n inputKey: 'id',\n flagName: 'id',\n description: 'Automation ID.',\n required: true,\n }),\n jsonOption({\n inputKey: 'input',\n flagName: 'input-json',\n description: 'UpdateAutomationInput payload.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'updateAutomation.graphql' },\n document: `# Mutation to update an automation\n# Returns only id and lastSavedAt for MCP tool simplicity\nmutation UpdateAutomationById($id: ID!, $input: UpdateAutomationInput!) {\n updateAutomation(id: $id, input: $input) {\n id\n lastSavedAt\n }\n}`,\n }),\n] as const satisfies readonly OperationSpec[];\n","import type { z } from 'zod';\nimport type { OperationSpec } from './operation-types';\n\nfunction stripLeadingGraphqlComments(document: string): string {\n return document.replace(/^(?:\\s*#.*\\n)+/u, '').trimStart();\n}\n\nfunction assertDocumentMatchesOperation({\n document,\n kind,\n operationName,\n}: {\n document: string;\n kind: OperationSpec['kind'];\n operationName: string;\n}): void {\n const normalizedDocument = stripLeadingGraphqlComments(document);\n const match =\n /^(?<actualKind>query|mutation)\\s+(?<actualOperationName>[_A-Za-z][_0-9A-Za-z]*)/u.exec(\n normalizedDocument,\n );\n\n const actualKind = match?.groups?.['actualKind'];\n const actualOperationName = match?.groups?.['actualOperationName'];\n if (!actualKind || !actualOperationName) {\n throw new Error(\n `Operation \"${operationName}\" is missing a top-level GraphQL ${kind} definition.`,\n );\n }\n\n if (actualKind !== kind || actualOperationName !== operationName) {\n throw new Error(\n `Operation \"${operationName}\" does not match its GraphQL document (${actualKind} ${actualOperationName}).`,\n );\n }\n}\n\nexport function createOperationSpec<TInputSchema extends z.ZodTypeAny>(\n spec: OperationSpec<TInputSchema>,\n): OperationSpec<TInputSchema> {\n assertDocumentMatchesOperation(spec);\n return spec;\n}\n","import { operationSpecs } from '@magical/mcp-registry';\nimport type { CliOptionSpec, OperationSpec } from '@magical/mcp-registry';\nimport { Command, InvalidArgumentError, Option } from 'commander';\nimport { createMagicalApiClient } from './api';\nimport type { ApiClient } from './api';\nimport {\n formatAuthLoginPrompt,\n formatAuthLoginSuccess,\n formatBrowserOpenFallback,\n formatDefaultOrganizationSelection,\n formatExamples,\n formatHumanReadableOutput,\n formatLogoutSuccess,\n formatOrganizationList,\n formatOutputModesNote,\n} from './cli-formatting';\nimport {\n configureCommandPresentation,\n createOperationHelpExamples,\n rootOperationalGroupDescriptions,\n} from './command-presentation';\nimport { getRuntimeConfig, requireWorkosClientId } from './config';\nimport type { RuntimeConfig } from './config';\nimport { CliError } from './errors';\nimport { createKeytarRefreshTokenStore } from './keychain';\nimport { openExternalUrl } from './open-url';\nimport { selfUpdateInstalledCli } from './self-update';\nimport { createFileStateStore } from './state';\nimport type {\n CliOrganization,\n CliState,\n RefreshTokenStore,\n StateStore,\n} from './state';\nimport { createWorkosAuthClient } from './workos-auth';\nimport type { AuthClient } from './workos-auth';\n\nexport interface CliIo {\n error: (message: string) => void;\n info: (message: string) => void;\n}\n\nexport interface CliDependencies {\n apiClient: ApiClient;\n authClient: AuthClient;\n io: CliIo;\n openExternalUrl: (url: string) => Promise<void>;\n refreshTokenStore: RefreshTokenStore;\n runtimeConfig: RuntimeConfig;\n selfUpdateCli?: () => Promise<{\n installPrefix: string;\n packageSpecifier: string;\n registryUrl: string;\n }>;\n stateStore: StateStore;\n}\n\ntype JsonCommandOptions = Record<string, unknown> & {\n json?: boolean;\n};\n\ninterface OperationalCommandOptions {\n json?: boolean;\n org?: string;\n}\n\nfunction buildCommandOptionProperty(flagName: string): string {\n const [firstSegment, ...remainingSegments] = flagName.split('-');\n return [\n firstSegment ?? '',\n ...remainingSegments.map(\n (segment) => `${segment[0]?.toUpperCase() ?? ''}${segment.slice(1)}`,\n ),\n ].join('');\n}\n\nfunction parseCommandOptionValue(\n rawValue: string,\n optionSpec: CliOptionSpec,\n): unknown {\n switch (optionSpec.valueType) {\n case 'number': {\n const parsedNumber = Number(rawValue);\n if (Number.isNaN(parsedNumber)) {\n throw new InvalidArgumentError(\n `Expected a number for --${optionSpec.flagName}.`,\n );\n }\n\n return parsedNumber;\n }\n\n case 'string-array': {\n return rawValue\n .split(',')\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n }\n\n case 'json': {\n try {\n return JSON.parse(rawValue) as unknown;\n } catch {\n throw new InvalidArgumentError(\n `Expected valid JSON for --${optionSpec.flagName}.`,\n );\n }\n }\n\n case 'boolean': {\n return rawValue;\n }\n\n case 'string': {\n return rawValue;\n }\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction resolveOrganizationBySelector({\n organizations,\n selector,\n}: {\n organizations: CliOrganization[];\n selector: string;\n}): CliOrganization {\n const matchedOrganization = organizations.find(\n (organization) =>\n organization.id === selector || organization.name === selector,\n );\n\n if (!matchedOrganization) {\n throw new CliError(`Unknown organization \"${selector}\".`);\n }\n\n return matchedOrganization;\n}\n\nfunction resolveSelectedOrganization({\n organizationSelector,\n state,\n}: {\n organizationSelector?: string;\n state: CliState;\n}): CliOrganization {\n if (organizationSelector) {\n return resolveOrganizationBySelector({\n organizations: state.organizations,\n selector: organizationSelector,\n });\n }\n\n if (!state.defaultOrgId) {\n throw new CliError(\n 'No default organization is configured. Use \"mgcl org use <org>\" or pass --org.',\n );\n }\n\n return resolveOrganizationBySelector({\n organizations: state.organizations,\n selector: state.defaultOrgId,\n });\n}\n\nfunction requireLoggedInState(state: CliState | null): CliState {\n if (!state) {\n throw new CliError('You are not logged in. Run \"mgcl auth login\" first.');\n }\n\n return state;\n}\n\nfunction writeJsonOutput(io: CliIo, value: unknown): void {\n io.info(JSON.stringify(value, null, 2));\n}\n\nfunction collectOperationVariables(\n operationSpec: OperationSpec,\n options: Record<string, unknown>,\n): Record<string, unknown> {\n const variables = Object.fromEntries(\n operationSpec.cli.options.flatMap((optionSpec: CliOptionSpec) => {\n const optionValue =\n options[buildCommandOptionProperty(optionSpec.flagName)];\n if (optionValue === undefined) {\n return [];\n }\n\n return [[optionSpec.inputKey, optionValue]];\n }),\n );\n\n const parsedVariables = operationSpec.inputSchema.safeParse(variables);\n if (!parsedVariables.success) {\n throw new CliError(\n parsedVariables.error.issues[0]?.message ?? 'Invalid command input.',\n );\n }\n\n if (!isRecord(parsedVariables.data)) {\n throw new CliError('Invalid command input.');\n }\n\n return parsedVariables.data;\n}\n\nasync function withOrgScopedAccessToken({\n dependencies,\n organizationId,\n state,\n}: {\n dependencies: CliDependencies;\n organizationId: string;\n state: CliState;\n}): Promise<{ accessToken: string }> {\n const refreshToken = await dependencies.refreshTokenStore.load(state.account);\n if (!refreshToken) {\n throw new CliError(\n 'No refresh token was found. Run \"mgcl auth login\" again.',\n );\n }\n\n const tokenResponse = await dependencies.authClient\n .refreshTokens({\n clientId: state.account.clientId,\n organizationId,\n refreshToken,\n })\n .catch((error: unknown) => {\n if (\n error instanceof CliError &&\n error.message === 'Refresh token already exchanged.'\n ) {\n throw new CliError(\n 'Refresh token already exchanged. Run \"mgcl auth login\" again.',\n { cause: error },\n );\n }\n\n throw error;\n });\n\n await dependencies.refreshTokenStore.save(\n state.account,\n tokenResponse.refresh_token,\n );\n\n return {\n accessToken: tokenResponse.access_token,\n };\n}\n\nasync function handleAuthLogin(\n dependencies: CliDependencies,\n options: JsonCommandOptions,\n): Promise<void> {\n const clientId = requireWorkosClientId(dependencies.runtimeConfig);\n const deviceAuthorization =\n await dependencies.authClient.startDeviceAuthorization({ clientId });\n const verificationUrl =\n deviceAuthorization.verification_uri_complete ??\n deviceAuthorization.verification_uri;\n const promptWriter = options.json\n ? dependencies.io.error\n : dependencies.io.info;\n\n promptWriter(\n formatAuthLoginPrompt({\n userCode: deviceAuthorization.user_code,\n verificationUrl,\n }),\n );\n\n await dependencies.openExternalUrl(verificationUrl).catch(() => {\n promptWriter(formatBrowserOpenFallback());\n });\n\n const tokenResponse = await dependencies.authClient.pollForDeviceTokens({\n clientId,\n deviceCode: deviceAuthorization.device_code,\n ...(deviceAuthorization.expires_in\n ? { expiresInSeconds: deviceAuthorization.expires_in }\n : {}),\n ...(deviceAuthorization.interval\n ? { intervalSeconds: deviceAuthorization.interval }\n : {}),\n });\n const accessTokenClaims = dependencies.authClient.decodeAccessTokenClaims(\n tokenResponse.access_token,\n );\n const [user, organizations] = await Promise.all([\n dependencies.apiClient.fetchUser({\n accessToken: tokenResponse.access_token,\n userId: accessTokenClaims.sub,\n }),\n dependencies.apiClient.fetchOrganizations({\n accessToken: tokenResponse.access_token,\n }),\n ]);\n\n const defaultOrgId = accessTokenClaims.org_id ?? organizations[0]?.id ?? null;\n const nextState: CliState = {\n account: {\n clientId,\n email: user.email,\n userId: user.id,\n },\n defaultOrgId,\n lastUsedOrgId: defaultOrgId,\n organizations,\n };\n\n await Promise.all([\n dependencies.refreshTokenStore.save(\n nextState.account,\n tokenResponse.refresh_token,\n ),\n dependencies.stateStore.save(nextState),\n ]);\n\n const defaultOrganization =\n organizations.find((organization) => organization.id === defaultOrgId) ??\n null;\n\n if (options.json) {\n writeJsonOutput(dependencies.io, nextState);\n return;\n }\n\n dependencies.io.info(\n formatAuthLoginSuccess({\n account: nextState.account,\n defaultOrganization,\n organizationCount: organizations.length,\n }),\n );\n}\n\nasync function handleAuthLogout(\n dependencies: CliDependencies,\n options: JsonCommandOptions,\n): Promise<void> {\n const state = await dependencies.stateStore.load();\n if (state) {\n await dependencies.refreshTokenStore.clear(state.account);\n }\n\n await dependencies.stateStore.clear();\n\n if (options.json) {\n writeJsonOutput(dependencies.io, { loggedOut: true });\n return;\n }\n\n dependencies.io.info(formatLogoutSuccess());\n}\n\nasync function handleOrgList(\n dependencies: CliDependencies,\n options: JsonCommandOptions,\n): Promise<void> {\n const state = requireLoggedInState(await dependencies.stateStore.load());\n if (options.json) {\n writeJsonOutput(dependencies.io, state.organizations);\n return;\n }\n\n dependencies.io.info(\n formatOrganizationList({\n defaultOrgId: state.defaultOrgId,\n lastUsedOrgId: state.lastUsedOrgId,\n organizations: state.organizations,\n }),\n );\n}\n\nasync function handleOrgUse(\n dependencies: CliDependencies,\n organizationSelector: string,\n options: JsonCommandOptions,\n): Promise<void> {\n const state = requireLoggedInState(await dependencies.stateStore.load());\n const organization = resolveOrganizationBySelector({\n organizations: state.organizations,\n selector: organizationSelector,\n });\n\n const nextState: CliState = {\n ...state,\n defaultOrgId: organization.id,\n lastUsedOrgId: organization.id,\n };\n await dependencies.stateStore.save(nextState);\n\n if (options.json) {\n writeJsonOutput(dependencies.io, {\n defaultOrgId: organization.id,\n organization,\n });\n return;\n }\n\n dependencies.io.info(formatDefaultOrganizationSelection(organization));\n}\n\nasync function handleSelfUpdate(\n dependencies: CliDependencies,\n options: JsonCommandOptions,\n): Promise<void> {\n const { selfUpdateCli } = dependencies;\n if (!selfUpdateCli) {\n throw new CliError('Self-update is not configured for this CLI instance.');\n }\n\n const updateResult = await selfUpdateCli();\n\n if (options.json) {\n writeJsonOutput(dependencies.io, {\n installPrefix: updateResult.installPrefix,\n packageSpecifier: updateResult.packageSpecifier,\n registryUrl: updateResult.registryUrl,\n updated: true,\n });\n return;\n }\n\n dependencies.io.info(\n `Updated mgcl via npm (${updateResult.packageSpecifier}) in ${updateResult.installPrefix}.`,\n );\n}\n\nasync function handleOperationCommand(\n dependencies: CliDependencies,\n operationSpec: OperationSpec,\n commandOptions: Record<string, unknown> & OperationalCommandOptions,\n): Promise<void> {\n const state = requireLoggedInState(await dependencies.stateStore.load());\n const organization = resolveSelectedOrganization({\n state,\n ...(commandOptions.org ? { organizationSelector: commandOptions.org } : {}),\n });\n const variables = collectOperationVariables(operationSpec, commandOptions);\n const { accessToken } = await withOrgScopedAccessToken({\n dependencies,\n organizationId: organization.id,\n state,\n });\n\n const result = await dependencies.apiClient.executeGraphQl({\n accessToken,\n query: operationSpec.document,\n resultKey: operationSpec.cli.resultKey,\n variables,\n });\n\n await dependencies.stateStore.save({\n ...state,\n lastUsedOrgId: organization.id,\n });\n\n if (commandOptions.json) {\n writeJsonOutput(dependencies.io, result);\n return;\n }\n\n dependencies.io.info(formatHumanReadableOutput(result));\n}\n\nfunction addRegistryOperationCommand({\n program,\n commandGroups,\n dependencies,\n operationSpec,\n}: {\n program: Command;\n commandGroups: Map<string, Command>;\n dependencies: CliDependencies;\n operationSpec: OperationSpec;\n}): void {\n const commandPath = [...operationSpec.cli.path];\n const leafCommandName = commandPath.pop();\n if (!leafCommandName) {\n throw new CliError(\n `CLI path is missing a leaf command for ${operationSpec.operationName}.`,\n );\n }\n\n let parentCommand = program;\n const currentGroupPath: string[] = [];\n\n for (const groupSegment of commandPath) {\n currentGroupPath.push(groupSegment);\n const groupPathKey = currentGroupPath.join(' ');\n const existingGroup = commandGroups.get(groupPathKey);\n if (existingGroup) {\n parentCommand = existingGroup;\n continue;\n }\n\n const nextGroup = parentCommand.command(groupSegment);\n if (currentGroupPath.length === 1) {\n nextGroup.helpGroup('Operation groups:');\n }\n const rootGroupDescription =\n currentGroupPath.length === 1\n ? rootOperationalGroupDescriptions.get(groupSegment)\n : undefined;\n if (rootGroupDescription) {\n nextGroup.description(rootGroupDescription);\n }\n\n commandGroups.set(groupPathKey, nextGroup);\n parentCommand = nextGroup;\n }\n\n const command = parentCommand.command(leafCommandName);\n configureOperationalCommand(command, dependencies, operationSpec);\n const legacyAliasCommand = program.command(operationSpec.cli.name, {\n hidden: true,\n });\n configureOperationalCommand(legacyAliasCommand, dependencies, operationSpec);\n}\nfunction configureOperationalCommand(\n command: Command,\n dependencies: CliDependencies,\n operationSpec: OperationSpec,\n): void {\n command\n .description(operationSpec.cli.description)\n .addOption(\n new Option(\n '--org <org>',\n 'Organization ID or exact organization name to use.',\n ).helpGroup('Shared options:'),\n )\n .addHelpText(\n 'after',\n `\\n${formatExamples(\n 'Examples',\n createOperationHelpExamples(operationSpec),\n )}`,\n );\n\n for (const optionSpec of operationSpec.cli.options) {\n const optionFlags =\n optionSpec.valueType === 'boolean'\n ? `--${optionSpec.flagName}`\n : `--${optionSpec.flagName} <value>`;\n const optionDescription = optionSpec.valueHint\n ? `${optionSpec.description} (${optionSpec.valueHint})`\n : optionSpec.description;\n const nextOption = new Option(optionFlags, optionDescription).helpGroup(\n operationSpec.kind === 'query' ? 'Query options:' : 'Mutation options:',\n );\n\n if (optionSpec.valueType === 'boolean') {\n command.addOption(nextOption);\n continue;\n }\n\n const parser = (rawValue: string): unknown =>\n parseCommandOptionValue(rawValue, optionSpec);\n nextOption.argParser(parser);\n\n if (optionSpec.required) {\n nextOption.makeOptionMandatory(true);\n command.addOption(nextOption);\n continue;\n }\n\n command.addOption(nextOption);\n }\n\n command.action(async function (this: Command) {\n await handleOperationCommand(\n dependencies,\n operationSpec,\n this.optsWithGlobals(),\n );\n });\n}\n\nexport function createConsoleIo(): CliIo {\n return {\n error(message) {\n process.stderr.write(`${message}\\n`);\n },\n info(message) {\n process.stdout.write(`${message}\\n`);\n },\n };\n}\n\nexport function createDefaultDependencies(): CliDependencies {\n const runtimeConfig = getRuntimeConfig();\n const selfUpdateOptions = {\n ...(runtimeConfig.cliDistTag ? { distTag: runtimeConfig.cliDistTag } : {}),\n ...(runtimeConfig.npmRegistryUrl\n ? { registryUrl: runtimeConfig.npmRegistryUrl }\n : {}),\n };\n\n return {\n apiClient: createMagicalApiClient({\n apiBaseUrl: runtimeConfig.magicalApiUrl,\n }),\n authClient: createWorkosAuthClient({\n workosApiUrl: runtimeConfig.workosApiUrl,\n }),\n io: createConsoleIo(),\n openExternalUrl,\n refreshTokenStore: createKeytarRefreshTokenStore(\n runtimeConfig.keychainServiceName,\n ),\n runtimeConfig,\n selfUpdateCli: async () => selfUpdateInstalledCli(selfUpdateOptions),\n stateStore: createFileStateStore(runtimeConfig.stateFilePath),\n };\n}\n\nexport function buildProgram(dependencies: CliDependencies): Command {\n const program = configureCommandPresentation(\n new Command()\n .name('mgcl')\n .description('Run Magical operations from the command line.'),\n )\n .addOption(new Option('--json', 'Render JSON output.'))\n .addOption(\n new Option(\n '--update',\n 'Update mgcl to the latest published npm release.',\n ),\n )\n .showHelpAfterError()\n .showSuggestionAfterError()\n .addHelpText(\n 'after',\n `\\n${formatExamples('Quick start', [\n 'mgcl auth login',\n 'mgcl org list',\n 'mgcl automations list --limit 10',\n 'mgcl automation-runs get --id <run-id>',\n 'mgcl update',\n ])}\\n\\n${formatOutputModesNote()}`,\n );\n program.action(async function (this: Command) {\n const options = this.optsWithGlobals<\n JsonCommandOptions & {\n update?: boolean;\n }\n >();\n\n if (options.update) {\n await handleSelfUpdate(dependencies, options);\n return;\n }\n\n this.outputHelp();\n });\n\n const authCommand = configureCommandPresentation(\n new Command('auth').description('Manage CLI authentication.'),\n )\n .helpGroup('Workspace:')\n .addHelpText(\n 'after',\n `\\n${formatExamples('Examples', [\n 'mgcl auth login',\n 'mgcl auth logout',\n ])}`,\n );\n authCommand\n .command('login')\n .description('Authenticate with Magical and load organization memberships.')\n .action(async function (this: Command) {\n await handleAuthLogin(dependencies, this.optsWithGlobals());\n });\n authCommand\n .command('logout')\n .description('Remove local CLI auth state.')\n .action(async function (this: Command) {\n await handleAuthLogout(dependencies, this.optsWithGlobals());\n });\n program.addCommand(authCommand);\n\n const orgCommand = configureCommandPresentation(\n new Command('org').description('Manage organization selection.'),\n )\n .helpGroup('Workspace:')\n .addHelpText(\n 'after',\n `\\n${formatExamples('Examples', [\n 'mgcl org list',\n 'mgcl org use <org>',\n ])}`,\n );\n orgCommand\n .command('list')\n .description('List organizations available to the saved identity.')\n .action(async function (this: Command) {\n await handleOrgList(dependencies, this.optsWithGlobals());\n });\n orgCommand\n .command('use <org>')\n .description('Set the default organization by ID or exact name.')\n .action(async function (this: Command, organizationSelector: string) {\n await handleOrgUse(\n dependencies,\n organizationSelector,\n this.optsWithGlobals(),\n );\n });\n program.addCommand(orgCommand);\n\n const updateCommand = configureCommandPresentation(\n new Command('update').description(\n 'Update mgcl to the latest published npm release.',\n ),\n )\n .helpGroup('Workspace:')\n .addHelpText(\n 'after',\n `\\n${formatExamples('Examples', ['mgcl update', 'mgcl --update'])}`,\n );\n updateCommand.action(async function (this: Command) {\n await handleSelfUpdate(dependencies, this.optsWithGlobals());\n });\n program.addCommand(updateCommand);\n\n const operationalCommandGroups = new Map<string, Command>();\n for (const operationSpec of operationSpecs) {\n addRegistryOperationCommand({\n program,\n commandGroups: operationalCommandGroups,\n dependencies,\n operationSpec,\n });\n }\n\n return program;\n}\n","import { z } from 'zod';\nimport { CliError } from './errors';\nimport type { CliOrganization } from './state';\n\nconst workosOrganizationsResponseSchema = z.object({\n organizations: z.array(\n z.object({\n id: z.string().min(1),\n name: z.string().min(1),\n primaryDomain: z.string().nullable().optional(),\n }),\n ),\n success: z.boolean(),\n});\n\nconst workosUserSchema = z.object({\n email: z.string().nullable(),\n id: z.string().min(1),\n});\n\nconst graphQlResponseSchema = z.object({\n data: z.record(z.string(), z.unknown()).optional(),\n errors: z\n .array(\n z.object({\n message: z.string().min(1),\n }),\n )\n .optional(),\n});\nconst apiErrorResponseSchema = z.object({\n errors: z\n .array(\n z.object({\n message: z.string().min(1),\n }),\n )\n .optional(),\n message: z.string().min(1).optional(),\n});\n\nfunction getApiErrorDetail(responseBody: unknown): string | null {\n const parsedResponse = apiErrorResponseSchema.safeParse(responseBody);\n if (!parsedResponse.success) {\n return null;\n }\n\n if (parsedResponse.data.message) {\n return parsedResponse.data.message;\n }\n\n if (!parsedResponse.data.errors || parsedResponse.data.errors.length === 0) {\n return null;\n }\n\n return parsedResponse.data.errors.map((error) => error.message).join('\\n');\n}\n\nexport interface ApiClient {\n executeGraphQl: (input: {\n accessToken: string;\n query: string;\n resultKey: string;\n variables: Record<string, unknown>;\n }) => Promise<unknown>;\n fetchOrganizations: (input: {\n accessToken: string;\n }) => Promise<CliOrganization[]>;\n fetchUser: (input: {\n accessToken: string;\n userId: string;\n }) => Promise<z.infer<typeof workosUserSchema>>;\n}\n\nexport function createMagicalApiClient({\n apiBaseUrl,\n fetchFn = fetch,\n}: {\n apiBaseUrl: string;\n fetchFn?: typeof fetch;\n}): ApiClient {\n async function fetchJson({\n accessToken,\n url,\n init,\n }: {\n accessToken: string;\n init?: RequestInit;\n url: string;\n }): Promise<unknown> {\n const headers = new Headers(init?.headers);\n headers.set('authorization', `Bearer ${accessToken}`);\n\n const response = await fetchFn(url, {\n ...init,\n headers,\n }).catch((error: unknown) => {\n throw new CliError(\n `Failed to reach Magical API at ${url}. Check MAGICAL_API_URL and make sure service-main is running.`,\n { cause: error },\n );\n });\n\n const responseBody = await response.json().catch((error: unknown) => {\n if (!response.ok) {\n throw new CliError(\n `Magical API request to ${url} failed with status ${response.status}.`,\n {\n cause: error,\n },\n );\n }\n\n throw new CliError(\n `Magical API returned a non-JSON response for ${url}.`,\n {\n cause: error,\n },\n );\n });\n if (!response.ok) {\n const errorDetail = getApiErrorDetail(responseBody);\n\n throw new CliError(\n `Magical API request to ${url} failed with status ${response.status}${errorDetail ? `: ${errorDetail}` : '.'}`,\n );\n }\n\n return responseBody;\n }\n\n return {\n async executeGraphQl({\n accessToken,\n query,\n resultKey,\n variables,\n }): Promise<unknown> {\n const headers = new Headers();\n headers.set('content-type', 'application/json');\n\n const parsedResponse = graphQlResponseSchema.safeParse(\n await fetchJson({\n accessToken,\n url: `${apiBaseUrl}/graphql`,\n init: {\n method: 'POST',\n headers,\n body: JSON.stringify({\n query,\n variables,\n }),\n },\n }),\n );\n\n if (!parsedResponse.success) {\n throw new CliError('GraphQL response payload was invalid.');\n }\n\n if (parsedResponse.data.errors && parsedResponse.data.errors.length > 0) {\n throw new CliError(\n parsedResponse.data.errors.map((error) => error.message).join('\\n'),\n );\n }\n\n return parsedResponse.data.data?.[resultKey] ?? null;\n },\n\n async fetchOrganizations({ accessToken }): Promise<CliOrganization[]> {\n const parsedResponse = workosOrganizationsResponseSchema.safeParse(\n await fetchJson({\n accessToken,\n url: `${apiBaseUrl}/workos/organizations`,\n }),\n );\n\n if (!parsedResponse.success) {\n throw new CliError('Organization list payload was invalid.');\n }\n\n return parsedResponse.data.organizations.map((organization) => ({\n id: organization.id,\n name: organization.name,\n primaryDomain: organization.primaryDomain ?? null,\n }));\n },\n\n async fetchUser({\n accessToken,\n userId,\n }): Promise<z.infer<typeof workosUserSchema>> {\n const parsedResponse = workosUserSchema.safeParse(\n await fetchJson({\n accessToken,\n url: `${apiBaseUrl}/workos/user/${userId}`,\n }),\n );\n\n if (!parsedResponse.success) {\n throw new CliError('User payload was invalid.');\n }\n\n return parsedResponse.data;\n },\n };\n}\n","import type { OperationSpec } from '@magical/mcp-registry';\nimport type { Command } from 'commander';\nimport { MagicalHelp } from './cli-formatting';\n\nexport const rootOperationalGroupDescriptions = new Map<string, string>([\n ['agents', 'Query agents.'],\n ['agent-runs', 'Query agent runs.'],\n ['automations', 'Manage automations.'],\n ['automation-runs', 'Inspect and control automation runs.'],\n ['catalog', 'Inspect available commands, models, and tools.'],\n ['graphql', 'Inspect GraphQL metadata.'],\n]);\n\nexport function configureCommandPresentation(command: Command): Command {\n const originalCreateCommand = command.createCommand.bind(command);\n command.createCommand = (name: string) =>\n configureCommandPresentation(originalCreateCommand(name));\n command.createHelp = () => new MagicalHelp();\n\n return command;\n}\n\nexport function createOperationHelpExamples(\n operationSpec: OperationSpec,\n): string[] {\n const baseCommand = `mgcl ${operationSpec.cli.path.join(' ')}`;\n const requiredOptions = operationSpec.cli.options\n .filter((optionSpec) => optionSpec.required)\n .map((optionSpec) => {\n if (optionSpec.valueType === 'boolean') {\n return `--${optionSpec.flagName}`;\n }\n\n if (optionSpec.valueType === 'number') {\n return `--${optionSpec.flagName} 10`;\n }\n\n if (optionSpec.valueType === 'json') {\n return `--${optionSpec.flagName} '{...}'`;\n }\n\n if (optionSpec.valueType === 'string-array') {\n return `--${optionSpec.flagName} value-a,value-b`;\n }\n\n return `--${optionSpec.flagName} <${optionSpec.flagName}>`;\n });\n const baseInvocation = [baseCommand, ...requiredOptions].join(' ');\n\n return [\n baseInvocation,\n `${baseInvocation} --org <org>`,\n `${baseInvocation} --json`,\n ];\n}\n","import os from 'node:os';\nimport path from 'node:path';\n\nexport const DEFAULT_MAGICAL_API_URL = 'https://api-agt.getmagical.io';\nexport const DEFAULT_WORKOS_API_URL = 'https://api.workos.com';\nexport const DEFAULT_WORKOS_CLIENT_ID = 'client_01JJZ6XJ1RF248P20WF63M4VAM';\nexport const DEFAULT_KEYCHAIN_SERVICE_NAME = '@getmagical/mcp-cli';\nexport const DEFAULT_CLI_DIST_TAG = 'latest';\nexport const DEFAULT_CLI_NPM_REGISTRY_URL = 'https://registry.npmjs.org/';\nexport const CLI_CONFIG_DIRECTORY_NAME = 'magical-mcp-cli';\nexport const CLI_STATE_FILE_NAME = 'state.json';\n\nexport interface RuntimeConfig {\n cliDistTag?: string;\n keychainServiceName: string;\n magicalApiUrl: string;\n npmRegistryUrl?: string;\n stateFilePath: string;\n workosApiUrl: string;\n workosClientId: string;\n workosAuthkitDomain?: string;\n}\n\nfunction resolvePlatformConfigDirectory(): string {\n const customConfigDirectory = process.env['MAGICAL_CLI_CONFIG_DIR'];\n if (customConfigDirectory) {\n return customConfigDirectory;\n }\n\n if (process.platform === 'darwin') {\n return path.join(os.homedir(), 'Library', 'Application Support');\n }\n\n if (process.platform === 'win32') {\n const appDataDirectory = process.env['APPDATA'];\n return appDataDirectory ?? path.join(os.homedir(), 'AppData', 'Roaming');\n }\n\n return process.env['XDG_CONFIG_HOME'] ?? path.join(os.homedir(), '.config');\n}\n\nexport function getRuntimeConfig(): RuntimeConfig {\n const configDirectory = path.join(\n resolvePlatformConfigDirectory(),\n CLI_CONFIG_DIRECTORY_NAME,\n );\n\n return {\n cliDistTag: process.env['MAGICAL_CLI_DIST_TAG'] ?? DEFAULT_CLI_DIST_TAG,\n magicalApiUrl: process.env['MAGICAL_API_URL'] ?? DEFAULT_MAGICAL_API_URL,\n npmRegistryUrl:\n process.env['MAGICAL_CLI_NPM_REGISTRY_URL'] ??\n DEFAULT_CLI_NPM_REGISTRY_URL,\n stateFilePath: path.join(configDirectory, CLI_STATE_FILE_NAME),\n workosApiUrl: DEFAULT_WORKOS_API_URL,\n workosClientId: process.env['WORKOS_CLIENT_ID'] ?? DEFAULT_WORKOS_CLIENT_ID,\n keychainServiceName: DEFAULT_KEYCHAIN_SERVICE_NAME,\n ...(process.env['WORKOS_AUTHKIT_DOMAIN']\n ? { workosAuthkitDomain: process.env['WORKOS_AUTHKIT_DOMAIN'] }\n : {}),\n };\n}\n\nexport function requireWorkosClientId(config: RuntimeConfig): string {\n return config.workosClientId;\n}\n","import keytar from 'keytar';\nimport type { CliAccount, RefreshTokenStore } from './state';\n\nfunction buildKeychainAccountName(account: CliAccount): string {\n return `${account.clientId}:${account.userId}`;\n}\n\nexport function createKeytarRefreshTokenStore(\n serviceName: string,\n): RefreshTokenStore {\n return {\n async clear(account) {\n await keytar.deletePassword(\n serviceName,\n buildKeychainAccountName(account),\n );\n },\n async load(account) {\n return keytar.getPassword(serviceName, buildKeychainAccountName(account));\n },\n async save(account, refreshToken) {\n await keytar.setPassword(\n serviceName,\n buildKeychainAccountName(account),\n refreshToken,\n );\n },\n };\n}\n","import { spawn } from 'node:child_process';\n\nexport async function openExternalUrl(url: string): Promise<void> {\n const command = resolveOpenCommand(url);\n\n const childProcess = spawn(command.executable, command.args, {\n detached: true,\n stdio: 'ignore',\n });\n\n await new Promise<void>((resolve, reject) => {\n childProcess.on('error', reject);\n childProcess.on('spawn', () => {\n childProcess.unref();\n resolve();\n });\n });\n}\n\nfunction resolveOpenCommand(url: string): {\n args: string[];\n executable: string;\n} {\n if (process.platform === 'darwin') {\n return { executable: 'open', args: [url] };\n }\n\n if (process.platform === 'win32') {\n return { executable: 'cmd', args: ['/c', 'start', '', url] };\n }\n\n return { executable: 'xdg-open', args: [url] };\n}\n","import { spawn } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { CliError } from './errors';\n\nexport const CLI_PACKAGE_NAME = '@getmagical/cli';\nexport const DEFAULT_CLI_DIST_TAG = 'latest';\nexport const DEFAULT_NPM_REGISTRY_URL = 'https://registry.npmjs.org/';\nexport const MANAGED_NODE_SUBPATH = 'runtime/node';\n\nexport interface SelfUpdateResult {\n installPrefix: string;\n packageSpecifier: string;\n registryUrl: string;\n}\n\ninterface NpmCommand {\n argsPrefix: string[];\n executable: string;\n}\n\nexport function resolveInstalledPackageRoot({\n entryFilePath,\n packageName,\n}: {\n entryFilePath: string;\n packageName: string;\n}): string | null {\n const packagePathSegments = packageName.split('/');\n let currentPath = path.dirname(entryFilePath);\n\n for (;;) {\n const currentPathSegments = currentPath.split(path.sep).filter(Boolean);\n const currentPackageSegments = currentPathSegments.slice(\n -packagePathSegments.length,\n );\n\n if (\n currentPackageSegments.length === packagePathSegments.length &&\n currentPackageSegments.every(\n (segment, index) => segment === packagePathSegments[index],\n )\n ) {\n return currentPath;\n }\n\n const parentPath = path.dirname(currentPath);\n if (parentPath === currentPath) {\n return null;\n }\n\n currentPath = parentPath;\n }\n}\n\nexport function resolveInstallPrefixFromPackageRoot(\n packageRootPath: string,\n): string | null {\n let currentPath = packageRootPath;\n\n for (;;) {\n if (path.basename(currentPath) === 'node_modules') {\n const nodeModulesParentPath = path.dirname(currentPath);\n if (path.basename(nodeModulesParentPath) === 'lib') {\n return path.dirname(nodeModulesParentPath);\n }\n\n return nodeModulesParentPath;\n }\n\n const parentPath = path.dirname(currentPath);\n if (parentPath === currentPath) {\n return null;\n }\n\n currentPath = parentPath;\n }\n}\n\nfunction resolveNpmCommandFromPath(): NpmCommand {\n return {\n argsPrefix: [],\n executable: process.platform === 'win32' ? 'npm.cmd' : 'npm',\n };\n}\n\nfunction resolveManagedNpmCommand(installPrefix: string): NpmCommand | null {\n if (process.platform === 'win32') {\n return null;\n }\n\n const managedNodeExecutable = path.join(\n installPrefix,\n MANAGED_NODE_SUBPATH,\n 'bin',\n 'node',\n );\n const managedNpmCli = path.join(\n installPrefix,\n MANAGED_NODE_SUBPATH,\n 'lib',\n 'node_modules',\n 'npm',\n 'bin',\n 'npm-cli.js',\n );\n\n if (!fs.existsSync(managedNodeExecutable) || !fs.existsSync(managedNpmCli)) {\n return null;\n }\n\n return {\n argsPrefix: [managedNpmCli],\n executable: managedNodeExecutable,\n };\n}\n\nexport async function installPublishedCli({\n distTag,\n installPrefix,\n packageName,\n registryUrl,\n}: {\n distTag: string;\n installPrefix: string;\n packageName: string;\n registryUrl: string;\n}): Promise<SelfUpdateResult> {\n const npmCommand =\n resolveManagedNpmCommand(installPrefix) ?? resolveNpmCommandFromPath();\n const packageSpecifier = `${packageName}@${distTag}`;\n const npmArguments = [\n ...npmCommand.argsPrefix,\n 'install',\n '--global',\n packageSpecifier,\n '--prefix',\n installPrefix,\n '--registry',\n registryUrl,\n ];\n\n await new Promise<void>((resolve, reject) => {\n const childProcess = spawn(npmCommand.executable, npmArguments, {\n stdio: 'inherit',\n });\n\n childProcess.on('error', (error: Error & { code?: string }) => {\n if (error.code === 'ENOENT') {\n reject(\n new CliError(\n 'npm is required to update mgcl. Install npm and rerun the command.',\n { cause: error },\n ),\n );\n return;\n }\n\n reject(error);\n });\n\n childProcess.on('exit', (exitCode) => {\n if (exitCode === 0) {\n resolve();\n return;\n }\n\n reject(\n new CliError(\n `npm install exited with status ${String(exitCode ?? 'unknown')}.`,\n ),\n );\n });\n });\n\n return {\n installPrefix,\n packageSpecifier,\n registryUrl,\n };\n}\n\nexport async function selfUpdateInstalledCli({\n distTag = DEFAULT_CLI_DIST_TAG,\n entryFilePath = fileURLToPath(import.meta.url),\n packageName = CLI_PACKAGE_NAME,\n registryUrl = DEFAULT_NPM_REGISTRY_URL,\n}: {\n distTag?: string;\n entryFilePath?: string;\n packageName?: string;\n registryUrl?: string;\n} = {}): Promise<SelfUpdateResult> {\n const packageRootPath = resolveInstalledPackageRoot({\n entryFilePath,\n packageName,\n });\n if (!packageRootPath) {\n throw new CliError(\n 'Self-update is only available for installed CLIs. Use the install script or \"npm install -g @getmagical/cli\".',\n );\n }\n\n const installPrefix = resolveInstallPrefixFromPackageRoot(packageRootPath);\n if (!installPrefix) {\n throw new CliError(\n 'Could not determine the installed npm prefix for this CLI. Reinstall with the install script and try again.',\n );\n }\n\n return installPublishedCli({\n distTag,\n installPrefix,\n packageName,\n registryUrl,\n });\n}\n","import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\n\nexport const cliAccountSchema = z.object({\n clientId: z.string().min(1),\n email: z.string().nullable(),\n userId: z.string().min(1),\n});\n\nexport const cliOrganizationSchema = z.object({\n id: z.string().min(1),\n name: z.string().min(1),\n primaryDomain: z.string().nullable().default(null),\n});\n\nexport const cliStateSchema = z.object({\n account: cliAccountSchema,\n defaultOrgId: z.string().nullable(),\n lastUsedOrgId: z.string().nullable(),\n organizations: z.array(cliOrganizationSchema),\n});\n\nexport type CliAccount = z.infer<typeof cliAccountSchema>;\nexport type CliOrganization = z.infer<typeof cliOrganizationSchema>;\nexport type CliState = z.infer<typeof cliStateSchema>;\n\nexport interface StateStore {\n clear: () => Promise<void>;\n load: () => Promise<CliState | null>;\n save: (state: CliState) => Promise<void>;\n}\n\nexport interface RefreshTokenStore {\n clear: (account: CliAccount) => Promise<void>;\n load: (account: CliAccount) => Promise<string | null>;\n save: (account: CliAccount, refreshToken: string) => Promise<void>;\n}\n\nexport function createFileStateStore(stateFilePath: string): StateStore {\n return {\n async clear() {\n await rm(stateFilePath, { force: true });\n },\n async load() {\n try {\n const fileContents = await readFile(stateFilePath, 'utf8');\n const parsed = cliStateSchema.safeParse(JSON.parse(fileContents));\n if (!parsed.success) {\n throw new CliError('Stored CLI state is invalid.');\n }\n\n return parsed.data;\n } catch (error: unknown) {\n if (\n error instanceof Error &&\n 'code' in error &&\n error.code === 'ENOENT'\n ) {\n return null;\n }\n\n if (error instanceof CliError) {\n throw error;\n }\n\n throw new CliError('Failed to load CLI state.', { cause: error });\n }\n },\n async save(state) {\n await mkdir(path.dirname(stateFilePath), { recursive: true });\n await writeFile(stateFilePath, `${JSON.stringify(state, null, 2)}\\n`);\n },\n };\n}\n\nexport function createMemoryRefreshTokenStore(): RefreshTokenStore {\n const values = new Map<string, string>();\n\n return {\n async clear(account) {\n values.delete(buildRefreshTokenKey(account));\n },\n async load(account) {\n return values.get(buildRefreshTokenKey(account)) ?? null;\n },\n async save(account, refreshToken) {\n values.set(buildRefreshTokenKey(account), refreshToken);\n },\n };\n}\n\nfunction buildRefreshTokenKey(account: CliAccount): string {\n return `${account.clientId}:${account.userId}`;\n}\n","import { z } from 'zod';\nimport { CliError } from './errors';\n\nconst DEFAULT_DEVICE_POLL_INTERVAL_SECONDS = 5;\n\nfunction buildFormHeaders(): Headers {\n const headers = new Headers();\n headers.set('content-type', 'application/x-www-form-urlencoded');\n return headers;\n}\n\nconst deviceAuthorizationSchema = z.object({\n device_code: z.string().min(1),\n expires_in: z.number().int().positive().optional(),\n interval: z.number().int().positive().optional(),\n user_code: z.string().min(1),\n verification_uri: z.url(),\n verification_uri_complete: z.url().optional(),\n});\n\nconst tokenResponseSchema = z.object({\n access_token: z.string().min(1),\n expires_in: z.number().int().positive().optional(),\n refresh_token: z.string().min(1),\n token_type: z.string().optional(),\n});\n\nconst tokenErrorSchema = z.object({\n error: z.string().min(1),\n error_description: z.string().optional(),\n});\n\nconst accessTokenClaimsSchema = z.object({\n org_id: z.string().min(1).optional(),\n sid: z.string().min(1).optional(),\n sub: z.string().min(1),\n});\n\nexport type DeviceAuthorization = z.infer<typeof deviceAuthorizationSchema>;\nexport type TokenResponse = z.infer<typeof tokenResponseSchema>;\nexport type AccessTokenClaims = z.infer<typeof accessTokenClaimsSchema>;\n\nexport interface AuthClient {\n decodeAccessTokenClaims: (accessToken: string) => AccessTokenClaims;\n pollForDeviceTokens: (input: {\n clientId: string;\n deviceCode: string;\n expiresInSeconds?: number;\n intervalSeconds?: number;\n }) => Promise<TokenResponse>;\n refreshTokens: (input: {\n clientId: string;\n organizationId?: string;\n refreshToken: string;\n }) => Promise<TokenResponse>;\n startDeviceAuthorization: (input: {\n clientId: string;\n }) => Promise<DeviceAuthorization>;\n}\n\nexport function createWorkosAuthClient({\n fetchFn = fetch,\n sleep = async (milliseconds): Promise<void> => {\n await new Promise((resolve) => {\n setTimeout(resolve, milliseconds);\n });\n },\n workosApiUrl,\n}: {\n fetchFn?: typeof fetch;\n sleep?: (milliseconds: number) => Promise<void>;\n workosApiUrl: string;\n}): AuthClient {\n async function postForm<TSchema extends z.ZodTypeAny>({\n endpointPath,\n formData,\n responseSchema,\n }: {\n endpointPath: string;\n formData: URLSearchParams;\n responseSchema: TSchema;\n }): Promise<z.infer<TSchema>> {\n const response = await fetchFn(`${workosApiUrl}${endpointPath}`, {\n method: 'POST',\n headers: buildFormHeaders(),\n body: formData,\n });\n\n const responseBody = await response.json();\n if (!response.ok) {\n const parsedError = tokenErrorSchema.safeParse(responseBody);\n if (parsedError.success) {\n throw new CliError(\n parsedError.data.error_description ?? parsedError.data.error,\n );\n }\n\n throw new CliError(\n `WorkOS request failed with status ${response.status}.`,\n );\n }\n\n const parsedResponse = responseSchema.safeParse(responseBody);\n if (!parsedResponse.success) {\n throw new CliError('WorkOS returned an unexpected response payload.');\n }\n\n return parsedResponse.data;\n }\n\n return {\n decodeAccessTokenClaims(accessToken) {\n const [, payloadSegment] = accessToken.split('.');\n if (!payloadSegment) {\n throw new CliError('WorkOS access token is malformed.');\n }\n\n const payload: unknown = JSON.parse(\n Buffer.from(payloadSegment, 'base64url').toString('utf8'),\n );\n const parsedClaims = accessTokenClaimsSchema.safeParse(payload);\n if (!parsedClaims.success) {\n throw new CliError('WorkOS access token is missing required claims.');\n }\n\n return parsedClaims.data;\n },\n\n async pollForDeviceTokens({\n clientId,\n deviceCode,\n expiresInSeconds,\n intervalSeconds,\n }): Promise<TokenResponse> {\n const timeoutAt = Date.now() + (expiresInSeconds ?? 15 * 60) * 1000;\n const initialIntervalMilliseconds =\n (intervalSeconds ?? DEFAULT_DEVICE_POLL_INTERVAL_SECONDS) * 1000;\n\n async function poll(\n nextIntervalMilliseconds: number,\n ): Promise<TokenResponse> {\n if (Date.now() >= timeoutAt) {\n throw new CliError(\n 'WorkOS device authorization expired before completion.',\n );\n }\n\n const formData = new URLSearchParams();\n formData.set('client_id', clientId);\n formData.set('device_code', deviceCode);\n formData.set(\n 'grant_type',\n 'urn:ietf:params:oauth:grant-type:device_code',\n );\n\n const response = await fetchFn(\n `${workosApiUrl}/user_management/authenticate`,\n {\n method: 'POST',\n headers: buildFormHeaders(),\n body: formData,\n },\n );\n\n const responseBody = await response.json();\n if (response.ok) {\n const parsedTokens = tokenResponseSchema.safeParse(responseBody);\n if (!parsedTokens.success) {\n throw new CliError('WorkOS returned an unexpected token response.');\n }\n\n return parsedTokens.data;\n }\n\n const parsedError = tokenErrorSchema.safeParse(responseBody);\n if (!parsedError.success) {\n throw new CliError(\n `WorkOS device authorization failed with status ${response.status}.`,\n );\n }\n\n if (parsedError.data.error === 'authorization_pending') {\n await sleep(nextIntervalMilliseconds);\n return poll(nextIntervalMilliseconds);\n }\n\n if (parsedError.data.error === 'slow_down') {\n const slowedIntervalMilliseconds = nextIntervalMilliseconds + 5000;\n await sleep(slowedIntervalMilliseconds);\n return poll(slowedIntervalMilliseconds);\n }\n\n throw new CliError(\n parsedError.data.error_description ?? parsedError.data.error,\n );\n }\n\n return poll(initialIntervalMilliseconds);\n },\n\n async refreshTokens({\n clientId,\n organizationId,\n refreshToken,\n }): Promise<TokenResponse> {\n const formData = new URLSearchParams();\n formData.set('client_id', clientId);\n formData.set('grant_type', 'refresh_token');\n formData.set('refresh_token', refreshToken);\n\n if (organizationId) {\n formData.set('organization_id', organizationId);\n }\n\n return postForm({\n endpointPath: '/user_management/authenticate',\n formData,\n responseSchema: tokenResponseSchema,\n });\n },\n\n async startDeviceAuthorization({ clientId }): Promise<DeviceAuthorization> {\n const formData = new URLSearchParams();\n formData.set('client_id', clientId);\n\n return postForm({\n endpointPath: '/user_management/authorize/device',\n formData,\n responseSchema: deviceAuthorizationSchema,\n });\n },\n };\n}\n","#!/usr/bin/env node\n\nimport { formatCliError } from './cli-formatting';\nimport { getErrorMessage } from './errors';\nimport { buildProgram, createDefaultDependencies } from './program';\n\nconst program = buildProgram(createDefaultDependencies());\n\nprogram.parseAsync(process.argv).catch((error: unknown) => {\n process.stderr.write(`${formatCliError(getErrorMessage(error))}\\n`);\n process.exitCode = 1;\n});\n"],"mappings":";;;AAAA,SAAS,SAAS,0BAA0B,iBAAiB;AAC7D,SAAS,YAAY;AAGrB,IAAM,cAAc;AACpB,IAAM,YAAY;AAGlB,SAAS,WACP,OACA,OACA,UAAU,MACF;AACR,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,UAAU,OAAO,KAAK;AAC/B;AAEA,SAAS,OAAO,MAAc,QAAQ,GAAW;AAC/C,QAAM,UAAU,IAAI,OAAO,KAAK;AAChC,SAAO,KACJ,MAAM,IAAI,EACV,IAAI,CAAC,SAAS,GAAG,OAAO,GAAG,IAAI,EAAE,EACjC,KAAK,IAAI;AACd;AAEA,SAAS,UAAU,OAAuB;AACxC,SAAO,yBAAyB,KAAK;AACvC;AAEA,SAAS,aAAa,OAAuB;AAC3C,SAAO,UAAU,KAAK,EAAE;AAC1B;AAEA,SAAS,QAAQ,OAAe,OAAuB;AACrD,SAAO,MAAM,OAAO,QAAQ,MAAM,SAAS,aAAa,KAAK,CAAC;AAChE;AAEA,SAAS,cAAc,OAAuB;AAC5C,SAAO,WAAW,OAAO,CAAC,QAAQ,MAAM,CAAC;AAC3C;AAEA,SAAS,YAAY,OAAuB;AAC1C,SAAO,WAAW,OAAO,KAAK;A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eAAe,eAAe,CAAC,CAAC;AAAA,EACnE;AACF,gBAAc,OAAO,iBAA+B;AAClD,UAAM,iBAAiB,cAAc,KAAK,gBAAgB,CAAC;AAAA,EAC7D,CAAC;AACD,EAAAA,SAAQ,WAAW,aAAa;AAEhC,QAAM,2BAA2B,oBAAI,IAAqB;AAC1D,aAAW,iBAAiB,gBAAgB;AAC1C,gCAA4B;AAAA,MAC1B,SAAAA;AAAA,MACA,eAAe;AAAA,MACf;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAOA;AACT;;;ASluBA,IAAM,UAAU,aAAa,0BAA0B,CAAC;AAExD,QAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,UAAmB;AACzD,UAAQ,OAAO,MAAM,GAAG,eAAe,gBAAgB,KAAK,CAAC,CAAC;AAAA,CAAI;AAClE,UAAQ,WAAW;AACrB,CAAC;","names":["z","z","spawn","path","DEFAULT_CLI_DIST_TAG","path","spawn","path","z","z","path","z","z","isRecord","program"]}
1
+ {"version":3,"sources":["../src/cli-formatting.ts","../src/errors.ts","../../mcp-registry/src/operation-specs.ts","../../mcp-registry/src/operation-spec.ts","../src/program.ts","../src/api.ts","../src/config.ts","../src/settings.ts","../src/auth-login.ts","../src/command-presentation.ts","../src/keychain.ts","../src/open-url.ts","../src/self-update.ts","../src/settings-command.ts","../src/state.ts","../src/workos-auth.ts","../src/index.ts"],"sourcesContent":["import { inspect, stripVTControlCharacters, styleText } from 'node:util';\nimport { Help } from 'commander';\nimport type { CliAccount, CliOrganization } from './state';\n\nconst EMPTY_VALUE = '-';\nconst TABLE_GAP = ' ';\ntype TerminalStyle = Parameters<typeof styleText>[0];\n\nfunction applyStyle(\n value: string,\n style: TerminalStyle,\n enabled = true,\n): string {\n if (!enabled) {\n return value;\n }\n\n return styleText(style, value);\n}\n\nfunction indent(text: string, level = 2): string {\n const padding = ' '.repeat(level);\n return text\n .split('\\n')\n .map((line) => `${padding}${line}`)\n .join('\\n');\n}\n\nfunction stripAnsi(value: string): string {\n return stripVTControlCharacters(value);\n}\n\nfunction displayWidth(value: string): number {\n return stripAnsi(value).length;\n}\n\nfunction padCell(value: string, width: number): string {\n return value.padEnd(width + value.length - displayWidth(value));\n}\n\nfunction formatHeading(title: string): string {\n return applyStyle(title, ['bold', 'cyan']);\n}\n\nfunction formatLabel(label: string): string {\n return applyStyle(label, 'dim');\n}\n\nfunction formatCommandSnippet(command: string): string {\n return applyStyle(command, ['bold', 'cyan']);\n}\n\nfunction formatFlag(flag: string): string {\n return applyStyle(flag, ['bold', 'yellow']);\n}\n\nfunction formatErrorLabel(label: string): string {\n return applyStyle(label, ['bold', 'red'], process.stderr.isTTY);\n}\n\nfunction splitWords(value: string): string[] {\n const tokens: string[] = [];\n\n for (const word of value\n .replaceAll('_', ' ')\n .replaceAll('-', ' ')\n .split(' ')) {\n if (word.length === 0) {\n continue;\n }\n\n let currentToken = word[0] ?? '';\n for (const character of word.slice(1)) {\n const previousCharacter = currentToken.at(-1) ?? '';\n const shouldBreak =\n character >= 'A' &&\n character <= 'Z' &&\n ((previousCharacter >= 'a' && previousCharacter <= 'z') ||\n (previousCharacter >= '0' && previousCharacter <= '9'));\n\n if (shouldBreak) {\n tokens.push(currentToken);\n currentToken = character;\n continue;\n }\n\n currentToken += character;\n }\n\n tokens.push(currentToken);\n }\n\n return tokens;\n}\n\nfunction startCase(value: string): string {\n return splitWords(value)\n .map((segment) => {\n const lowerSegment = segment.toLowerCase();\n if (lowerSegment === 'id') {\n return 'ID';\n }\n\n if (lowerSegment === 'url') {\n return 'URL';\n }\n\n if (lowerSegment === 'api') {\n return 'API';\n }\n\n return segment.charAt(0).toUpperCase() + segment.slice(1);\n })\n .join(' ');\n}\n\nfunction formatScalar(value: unknown): string {\n if (value === null || value === undefined) {\n return EMPTY_VALUE;\n }\n\n if (typeof value === 'string') {\n return value.length === 0 ? EMPTY_VALUE : value;\n }\n\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n\n return inspect(value, {\n breakLength: Infinity,\n colors: false,\n compact: true,\n depth: 2,\n });\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isPrimitiveLike(value: unknown): boolean {\n return (\n value === null ||\n value === undefined ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n );\n}\n\nfunction formatTable(options: {\n columns: readonly string[];\n rows: readonly (readonly string[])[];\n}): string {\n const widths = options.columns.map((column, columnIndex) =>\n Math.max(\n displayWidth(column),\n ...options.rows.map((row) => displayWidth(row[columnIndex] ?? '')),\n ),\n );\n\n const renderRow = (cells: readonly string[]): string =>\n cells\n .map((cell, columnIndex) => padCell(cell, widths[columnIndex] ?? 0))\n .join(TABLE_GAP)\n .trimEnd();\n\n const divider = widths.map((width) => '-'.repeat(width)).join(TABLE_GAP);\n\n return [\n renderRow(options.columns.map((column) => applyStyle(column, 'bold'))),\n divider,\n ...options.rows.map(renderRow),\n ].join('\\n');\n}\n\nfunction canRenderRecordArrayAsTable(\n items: readonly unknown[],\n): items is readonly Record<string, unknown>[] {\n if (items.length === 0 || !items.every(isRecord)) {\n return false;\n }\n\n const keys = [...new Set(items.flatMap((item) => Object.keys(item)))];\n\n if (keys.length === 0 || keys.length > 8) {\n return false;\n }\n\n return items.every((item) => keys.every((key) => isPrimitiveLike(item[key])));\n}\n\nfunction formatRecord(record: Record<string, unknown>): string {\n const entries = Object.entries(record);\n if (entries.length === 0) {\n return EMPTY_VALUE;\n }\n\n const labelWidth = Math.max(\n ...entries.map(([key]) => displayWidth(startCase(key))),\n );\n\n return entries\n .map(([key, value]) => {\n const label = `${startCase(key)}:`;\n if (isPrimitiveLike(value)) {\n return `${padCell(formatLabel(label), labelWidth + 1)} ${formatScalar(value)}`;\n }\n\n return `${formatLabel(label)}\\n${indent(formatHumanReadableOutput(value))}`;\n })\n .join('\\n');\n}\n\nfunction formatArray(items: readonly unknown[]): string {\n if (items.length === 0) {\n return 'No results.';\n }\n\n if (items.every(isPrimitiveLike)) {\n return items.map((item) => `- ${formatScalar(item)}`).join('\\n');\n }\n\n if (canRenderRecordArrayAsTable(items)) {\n const keys = [...new Set(items.flatMap((item) => Object.keys(item)))];\n\n return formatTable({\n columns: keys.map((key) => startCase(key)),\n rows: items.map((item) => keys.map((key) => formatScalar(item[key]))),\n });\n }\n\n return items\n .map((item, index) => {\n const title = formatHeading(`Item ${index + 1}`);\n return `${title}\\n${indent(formatHumanReadableOutput(item))}`;\n })\n .join('\\n\\n');\n}\n\nfunction renderKeyValueBlock(entries: readonly [string, string][]): string {\n const labelWidth = Math.max(...entries.map(([label]) => displayWidth(label)));\n return entries\n .map(\n ([label, value]) =>\n `${padCell(formatLabel(`${label}:`), labelWidth + 1)} ${value}`,\n )\n .join('\\n');\n}\n\nfunction renderSection(title: string, bodyLines: readonly string[]): string {\n return [formatHeading(title), '', ...bodyLines].join('\\n');\n}\n\nexport class MagicalHelp extends Help {\n private outputHasColors = process.stdout.isTTY;\n\n public constructor() {\n super();\n this.helpWidth = 96;\n this.showGlobalOptions = true;\n this.sortSubcommands = true;\n }\n\n public override prepareContext(contextOptions: {\n error?: boolean;\n helpWidth?: number;\n outputHasColors?: boolean;\n }): void {\n super.prepareContext(contextOptions);\n this.outputHasColors =\n contextOptions.outputHasColors ?? process.stdout.isTTY;\n }\n\n public override styleTitle(str: string): string {\n return applyStyle(str, ['bold', 'cyan'], this.outputHasColors);\n }\n\n public override styleCommandText(str: string): string {\n return applyStyle(str, ['bold', 'cyan'], this.outputHasColors);\n }\n\n public override styleSubcommandText(str: string): string {\n return applyStyle(str, ['bold', 'cyan'], this.outputHasColors);\n }\n\n public override styleOptionText(str: string): string {\n return applyStyle(str, ['bold', 'yellow'], this.outputHasColors);\n }\n\n public override styleArgumentText(str: string): string {\n return applyStyle(str, ['bold', 'green'], this.outputHasColors);\n }\n\n public override styleDescriptionText(str: string): string {\n return applyStyle(str, 'dim', this.outputHasColors);\n }\n}\n\nexport function formatAuthLoginPrompt(options: {\n userCode: string;\n verificationUrl: string;\n}): string {\n return renderSection('Sign In With Your Browser', [\n renderKeyValueBlock([\n ['Open', options.verificationUrl],\n ['Code', options.userCode],\n ]),\n ]);\n}\n\nexport function formatAuthLoginSuccess(options: {\n account: CliAccount;\n defaultOrganization: CliOrganization | null;\n organizationCount: number;\n}): string {\n return renderSection('Signed In', [\n renderKeyValueBlock([\n ['Account', options.account.email ?? options.account.userId],\n ['Organizations', String(options.organizationCount)],\n [\n 'Default org',\n options.defaultOrganization\n ? `${options.defaultOrganization.name} (${options.defaultOrganization.id})`\n : 'None selected',\n ],\n ]),\n ]);\n}\n\nexport function formatBrowserOpenFallback(): string {\n return 'Browser auto-open failed. Paste the URL above into any browser.';\n}\n\nexport function formatLogoutSuccess(): string {\n return renderSection('Signed Out', ['Saved CLI auth state was cleared.']);\n}\n\nexport function formatOrganizationList(options: {\n defaultOrgId: string | null;\n lastUsedOrgId: string | null;\n organizations: readonly CliOrganization[];\n}): string {\n if (options.organizations.length === 0) {\n return renderSection('Organizations', ['No organizations are available.']);\n }\n\n const rows = options.organizations.map((organization) => {\n const status = [\n options.defaultOrgId === organization.id ? 'default' : null,\n options.lastUsedOrgId === organization.id ? 'last used' : null,\n ]\n .filter((value) => value !== null)\n .join(', ');\n\n return [\n status || EMPTY_VALUE,\n organization.name,\n organization.id,\n organization.primaryDomain ?? EMPTY_VALUE,\n ];\n });\n\n return renderSection('Organizations', [\n formatTable({\n columns: ['Status', 'Name', 'ID', 'Primary domain'],\n rows,\n }),\n ]);\n}\n\nexport function formatDefaultOrganizationSelection(\n organization: CliOrganization,\n): string {\n return renderSection('Default Organization Updated', [\n `${organization.name} (${organization.id})`,\n ]);\n}\n\nexport function formatHumanReadableOutput(value: unknown): string {\n if (isPrimitiveLike(value)) {\n return formatScalar(value);\n }\n\n if (Array.isArray(value)) {\n return formatArray(value);\n }\n\n if (isRecord(value)) {\n return formatRecord(value);\n }\n\n return inspect(value, {\n colors: false,\n depth: null,\n });\n}\n\nexport function formatCliError(message: string): string {\n return `${formatErrorLabel('Error:')} ${message}`;\n}\n\nexport function formatExamples(\n title: string,\n examples: readonly string[],\n): string {\n return [\n formatHeading(title),\n '',\n ...examples.map((example) => ` ${formatCommandSnippet(example)}`),\n ].join('\\n');\n}\n\nexport function formatOutputModesNote(): string {\n return renderSection('Output', [\n `Human-readable by default.`,\n `Add ${formatFlag('--json')} before or after a command for stable machine-readable output.`,\n ]);\n}\n","export class CliError extends Error {\n public constructor(\n message: string,\n options?: {\n cause?: unknown;\n },\n ) {\n super(message, options);\n this.name = 'CliError';\n }\n}\n\nexport function getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n return 'Unknown CLI error';\n}\n","import { z } from 'zod';\nimport { createOperationSpec } from './operation-spec';\nimport type { CliOptionSpec, OperationSpec } from './operation-types';\n\nfunction stringOption({\n description,\n flagName,\n inputKey,\n required = false,\n}: {\n description: string;\n flagName: string;\n inputKey: string;\n required?: boolean;\n}): CliOptionSpec {\n return {\n description,\n flagName,\n inputKey,\n required,\n valueType: 'string',\n };\n}\n\nfunction numberOption({\n description,\n flagName,\n inputKey,\n required = false,\n}: {\n description: string;\n flagName: string;\n inputKey: string;\n required?: boolean;\n}): CliOptionSpec {\n return {\n description,\n flagName,\n inputKey,\n required,\n valueType: 'number',\n };\n}\n\nfunction booleanOption({\n description,\n flagName,\n inputKey,\n}: {\n description: string;\n flagName: string;\n inputKey: string;\n}): CliOptionSpec {\n return {\n description,\n flagName,\n inputKey,\n valueType: 'boolean',\n };\n}\n\nfunction stringArrayOption({\n description,\n flagName,\n inputKey,\n}: {\n description: string;\n flagName: string;\n inputKey: string;\n}): CliOptionSpec {\n return {\n description,\n flagName,\n inputKey,\n valueHint: 'comma-separated',\n valueType: 'string-array',\n };\n}\n\nfunction jsonOption({\n description,\n flagName,\n inputKey,\n required = false,\n}: {\n description: string;\n flagName: string;\n inputKey: string;\n required?: boolean;\n}): CliOptionSpec {\n return {\n description,\n flagName,\n inputKey,\n required,\n valueHint: 'JSON',\n valueType: 'json',\n };\n}\n\nconst jsonObjectSchema = z.record(z.string(), z.unknown());\n\nexport const operationSpecs = [\n createOperationSpec({\n operationName: 'GetAgent',\n kind: 'query',\n inputSchema: z.object({\n id: z.string().min(1),\n }),\n cli: {\n name: 'get-agent',\n path: ['agents', 'get'],\n description: 'Fetch a single agent with config and schema fields.',\n resultKey: 'agent',\n options: [\n stringOption({\n inputKey: 'id',\n flagName: 'id',\n description: 'Agent ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'agent.graphql' },\n document: `# Query to fetch a single agent with all fields\n# Config selection is limited to scalar/JSON fields to keep responses flat\nquery GetAgent($id: ID!) {\n agent(id: $id) {\n id\n name\n description\n instructions\n organizationId\n createdAt\n updatedAt\n sourceAgentId\n inputSchema\n outputSchema\n config {\n type\n language\n model\n tools\n maxSessionMessages\n commonParametersSchema\n taskQueue\n waitUponQueueing\n queueableAgentIds\n additionalSystemPrompt\n ignoreUnstableSessionState\n }\n childAgentIds\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAgentRun',\n kind: 'query',\n inputSchema: z.object({\n id: z.string().min(1),\n }),\n cli: {\n name: 'get-agent-run',\n path: ['agent-runs', 'get'],\n description: 'Fetch a single agent run.',\n resultKey: 'agentRun',\n options: [\n stringOption({\n inputKey: 'id',\n flagName: 'id',\n description: 'Agent run ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'agentRun.graphql' },\n document: `# Query a single agent run\nquery GetAgentRun($id: ID!) {\n agentRun(id: $id) {\n id\n agentVersionId\n agentName\n status\n statusDetail\n isChildAgent\n input\n startedAt\n finishedAt\n parentAgentRunId\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomationAgents',\n kind: 'query',\n inputSchema: z.object({\n id: z.string().min(1),\n }),\n cli: {\n name: 'get-automation-agents',\n path: ['automations', 'agents'],\n description: 'Fetch the agents attached to an automation.',\n resultKey: 'automation',\n options: [\n stringOption({\n inputKey: 'id',\n flagName: 'id',\n description: 'Automation ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'automationAgents.graphql' },\n document: `# Query to fetch automation agents with flat fields only\n# Excludes nested agent config and schemas for MCP tool simplicity\nquery GetAutomationAgents($id: ID!) {\n automation(id: $id) {\n id\n name\n agents {\n automationId\n agentId\n isTrigger\n agent {\n id\n name\n description\n instructions\n organizationId\n createdAt\n updatedAt\n sourceAgentId\n childAgentIds\n }\n }\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomationRun',\n kind: 'query',\n inputSchema: z.object({\n id: z.string().min(1),\n }),\n cli: {\n name: 'get-automation-run',\n path: ['automation-runs', 'get'],\n description: 'Fetch a single automation run.',\n resultKey: 'automationRun',\n options: [\n stringOption({\n inputKey: 'id',\n flagName: 'id',\n description: 'Automation run ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'automationRun.graphql' },\n document: `# Query a full automation run details payload\nquery GetAutomationRun($id: ID!) {\n automationRun(id: $id) {\n id\n automationId\n status\n statusDetail\n summary\n invocationType\n input\n additionalPrompt\n debugUrl\n createdAt\n startedAt\n pausedAt\n finishedAt\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomationRunAgentRuns',\n kind: 'query',\n inputSchema: z.object({\n automationRunId: z.string().min(1),\n }),\n cli: {\n name: 'get-automation-run-agent-runs',\n path: ['automation-runs', 'agent-runs'],\n description: 'Fetch ordered agent runs for an automation run.',\n resultKey: 'automationRunAgentRuns',\n options: [\n stringOption({\n inputKey: 'automationRunId',\n flagName: 'automation-run-id',\n description: 'Automation run ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'automationRunAgentRuns.graphql' },\n document: `# Query ordered agent runs for an automation run\nquery GetAutomationRunAgentRuns($automationRunId: ID!) {\n automationRunAgentRuns(automationRunId: $automationRunId) {\n id\n agentVersionId\n agentName\n status\n statusDetail\n isChildAgent\n input\n startedAt\n finishedAt\n parentAgentRunId\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomationRunIterations',\n kind: 'query',\n inputSchema: z.object({\n automationRunId: z.string().min(1),\n agentRunId: z.string().min(1).optional(),\n limit: z.number().int().positive().optional(),\n reverse: z.boolean().optional(),\n }),\n cli: {\n name: 'get-automation-run-iterations',\n path: ['automation-runs', 'iterations'],\n description: 'Fetch ordered iterations for an automation run.',\n resultKey: 'automationRunIterations',\n options: [\n stringOption({\n inputKey: 'automationRunId',\n flagName: 'automation-run-id',\n description: 'Automation run ID.',\n required: true,\n }),\n stringOption({\n inputKey: 'agentRunId',\n flagName: 'agent-run-id',\n description: 'Optional agent run ID to filter by.',\n }),\n numberOption({\n inputKey: 'limit',\n flagName: 'limit',\n description: 'Maximum number of iterations to return.',\n }),\n booleanOption({\n inputKey: 'reverse',\n flagName: 'reverse',\n description: 'Return newest iterations first.',\n }),\n ],\n },\n mcp: { fileName: 'automationRunIterations.graphql' },\n document: `# Query iterations for an automation run with optional filtering by agent run\nquery GetAutomationRunIterations(\n $automationRunId: ID!\n $agentRunId: ID\n $limit: Int\n $reverse: Boolean\n) {\n automationRunIterations(\n automationRunId: $automationRunId\n agentRunId: $agentRunId\n limit: $limit\n reverse: $reverse\n ) {\n id\n sequence\n agentRunId\n metadata\n startedAt\n finishedAt\n totalDurationMs\n llmResponseDurationMs\n withMarksScreenshotUrl\n withMarksMimeType\n memories {\n id\n type\n value\n sequence\n screenshotUrl\n screenshotMimeType\n }\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomationRuns',\n kind: 'query',\n inputSchema: z.object({\n automationId: z.string().min(1),\n status: z.array(z.string().min(1)).optional(),\n invocationType: z.array(z.string().min(1)).optional(),\n limit: z.number().int().positive().optional(),\n page: z.number().int().positive().optional(),\n }),\n cli: {\n name: 'get-automation-runs',\n path: ['automation-runs', 'list'],\n description: 'Fetch automation run history.',\n resultKey: 'automationRuns',\n options: [\n stringOption({\n inputKey: 'automationId',\n flagName: 'automation-id',\n description: 'Automation ID.',\n required: true,\n }),\n stringArrayOption({\n inputKey: 'status',\n flagName: 'status',\n description: 'Optional run statuses.',\n }),\n stringArrayOption({\n inputKey: 'invocationType',\n flagName: 'invocation-type',\n description: 'Optional invocation types.',\n }),\n numberOption({\n inputKey: 'limit',\n flagName: 'limit',\n description: 'Maximum number of runs to return.',\n }),\n numberOption({\n inputKey: 'page',\n flagName: 'page',\n description: 'Page number.',\n }),\n ],\n },\n mcp: { fileName: 'automationRuns.graphql' },\n document: `# Query automation run history for a specific automation with optional filters\nquery GetAutomationRuns(\n $automationId: ID!\n $status: [RunStatus!]\n $invocationType: [InvocationType!]\n $limit: Int\n $page: Int\n) {\n automationRuns(\n automationId: $automationId\n status: $status\n invocationType: $invocationType\n limit: $limit\n page: $page\n ) {\n id\n automationId\n status\n statusDetail\n invocationType\n summary\n createdAt\n startedAt\n pausedAt\n finishedAt\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomations',\n kind: 'query',\n inputSchema: z.object({\n limit: z.number().positive().optional(),\n order: jsonObjectSchema.optional(),\n where: jsonObjectSchema.optional(),\n }),\n cli: {\n name: 'get-automations',\n path: ['automations', 'list'],\n description: 'Fetch automations with optional list filters.',\n resultKey: 'automations',\n options: [\n numberOption({\n inputKey: 'limit',\n flagName: 'limit',\n description: 'Maximum number of automations to return.',\n }),\n jsonOption({\n inputKey: 'order',\n flagName: 'order-json',\n description: 'GraphQL order object.',\n }),\n jsonOption({\n inputKey: 'where',\n flagName: 'where-json',\n description: 'GraphQL filter object.',\n }),\n ],\n },\n mcp: { fileName: 'automations.graphql' },\n document: `# Query to fetch automations with flat fields only (no nested objects)\n# Excludes config and agents for MCP tool simplicity\nquery GetAutomations(\n $limit: Float\n $order: AutomationsOrder\n $where: AutomationsWhereInput\n) {\n automations(limit: $limit, order: $order, where: $where) {\n id\n name\n organizationId\n createdAt\n updatedAt\n environment\n lastSavedAt\n publishedVersionId\n draftVersionId\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAutomationWithConfigs',\n kind: 'query',\n inputSchema: z.object({\n id: z.string().min(1),\n }),\n cli: {\n name: 'get-automation-with-configs',\n path: ['automations', 'get'],\n description: 'Fetch a single automation with config fields.',\n resultKey: 'automation',\n options: [\n stringOption({\n inputKey: 'id',\n flagName: 'id',\n description: 'Automation ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'automationWithConfigs.graphql' },\n document: `# Query to fetch a single automation with config but excluding agents\n# Config selection is limited to scalar/JSON fields to keep responses flat\nquery GetAutomationWithConfigs($id: ID!) {\n automation(id: $id) {\n id\n name\n organizationId\n createdAt\n updatedAt\n environment\n lastSavedAt\n publishedVersionId\n draftVersionId\n config {\n cronExpression\n calendars\n interval\n enableVisualChangeChecks\n isCDPforSOM\n humanInterventionTimeoutSeconds\n availableSlots\n additionalSystemPrompt\n ignoreUnstableSessionState\n }\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAvailableCommands',\n kind: 'query',\n inputSchema: z.object({\n env: z.string().min(1),\n }),\n cli: {\n name: 'get-available-commands',\n path: ['catalog', 'commands'],\n description: 'Fetch available command definitions by environment.',\n resultKey: 'availableCommands',\n options: [\n stringOption({\n inputKey: 'env',\n flagName: 'env',\n description: 'Environment name.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'availableCommands.graphql' },\n document: `# Query to fetch available command definitions by environment\nquery GetAvailableCommands($env: AvailableCommandsEnv!) {\n availableCommands(env: $env) {\n id\n description\n inputSchema\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAvailableModels',\n kind: 'query',\n inputSchema: z.object({\n agentId: z.string().min(1),\n }),\n cli: {\n name: 'get-available-models',\n path: ['catalog', 'models'],\n description: 'Fetch available model definitions for an agent.',\n resultKey: 'availableModels',\n options: [\n stringOption({\n inputKey: 'agentId',\n flagName: 'agent-id',\n description: 'Agent ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'availableModels.graphql' },\n document: `# Query to fetch available model definitions and pools for a specific agent\nquery GetAvailableModels($agentId: String!) {\n availableModels(agentId: $agentId) {\n availableModelPools {\n name\n poolId\n models {\n id\n name\n description\n status\n provider\n }\n }\n allAvailableModels {\n id\n name\n description\n status\n provider\n }\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetAvailableTools',\n kind: 'query',\n inputSchema: z.object({\n env: z.string().min(1),\n automationId: z.string().min(1).optional(),\n }),\n cli: {\n name: 'get-available-tools',\n path: ['catalog', 'tools'],\n description: 'Fetch available tool definitions by environment.',\n resultKey: 'availableTools',\n options: [\n stringOption({\n inputKey: 'env',\n flagName: 'env',\n description: 'Environment name.',\n required: true,\n }),\n stringOption({\n inputKey: 'automationId',\n flagName: 'automation-id',\n description: 'Optional automation ID.',\n }),\n ],\n },\n mcp: { fileName: 'availableTools.graphql' },\n document: `# Query to fetch available tool definitions by environment\nquery GetAvailableTools($env: AvailableCommandsEnv!, $automationId: String) {\n availableTools(env: $env, automationId: $automationId) {\n id\n description\n inputSchema\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'CreateAutomation',\n kind: 'mutation',\n inputSchema: z.object({\n input: jsonObjectSchema,\n }),\n cli: {\n name: 'create-automation',\n path: ['automations', 'create'],\n description: 'Create a draft automation.',\n resultKey: 'createAutomation',\n options: [\n jsonOption({\n inputKey: 'input',\n flagName: 'input-json',\n description: 'CreateAutomationInput payload.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'createAutomation.graphql' },\n document: `# Mutation to create a draft automation with optional initial values\n# Returns flat fields only for MCP tool simplicity\nmutation CreateAutomation($input: CreateAutomationInput!) {\n createAutomation(input: $input) {\n id\n name\n organizationId\n createdAt\n updatedAt\n environment\n lastSavedAt\n publishedVersionId\n draftVersionId\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'GetGraphqlSchema',\n kind: 'query',\n inputSchema: z.object({}),\n cli: {\n name: 'get-graphql-schema',\n path: ['graphql', 'schema'],\n description: 'Fetch GraphQL schema metadata.',\n resultKey: 'graphqlSchema',\n options: [],\n },\n mcp: { fileName: 'graphqlSchema.graphql' },\n document: `# Query to fetch full GraphQL schema metadata.\n# Uses the first-class graphqlSchema query field to avoid __schema validation\n# issues in MCP tool-load paths while still returning introspection JSON.\n# Response can be large: call sparingly (typically once per task/session) and\n# reuse cached results.\nquery GetGraphqlSchema {\n graphqlSchema\n}`,\n }),\n createOperationSpec({\n operationName: 'PauseAutomationRun',\n kind: 'mutation',\n inputSchema: z.object({\n automationRunId: z.string().min(1),\n }),\n cli: {\n name: 'pause-automation-run',\n path: ['automation-runs', 'pause'],\n description: 'Pause an automation run.',\n resultKey: 'pauseAutomationRun',\n options: [\n stringOption({\n inputKey: 'automationRunId',\n flagName: 'automation-run-id',\n description: 'Automation run ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'pauseAutomationRun.graphql' },\n document: `# Mutation to pause an automation run\nmutation PauseAutomationRun($automationRunId: ID!) {\n pauseAutomationRun(automationRunId: $automationRunId)\n}`,\n }),\n createOperationSpec({\n operationName: 'RerunAutomation',\n kind: 'mutation',\n inputSchema: z.object({\n automationRunId: z.string().min(1),\n additionalPrompt: z.string().min(1).optional(),\n idempotencyKey: z.string().min(1),\n }),\n cli: {\n name: 'rerun-automation',\n path: ['automation-runs', 'rerun'],\n description: 'Rerun an existing automation run.',\n resultKey: 'rerunAutomation',\n options: [\n stringOption({\n inputKey: 'automationRunId',\n flagName: 'automation-run-id',\n description: 'Automation run ID.',\n required: true,\n }),\n stringOption({\n inputKey: 'additionalPrompt',\n flagName: 'additional-prompt',\n description: 'Optional prompt appended to the rerun.',\n }),\n stringOption({\n inputKey: 'idempotencyKey',\n flagName: 'idempotency-key',\n description: 'Idempotency key for the rerun request.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'rerunAutomation.graphql' },\n document: `# Mutation to rerun an existing automation run\nmutation RerunAutomation(\n $automationRunId: ID!\n $additionalPrompt: String\n $idempotencyKey: String!\n) {\n rerunAutomation(\n automationRunId: $automationRunId\n additionalPrompt: $additionalPrompt\n idempotencyKey: $idempotencyKey\n ) {\n automationRunId\n workflowId\n workflowRunId\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'ResumeAutomationRun',\n kind: 'mutation',\n inputSchema: z.object({\n automationRunId: z.string().min(1),\n message: z.string().min(1).optional(),\n }),\n cli: {\n name: 'resume-automation-run',\n path: ['automation-runs', 'resume'],\n description: 'Resume a paused automation run.',\n resultKey: 'resumeAutomationRun',\n options: [\n stringOption({\n inputKey: 'automationRunId',\n flagName: 'automation-run-id',\n description: 'Automation run ID.',\n required: true,\n }),\n stringOption({\n inputKey: 'message',\n flagName: 'message',\n description: 'Optional resume message.',\n }),\n ],\n },\n mcp: { fileName: 'resumeAutomationRun.graphql' },\n document: `# Mutation to resume an automation run\nmutation ResumeAutomationRun($automationRunId: ID!, $message: String) {\n resumeAutomationRun(automationRunId: $automationRunId, message: $message)\n}`,\n }),\n createOperationSpec({\n operationName: 'RunDraftAutomation',\n kind: 'mutation',\n inputSchema: z.object({\n draftAutomationId: z.string().min(1),\n agentId: z.string().min(1),\n idempotencyKey: z.string().min(1),\n input: z.unknown().optional(),\n additionalPrompt: z.string().min(1).optional(),\n }),\n cli: {\n name: 'run-draft-automation',\n path: ['automations', 'run-draft'],\n description: 'Run a draft automation with an explicit trigger agent.',\n resultKey: 'runDraftAutomation',\n options: [\n stringOption({\n inputKey: 'draftAutomationId',\n flagName: 'draft-automation-id',\n description: 'Draft automation ID.',\n required: true,\n }),\n stringOption({\n inputKey: 'agentId',\n flagName: 'agent-id',\n description: 'Trigger agent ID.',\n required: true,\n }),\n stringOption({\n inputKey: 'idempotencyKey',\n flagName: 'idempotency-key',\n description: 'Idempotency key for the run request.',\n required: true,\n }),\n jsonOption({\n inputKey: 'input',\n flagName: 'input-json',\n description: 'Optional JSON input payload.',\n }),\n stringOption({\n inputKey: 'additionalPrompt',\n flagName: 'additional-prompt',\n description: 'Optional prompt appended to the run.',\n }),\n ],\n },\n mcp: { fileName: 'runDraftAutomation.graphql' },\n document: `# Mutation to run a draft automation with an explicit agent.\n# \\`draftAutomationId\\` is the draft automation entity ID (\\`Automation.id\\`), not \\`draftVersionId\\`.\nmutation RunDraftAutomation(\n $draftAutomationId: ID!\n $agentId: ID!\n $idempotencyKey: String!\n $input: JSON\n $additionalPrompt: String\n) {\n runDraftAutomation(\n draftAutomationId: $draftAutomationId\n agentId: $agentId\n idempotencyKey: $idempotencyKey\n input: $input\n additionalPrompt: $additionalPrompt\n ) {\n automationRunId\n workflowId\n workflowRunId\n }\n}`,\n }),\n createOperationSpec({\n operationName: 'StopAutomationRun',\n kind: 'mutation',\n inputSchema: z.object({\n automationRunId: z.string().min(1),\n }),\n cli: {\n name: 'stop-automation-run',\n path: ['automation-runs', 'stop'],\n description: 'Stop an automation run.',\n resultKey: 'stopAutomationRun',\n options: [\n stringOption({\n inputKey: 'automationRunId',\n flagName: 'automation-run-id',\n description: 'Automation run ID.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'stopAutomationRun.graphql' },\n document: `# Mutation to stop an automation run\nmutation StopAutomationRun($automationRunId: ID!) {\n stopAutomationRun(automationRunId: $automationRunId)\n}`,\n }),\n createOperationSpec({\n operationName: 'UpdateAutomationById',\n kind: 'mutation',\n inputSchema: z.object({\n id: z.string().min(1),\n input: jsonObjectSchema,\n }),\n cli: {\n name: 'update-automation-by-id',\n path: ['automations', 'update'],\n description: 'Update an automation.',\n resultKey: 'updateAutomation',\n options: [\n stringOption({\n inputKey: 'id',\n flagName: 'id',\n description: 'Automation ID.',\n required: true,\n }),\n jsonOption({\n inputKey: 'input',\n flagName: 'input-json',\n description: 'UpdateAutomationInput payload.',\n required: true,\n }),\n ],\n },\n mcp: { fileName: 'updateAutomation.graphql' },\n document: `# Mutation to update an automation\n# Returns only id and lastSavedAt for MCP tool simplicity\nmutation UpdateAutomationById($id: ID!, $input: UpdateAutomationInput!) {\n updateAutomation(id: $id, input: $input) {\n id\n lastSavedAt\n }\n}`,\n }),\n] as const satisfies readonly OperationSpec[];\n","import type { z } from 'zod';\nimport type { OperationSpec } from './operation-types';\n\nfunction stripLeadingGraphqlComments(document: string): string {\n return document.replace(/^(?:\\s*#.*\\n)+/u, '').trimStart();\n}\n\nfunction assertDocumentMatchesOperation({\n document,\n kind,\n operationName,\n}: {\n document: string;\n kind: OperationSpec['kind'];\n operationName: string;\n}): void {\n const normalizedDocument = stripLeadingGraphqlComments(document);\n const match =\n /^(?<actualKind>query|mutation)\\s+(?<actualOperationName>[_A-Za-z][_0-9A-Za-z]*)/u.exec(\n normalizedDocument,\n );\n\n const actualKind = match?.groups?.['actualKind'];\n const actualOperationName = match?.groups?.['actualOperationName'];\n if (!actualKind || !actualOperationName) {\n throw new Error(\n `Operation \"${operationName}\" is missing a top-level GraphQL ${kind} definition.`,\n );\n }\n\n if (actualKind !== kind || actualOperationName !== operationName) {\n throw new Error(\n `Operation \"${operationName}\" does not match its GraphQL document (${actualKind} ${actualOperationName}).`,\n );\n }\n}\n\nexport function createOperationSpec<TInputSchema extends z.ZodTypeAny>(\n spec: OperationSpec<TInputSchema>,\n): OperationSpec<TInputSchema> {\n assertDocumentMatchesOperation(spec);\n return spec;\n}\n","import { operationSpecs } from '@magical/mcp-registry';\nimport type { CliOptionSpec, OperationSpec } from '@magical/mcp-registry';\nimport { Command, InvalidArgumentError, Option } from 'commander';\nimport { createMagicalApiClient } from './api';\nimport type { ApiClient } from './api';\nimport { handleAuthLogin } from './auth-login';\nimport {\n formatDefaultOrganizationSelection,\n formatExamples,\n formatHumanReadableOutput,\n formatLogoutSuccess,\n formatOrganizationList,\n formatOutputModesNote,\n} from './cli-formatting';\nimport {\n configureCommandPresentation,\n createOperationHelpExamples,\n rootOperationalGroupDescriptions,\n} from './command-presentation';\nimport { getRuntimeConfig } from './config';\nimport type { RuntimeConfig } from './config';\nimport { CliError } from './errors';\nimport { createKeytarRefreshTokenStore } from './keychain';\nimport { openExternalUrl } from './open-url';\nimport { selfUpdateInstalledCli } from './self-update';\nimport {\n createFileSettingsStore,\n resolveConfiguredApiBaseUrl,\n} from './settings';\nimport type { SettingsStore } from './settings';\nimport { createSettingsCommand } from './settings-command';\nimport { createFileStateStore } from './state';\nimport type {\n CliOrganization,\n CliState,\n RefreshTokenStore,\n StateStore,\n} from './state';\nimport { createWorkosAuthClient } from './workos-auth';\nimport type { AuthClient } from './workos-auth';\n\nexport interface CliIo {\n error: (message: string) => void;\n info: (message: string) => void;\n}\n\nexport interface CliDependencies {\n apiClient: ApiClient;\n authClient: AuthClient;\n io: CliIo;\n openExternalUrl: (url: string) => Promise<void>;\n refreshTokenStore: RefreshTokenStore;\n runtimeConfig: RuntimeConfig;\n settingsStore?: SettingsStore;\n selfUpdateCli?: () => Promise<{\n installPrefix: string;\n packageSpecifier: string;\n registryUrl: string;\n }>;\n stateStore: StateStore;\n}\n\ntype JsonCommandOptions = Record<string, unknown> & {\n json?: boolean;\n};\n\ninterface OperationalCommandOptions {\n json?: boolean;\n org?: string;\n}\n\nfunction buildCommandOptionProperty(flagName: string): string {\n const [firstSegment, ...remainingSegments] = flagName.split('-');\n return [\n firstSegment ?? '',\n ...remainingSegments.map(\n (segment) => `${segment[0]?.toUpperCase() ?? ''}${segment.slice(1)}`,\n ),\n ].join('');\n}\n\nfunction parseCommandOptionValue(\n rawValue: string,\n optionSpec: CliOptionSpec,\n): unknown {\n switch (optionSpec.valueType) {\n case 'number': {\n const parsedNumber = Number(rawValue);\n if (Number.isNaN(parsedNumber)) {\n throw new InvalidArgumentError(\n `Expected a number for --${optionSpec.flagName}.`,\n );\n }\n\n return parsedNumber;\n }\n\n case 'string-array': {\n return rawValue\n .split(',')\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n }\n\n case 'json': {\n try {\n return JSON.parse(rawValue) as unknown;\n } catch {\n throw new InvalidArgumentError(\n `Expected valid JSON for --${optionSpec.flagName}.`,\n );\n }\n }\n\n case 'boolean': {\n return rawValue;\n }\n\n case 'string': {\n return rawValue;\n }\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction resolveOrganizationBySelector({\n organizations,\n selector,\n}: {\n organizations: CliOrganization[];\n selector: string;\n}): CliOrganization {\n const matchedOrganization = organizations.find(\n (organization) =>\n organization.id === selector || organization.name === selector,\n );\n\n if (!matchedOrganization) {\n throw new CliError(`Unknown organization \"${selector}\".`);\n }\n\n return matchedOrganization;\n}\n\nfunction resolveSelectedOrganization({\n organizationSelector,\n state,\n}: {\n organizationSelector?: string;\n state: CliState;\n}): CliOrganization {\n if (organizationSelector) {\n return resolveOrganizationBySelector({\n organizations: state.organizations,\n selector: organizationSelector,\n });\n }\n\n if (!state.defaultOrgId) {\n throw new CliError(\n 'No default organization is configured. Use \"mgcl org use <org>\" or pass --org.',\n );\n }\n\n return resolveOrganizationBySelector({\n organizations: state.organizations,\n selector: state.defaultOrgId,\n });\n}\n\nfunction requireLoggedInState(state: CliState | null): CliState {\n if (!state) {\n throw new CliError('You are not logged in. Run \"mgcl auth login\" first.');\n }\n\n return state;\n}\n\nfunction writeJsonOutput(io: CliIo, value: unknown): void {\n io.info(JSON.stringify(value, null, 2));\n}\n\nfunction collectOperationVariables(\n operationSpec: OperationSpec,\n options: Record<string, unknown>,\n): Record<string, unknown> {\n const variables = Object.fromEntries(\n operationSpec.cli.options.flatMap((optionSpec: CliOptionSpec) => {\n const optionValue =\n options[buildCommandOptionProperty(optionSpec.flagName)];\n if (optionValue === undefined) {\n return [];\n }\n\n return [[optionSpec.inputKey, optionValue]];\n }),\n );\n\n const parsedVariables = operationSpec.inputSchema.safeParse(variables);\n if (!parsedVariables.success) {\n throw new CliError(\n parsedVariables.error.issues[0]?.message ?? 'Invalid command input.',\n );\n }\n\n if (!isRecord(parsedVariables.data)) {\n throw new CliError('Invalid command input.');\n }\n\n return parsedVariables.data;\n}\n\nasync function withOrgScopedAccessToken({\n dependencies,\n organizationId,\n state,\n}: {\n dependencies: CliDependencies;\n organizationId: string;\n state: CliState;\n}): Promise<{ accessToken: string }> {\n const refreshToken = await dependencies.refreshTokenStore.load(state.account);\n if (!refreshToken) {\n throw new CliError(\n 'No refresh token was found. Run \"mgcl auth login\" again.',\n );\n }\n\n const tokenResponse = await dependencies.authClient\n .refreshTokens({\n clientId: state.account.clientId,\n organizationId,\n refreshToken,\n })\n .catch((error: unknown) => {\n if (\n error instanceof CliError &&\n error.message === 'Refresh token already exchanged.'\n ) {\n throw new CliError(\n 'Refresh token already exchanged. Run \"mgcl auth login\" again.',\n { cause: error },\n );\n }\n\n throw error;\n });\n\n await dependencies.refreshTokenStore.save(\n state.account,\n tokenResponse.refresh_token,\n );\n\n return {\n accessToken: tokenResponse.access_token,\n };\n}\n\nasync function handleAuthLogout(\n dependencies: CliDependencies,\n options: JsonCommandOptions,\n): Promise<void> {\n const state = await dependencies.stateStore.load();\n if (state) {\n await dependencies.refreshTokenStore.clear(state.account);\n }\n\n await dependencies.stateStore.clear();\n\n if (options.json) {\n writeJsonOutput(dependencies.io, { loggedOut: true });\n return;\n }\n\n dependencies.io.info(formatLogoutSuccess());\n}\n\nasync function handleOrgList(\n dependencies: CliDependencies,\n options: JsonCommandOptions,\n): Promise<void> {\n const state = requireLoggedInState(await dependencies.stateStore.load());\n if (options.json) {\n writeJsonOutput(dependencies.io, state.organizations);\n return;\n }\n\n dependencies.io.info(\n formatOrganizationList({\n defaultOrgId: state.defaultOrgId,\n lastUsedOrgId: state.lastUsedOrgId,\n organizations: state.organizations,\n }),\n );\n}\n\nasync function handleOrgUse(\n dependencies: CliDependencies,\n organizationSelector: string,\n options: JsonCommandOptions,\n): Promise<void> {\n const state = requireLoggedInState(await dependencies.stateStore.load());\n const organization = resolveOrganizationBySelector({\n organizations: state.organizations,\n selector: organizationSelector,\n });\n\n const nextState: CliState = {\n ...state,\n defaultOrgId: organization.id,\n lastUsedOrgId: organization.id,\n };\n await dependencies.stateStore.save(nextState);\n\n if (options.json) {\n writeJsonOutput(dependencies.io, {\n defaultOrgId: organization.id,\n organization,\n });\n return;\n }\n\n dependencies.io.info(formatDefaultOrganizationSelection(organization));\n}\n\nasync function handleSelfUpdate(\n dependencies: CliDependencies,\n options: JsonCommandOptions,\n): Promise<void> {\n const { selfUpdateCli } = dependencies;\n if (!selfUpdateCli) {\n throw new CliError('Self-update is not configured for this CLI instance.');\n }\n\n const updateResult = await selfUpdateCli();\n\n if (options.json) {\n writeJsonOutput(dependencies.io, {\n installPrefix: updateResult.installPrefix,\n packageSpecifier: updateResult.packageSpecifier,\n registryUrl: updateResult.registryUrl,\n updated: true,\n });\n return;\n }\n\n dependencies.io.info(\n `Updated mgcl via npm (${updateResult.packageSpecifier}) in ${updateResult.installPrefix}.`,\n );\n}\n\nasync function handleOperationCommand(\n dependencies: CliDependencies,\n operationSpec: OperationSpec,\n commandOptions: Record<string, unknown> & OperationalCommandOptions,\n): Promise<void> {\n const state = requireLoggedInState(await dependencies.stateStore.load());\n const organization = resolveSelectedOrganization({\n state,\n ...(commandOptions.org ? { organizationSelector: commandOptions.org } : {}),\n });\n const variables = collectOperationVariables(operationSpec, commandOptions);\n const { accessToken } = await withOrgScopedAccessToken({\n dependencies,\n organizationId: organization.id,\n state,\n });\n\n const result = await dependencies.apiClient.executeGraphQl({\n accessToken,\n query: operationSpec.document,\n resultKey: operationSpec.cli.resultKey,\n variables,\n });\n\n await dependencies.stateStore.save({\n ...state,\n lastUsedOrgId: organization.id,\n });\n\n if (commandOptions.json) {\n writeJsonOutput(dependencies.io, result);\n return;\n }\n\n dependencies.io.info(formatHumanReadableOutput(result));\n}\n\nfunction addRegistryOperationCommand({\n program,\n commandGroups,\n dependencies,\n operationSpec,\n}: {\n program: Command;\n commandGroups: Map<string, Command>;\n dependencies: CliDependencies;\n operationSpec: OperationSpec;\n}): void {\n const commandPath = [...operationSpec.cli.path];\n const leafCommandName = commandPath.pop();\n if (!leafCommandName) {\n throw new CliError(\n `CLI path is missing a leaf command for ${operationSpec.operationName}.`,\n );\n }\n\n let parentCommand = program;\n const currentGroupPath: string[] = [];\n\n for (const groupSegment of commandPath) {\n currentGroupPath.push(groupSegment);\n const groupPathKey = currentGroupPath.join(' ');\n const existingGroup = commandGroups.get(groupPathKey);\n if (existingGroup) {\n parentCommand = existingGroup;\n continue;\n }\n\n const nextGroup = parentCommand.command(groupSegment);\n if (currentGroupPath.length === 1) {\n nextGroup.helpGroup('Operation groups:');\n }\n const rootGroupDescription =\n currentGroupPath.length === 1\n ? rootOperationalGroupDescriptions.get(groupSegment)\n : undefined;\n if (rootGroupDescription) {\n nextGroup.description(rootGroupDescription);\n }\n\n commandGroups.set(groupPathKey, nextGroup);\n parentCommand = nextGroup;\n }\n\n const command = parentCommand.command(leafCommandName);\n configureOperationalCommand(command, dependencies, operationSpec);\n const legacyAliasCommand = program.command(operationSpec.cli.name, {\n hidden: true,\n });\n configureOperationalCommand(legacyAliasCommand, dependencies, operationSpec);\n}\nfunction configureOperationalCommand(\n command: Command,\n dependencies: CliDependencies,\n operationSpec: OperationSpec,\n): void {\n command\n .description(operationSpec.cli.description)\n .addOption(\n new Option(\n '--org <org>',\n 'Organization ID or exact organization name to use.',\n ).helpGroup('Shared options:'),\n )\n .addHelpText(\n 'after',\n `\\n${formatExamples(\n 'Examples',\n createOperationHelpExamples(operationSpec),\n )}`,\n );\n\n for (const optionSpec of operationSpec.cli.options) {\n const optionFlags =\n optionSpec.valueType === 'boolean'\n ? `--${optionSpec.flagName}`\n : `--${optionSpec.flagName} <value>`;\n const optionDescription = optionSpec.valueHint\n ? `${optionSpec.description} (${optionSpec.valueHint})`\n : optionSpec.description;\n const nextOption = new Option(optionFlags, optionDescription).helpGroup(\n operationSpec.kind === 'query' ? 'Query options:' : 'Mutation options:',\n );\n\n if (optionSpec.valueType === 'boolean') {\n command.addOption(nextOption);\n continue;\n }\n\n const parser = (rawValue: string): unknown =>\n parseCommandOptionValue(rawValue, optionSpec);\n nextOption.argParser(parser);\n\n if (optionSpec.required) {\n nextOption.makeOptionMandatory(true);\n command.addOption(nextOption);\n continue;\n }\n\n command.addOption(nextOption);\n }\n\n command.action(async function (this: Command) {\n await handleOperationCommand(\n dependencies,\n operationSpec,\n this.optsWithGlobals(),\n );\n });\n}\n\nexport function createConsoleIo(): CliIo {\n return {\n error(message) {\n process.stderr.write(`${message}\\n`);\n },\n info(message) {\n process.stdout.write(`${message}\\n`);\n },\n };\n}\n\nexport function createDefaultDependencies(): CliDependencies {\n const runtimeConfig = getRuntimeConfig();\n const settingsStore = createFileSettingsStore(runtimeConfig.stateFilePath);\n const selfUpdateOptions = {\n ...(runtimeConfig.cliDistTag ? { distTag: runtimeConfig.cliDistTag } : {}),\n ...(runtimeConfig.npmRegistryUrl\n ? { registryUrl: runtimeConfig.npmRegistryUrl }\n : {}),\n };\n\n return {\n apiClient: createMagicalApiClient({\n apiBaseUrl: async () =>\n resolveConfiguredApiBaseUrl({\n defaultApiBaseUrl: runtimeConfig.magicalApiUrl,\n settings: await settingsStore.load(),\n }),\n }),\n authClient: createWorkosAuthClient({\n workosApiUrl: runtimeConfig.workosApiUrl,\n }),\n io: createConsoleIo(),\n openExternalUrl,\n refreshTokenStore: createKeytarRefreshTokenStore(\n runtimeConfig.keychainServiceName,\n ),\n runtimeConfig,\n settingsStore,\n selfUpdateCli: async () => selfUpdateInstalledCli(selfUpdateOptions),\n stateStore: createFileStateStore(runtimeConfig.stateFilePath),\n };\n}\n\nexport function buildProgram(dependencies: CliDependencies): Command {\n const program = configureCommandPresentation(\n new Command()\n .name('mgcl')\n .description('Run Magical operations from the command line.'),\n )\n .addOption(new Option('--json', 'Render JSON output.'))\n .addOption(\n new Option(\n '--update',\n 'Update mgcl to the latest published npm release.',\n ),\n )\n .showHelpAfterError()\n .showSuggestionAfterError()\n .addHelpText(\n 'after',\n `\\n${formatExamples('Quick start', [\n 'mgcl auth login',\n 'mgcl org list',\n 'mgcl automations list --limit 10',\n 'mgcl automation-runs get --id <run-id>',\n 'mgcl update',\n ])}\\n\\n${formatOutputModesNote()}`,\n );\n program.action(async function (this: Command) {\n const options = this.optsWithGlobals<\n JsonCommandOptions & {\n update?: boolean;\n }\n >();\n\n if (options.update) {\n await handleSelfUpdate(dependencies, options);\n return;\n }\n\n this.outputHelp();\n });\n\n const authCommand = configureCommandPresentation(\n new Command('auth').description('Manage CLI authentication.'),\n )\n .helpGroup('Workspace:')\n .addHelpText(\n 'after',\n `\\n${formatExamples('Examples', ['mgcl auth login', 'mgcl auth logout'])}`,\n );\n authCommand\n .command('login')\n .description('Authenticate with Magical and load organization memberships.')\n .action(async function (this: Command) {\n await handleAuthLogin(dependencies, this.optsWithGlobals());\n });\n authCommand\n .command('logout')\n .description('Remove local CLI auth state.')\n .action(async function (this: Command) {\n await handleAuthLogout(dependencies, this.optsWithGlobals());\n });\n program.addCommand(authCommand);\n\n program.addCommand(createSettingsCommand(dependencies));\n\n const orgCommand = configureCommandPresentation(\n new Command('org').description('Manage organization selection.'),\n )\n .helpGroup('Workspace:')\n .addHelpText(\n 'after',\n `\\n${formatExamples('Examples', [\n 'mgcl org list',\n 'mgcl org use <org>',\n ])}`,\n );\n orgCommand\n .command('list')\n .description('List organizations available to the saved identity.')\n .action(async function (this: Command) {\n await handleOrgList(dependencies, this.optsWithGlobals());\n });\n orgCommand\n .command('use <org>')\n .description('Set the default organization by ID or exact name.')\n .action(async function (this: Command, organizationSelector: string) {\n await handleOrgUse(\n dependencies,\n organizationSelector,\n this.optsWithGlobals(),\n );\n });\n program.addCommand(orgCommand);\n\n const updateCommand = configureCommandPresentation(\n new Command('update').description(\n 'Update mgcl to the latest published npm release.',\n ),\n )\n .helpGroup('Workspace:')\n .addHelpText(\n 'after',\n `\\n${formatExamples('Examples', ['mgcl update', 'mgcl --update'])}`,\n );\n updateCommand.action(async function (this: Command) {\n await handleSelfUpdate(dependencies, this.optsWithGlobals());\n });\n program.addCommand(updateCommand);\n\n const operationalCommandGroups = new Map<string, Command>();\n for (const operationSpec of operationSpecs) {\n addRegistryOperationCommand({\n program,\n commandGroups: operationalCommandGroups,\n dependencies,\n operationSpec,\n });\n }\n\n return program;\n}\n","import { z } from 'zod';\nimport { CliError } from './errors';\nimport type { CliOrganization } from './state';\n\nconst workosOrganizationsResponseSchema = z.object({\n organizations: z.array(\n z.object({\n id: z.string().min(1),\n name: z.string().min(1),\n primaryDomain: z.string().nullable().optional(),\n }),\n ),\n success: z.boolean(),\n});\n\nconst workosUserSchema = z.object({\n email: z.string().nullable(),\n id: z.string().min(1),\n});\n\nconst graphQlResponseSchema = z.object({\n data: z.record(z.string(), z.unknown()).optional(),\n errors: z\n .array(\n z.object({\n message: z.string().min(1),\n }),\n )\n .optional(),\n});\nconst apiErrorResponseSchema = z.object({\n errors: z\n .array(\n z.object({\n message: z.string().min(1),\n }),\n )\n .optional(),\n message: z.string().min(1).optional(),\n});\n\nfunction getApiErrorDetail(responseBody: unknown): string | null {\n const parsedResponse = apiErrorResponseSchema.safeParse(responseBody);\n if (!parsedResponse.success) {\n return null;\n }\n\n if (parsedResponse.data.message) {\n return parsedResponse.data.message;\n }\n\n if (!parsedResponse.data.errors || parsedResponse.data.errors.length === 0) {\n return null;\n }\n\n return parsedResponse.data.errors.map((error) => error.message).join('\\n');\n}\n\nexport interface ApiClient {\n executeGraphQl: (input: {\n accessToken: string;\n query: string;\n resultKey: string;\n variables: Record<string, unknown>;\n }) => Promise<unknown>;\n fetchOrganizations: (input: {\n accessToken: string;\n }) => Promise<CliOrganization[]>;\n fetchUser: (input: {\n accessToken: string;\n userId: string;\n }) => Promise<z.infer<typeof workosUserSchema>>;\n}\n\ntype ApiBaseUrlResolver = () => Promise<string> | string;\n\nfunction trimTrailingSlash(value: string): string {\n return value.replace(/\\/+$/u, '');\n}\n\nexport function createMagicalApiClient({\n apiBaseUrl,\n fetchFn = fetch,\n}: {\n apiBaseUrl: string | ApiBaseUrlResolver;\n fetchFn?: typeof fetch;\n}): ApiClient {\n const resolveApiBaseUrl: ApiBaseUrlResolver =\n typeof apiBaseUrl === 'string' ? () => apiBaseUrl : apiBaseUrl;\n\n async function fetchJson({\n accessToken,\n path,\n init,\n }: {\n accessToken: string;\n init?: RequestInit;\n path: string;\n }): Promise<unknown> {\n const url = `${trimTrailingSlash(await resolveApiBaseUrl())}${path}`;\n const headers = new Headers(init?.headers);\n headers.set('authorization', `Bearer ${accessToken}`);\n\n const response = await fetchFn(url, {\n ...init,\n headers,\n }).catch((error: unknown) => {\n throw new CliError(\n `Failed to reach Magical API at ${url}. Check your configured base URL and make sure service-main is running.`,\n { cause: error },\n );\n });\n\n const responseBody = await response.json().catch((error: unknown) => {\n if (!response.ok) {\n throw new CliError(\n `Magical API request to ${url} failed with status ${response.status}.`,\n {\n cause: error,\n },\n );\n }\n\n throw new CliError(\n `Magical API returned a non-JSON response for ${url}.`,\n {\n cause: error,\n },\n );\n });\n if (!response.ok) {\n const errorDetail = getApiErrorDetail(responseBody);\n\n throw new CliError(\n `Magical API request to ${url} failed with status ${response.status}${errorDetail ? `: ${errorDetail}` : '.'}`,\n );\n }\n\n return responseBody;\n }\n\n return {\n async executeGraphQl({\n accessToken,\n query,\n resultKey,\n variables,\n }): Promise<unknown> {\n const headers = new Headers();\n headers.set('content-type', 'application/json');\n\n const parsedResponse = graphQlResponseSchema.safeParse(\n await fetchJson({\n accessToken,\n path: '/graphql',\n init: {\n method: 'POST',\n headers,\n body: JSON.stringify({\n query,\n variables,\n }),\n },\n }),\n );\n\n if (!parsedResponse.success) {\n throw new CliError('GraphQL response payload was invalid.');\n }\n\n if (parsedResponse.data.errors && parsedResponse.data.errors.length > 0) {\n throw new CliError(\n parsedResponse.data.errors.map((error) => error.message).join('\\n'),\n );\n }\n\n return parsedResponse.data.data?.[resultKey] ?? null;\n },\n\n async fetchOrganizations({ accessToken }): Promise<CliOrganization[]> {\n const parsedResponse = workosOrganizationsResponseSchema.safeParse(\n await fetchJson({\n accessToken,\n path: '/workos/organizations',\n }),\n );\n\n if (!parsedResponse.success) {\n throw new CliError('Organization list payload was invalid.');\n }\n\n return parsedResponse.data.organizations.map((organization) => ({\n id: organization.id,\n name: organization.name,\n primaryDomain: organization.primaryDomain ?? null,\n }));\n },\n\n async fetchUser({\n accessToken,\n userId,\n }): Promise<z.infer<typeof workosUserSchema>> {\n const parsedResponse = workosUserSchema.safeParse(\n await fetchJson({\n accessToken,\n path: `/workos/user/${userId}`,\n }),\n );\n\n if (!parsedResponse.success) {\n throw new CliError('User payload was invalid.');\n }\n\n return parsedResponse.data;\n },\n };\n}\n","import os from 'node:os';\nimport path from 'node:path';\n\nexport const DEFAULT_MAGICAL_API_URL = 'https://api-agt.getmagical.io';\nexport const DEFAULT_WORKOS_API_URL = 'https://api.workos.com';\nexport const DEFAULT_WORKOS_CLIENT_ID = 'client_01JJZ6XJ1RF248P20WF63M4VAM';\nexport const DEFAULT_STAGING_WORKOS_CLIENT_ID =\n 'client_01JJZ6X26BGFBT8AC303XPQ9EQ';\nexport const DEFAULT_KEYCHAIN_SERVICE_NAME = '@getmagical/mcp-cli';\nexport const DEFAULT_CLI_DIST_TAG = 'latest';\nexport const DEFAULT_CLI_NPM_REGISTRY_URL = 'https://registry.npmjs.org/';\nexport const CLI_CONFIG_DIRECTORY_NAME = 'magical-mcp-cli';\nexport const CLI_STATE_FILE_NAME = 'state.json';\nexport const CLI_SETTINGS_FILE_NAME = 'settings.json';\n\nexport interface RuntimeConfig {\n cliDistTag?: string;\n keychainServiceName: string;\n magicalApiUrl: string;\n npmRegistryUrl?: string;\n stateFilePath: string;\n workosApiUrl: string;\n workosClientId: string;\n}\n\nfunction resolvePlatformConfigDirectory(): string {\n const customConfigDirectory = process.env['MAGICAL_CLI_CONFIG_DIR'];\n if (customConfigDirectory) {\n return customConfigDirectory;\n }\n\n if (process.platform === 'darwin') {\n return path.join(os.homedir(), 'Library', 'Application Support');\n }\n\n if (process.platform === 'win32') {\n const appDataDirectory = process.env['APPDATA'];\n return appDataDirectory ?? path.join(os.homedir(), 'AppData', 'Roaming');\n }\n\n return process.env['XDG_CONFIG_HOME'] ?? path.join(os.homedir(), '.config');\n}\n\nexport function getRuntimeConfig(): RuntimeConfig {\n const configDirectory = path.join(\n resolvePlatformConfigDirectory(),\n CLI_CONFIG_DIRECTORY_NAME,\n );\n\n return {\n cliDistTag: process.env['MAGICAL_CLI_DIST_TAG'] ?? DEFAULT_CLI_DIST_TAG,\n magicalApiUrl: DEFAULT_MAGICAL_API_URL,\n npmRegistryUrl:\n process.env['MAGICAL_CLI_NPM_REGISTRY_URL'] ??\n DEFAULT_CLI_NPM_REGISTRY_URL,\n stateFilePath: path.join(configDirectory, CLI_STATE_FILE_NAME),\n workosApiUrl: DEFAULT_WORKOS_API_URL,\n workosClientId: DEFAULT_WORKOS_CLIENT_ID,\n keychainServiceName: DEFAULT_KEYCHAIN_SERVICE_NAME,\n };\n}\n\nexport function requireWorkosClientId(config: RuntimeConfig): string {\n return config.workosClientId;\n}\n","import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport { safeJsonParse } from '@magical/common/stdlib/json.util';\nimport { isErr } from '@magical/common/stdlib/result.util';\nimport { z } from 'zod';\nimport { CLI_SETTINGS_FILE_NAME } from './config';\nimport { CliError } from './errors';\n\nexport const cliSettingsSchema = z.object({\n env: z\n .object({\n baseUrl: z.url().optional(),\n })\n .default({}),\n});\n\nexport type CliSettings = z.infer<typeof cliSettingsSchema>;\n\nexport interface SettingsStore {\n load: () => Promise<CliSettings>;\n save: (settings: CliSettings) => Promise<void>;\n}\n\nexport function createEmptyCliSettings(): CliSettings {\n return {\n env: {},\n };\n}\n\nexport function hasCliSettingsOverrides(settings: CliSettings): boolean {\n return settings.env.baseUrl !== undefined;\n}\n\nexport function resolveSettingsFilePath(stateFilePath: string): string {\n return path.join(path.dirname(stateFilePath), CLI_SETTINGS_FILE_NAME);\n}\n\nexport function resolveConfiguredApiBaseUrl({\n defaultApiBaseUrl,\n settings,\n}: {\n defaultApiBaseUrl: string;\n settings: CliSettings;\n}): string {\n return settings.env.baseUrl ?? defaultApiBaseUrl;\n}\n\nexport function shouldUseStagingWorkosClientId(settings: CliSettings): boolean {\n return settings.env.baseUrl !== undefined;\n}\n\nexport function createFileSettingsStore(stateFilePath: string): SettingsStore {\n const settingsFilePath = resolveSettingsFilePath(stateFilePath);\n\n return {\n async load() {\n const fileContents = await readFile(settingsFilePath, 'utf8').catch(\n (error: unknown) => {\n if (\n error instanceof Error &&\n 'code' in error &&\n error.code === 'ENOENT'\n ) {\n return null;\n }\n\n throw new CliError('Failed to load CLI settings.', { cause: error });\n },\n );\n if (fileContents === null) {\n return createEmptyCliSettings();\n }\n\n const parsedJson = safeJsonParse<unknown>(fileContents);\n if (isErr(parsedJson)) {\n throw new CliError('Stored CLI settings are invalid.', {\n cause: parsedJson.error.cause,\n });\n }\n\n const parsed = cliSettingsSchema.safeParse(parsedJson.value);\n if (!parsed.success) {\n throw new CliError('Stored CLI settings are invalid.', {\n cause: parsed.error,\n });\n }\n\n return parsed.data;\n },\n async save(settings) {\n if (!hasCliSettingsOverrides(settings)) {\n await rm(settingsFilePath, { force: true });\n return;\n }\n\n await mkdir(path.dirname(settingsFilePath), { recursive: true });\n await writeFile(\n settingsFilePath,\n `${JSON.stringify(settings, null, 2)}\\n`,\n );\n },\n };\n}\n\nexport function createMemorySettingsStore(\n initialSettings: CliSettings = createEmptyCliSettings(),\n): SettingsStore {\n let currentSettings = initialSettings;\n\n return {\n async load() {\n return currentSettings;\n },\n async save(settings) {\n currentSettings = settings;\n },\n };\n}\n","import {\n formatAuthLoginPrompt,\n formatAuthLoginSuccess,\n formatBrowserOpenFallback,\n} from './cli-formatting';\nimport {\n DEFAULT_STAGING_WORKOS_CLIENT_ID,\n requireWorkosClientId,\n} from './config';\nimport type { CliDependencies } from './program';\nimport {\n createEmptyCliSettings,\n shouldUseStagingWorkosClientId,\n} from './settings';\nimport type { CliState } from './state';\n\nexport type AuthLoginCommandOptions = Record<string, unknown> & {\n json?: boolean;\n};\n\nfunction writeJsonOutput(io: CliDependencies['io'], value: unknown): void {\n io.info(JSON.stringify(value, null, 2));\n}\n\nexport async function handleAuthLogin(\n dependencies: CliDependencies,\n options: AuthLoginCommandOptions,\n): Promise<void> {\n const settings =\n (await dependencies.settingsStore?.load()) ?? createEmptyCliSettings();\n const clientId = shouldUseStagingWorkosClientId(settings)\n ? DEFAULT_STAGING_WORKOS_CLIENT_ID\n : requireWorkosClientId(dependencies.runtimeConfig);\n const deviceAuthorization =\n await dependencies.authClient.startDeviceAuthorization({ clientId });\n const verificationUrl =\n deviceAuthorization.verification_uri_complete ??\n deviceAuthorization.verification_uri;\n const promptWriter = options.json\n ? dependencies.io.error\n : dependencies.io.info;\n\n promptWriter(\n formatAuthLoginPrompt({\n userCode: deviceAuthorization.user_code,\n verificationUrl,\n }),\n );\n\n await dependencies.openExternalUrl(verificationUrl).catch(() => {\n promptWriter(formatBrowserOpenFallback());\n });\n\n const tokenResponse = await dependencies.authClient.pollForDeviceTokens({\n clientId,\n deviceCode: deviceAuthorization.device_code,\n ...(deviceAuthorization.expires_in\n ? { expiresInSeconds: deviceAuthorization.expires_in }\n : {}),\n ...(deviceAuthorization.interval\n ? { intervalSeconds: deviceAuthorization.interval }\n : {}),\n });\n const accessTokenClaims = dependencies.authClient.decodeAccessTokenClaims(\n tokenResponse.access_token,\n );\n const [user, organizations] = await Promise.all([\n dependencies.apiClient.fetchUser({\n accessToken: tokenResponse.access_token,\n userId: accessTokenClaims.sub,\n }),\n dependencies.apiClient.fetchOrganizations({\n accessToken: tokenResponse.access_token,\n }),\n ]);\n\n const defaultOrgId = accessTokenClaims.org_id ?? organizations[0]?.id ?? null;\n const nextState: CliState = {\n account: {\n clientId,\n email: user.email,\n userId: user.id,\n },\n defaultOrgId,\n lastUsedOrgId: defaultOrgId,\n organizations,\n };\n\n await Promise.all([\n dependencies.refreshTokenStore.save(\n nextState.account,\n tokenResponse.refresh_token,\n ),\n dependencies.stateStore.save(nextState),\n ]);\n\n const defaultOrganization =\n organizations.find((organization) => organization.id === defaultOrgId) ??\n null;\n\n if (options.json) {\n writeJsonOutput(dependencies.io, nextState);\n return;\n }\n\n dependencies.io.info(\n formatAuthLoginSuccess({\n account: nextState.account,\n defaultOrganization,\n organizationCount: organizations.length,\n }),\n );\n}\n","import type { OperationSpec } from '@magical/mcp-registry';\nimport type { Command } from 'commander';\nimport { MagicalHelp } from './cli-formatting';\n\nexport const rootOperationalGroupDescriptions = new Map<string, string>([\n ['agents', 'Query agents.'],\n ['agent-runs', 'Query agent runs.'],\n ['automations', 'Manage automations.'],\n ['automation-runs', 'Inspect and control automation runs.'],\n ['catalog', 'Inspect available commands, models, and tools.'],\n ['graphql', 'Inspect GraphQL metadata.'],\n]);\n\nexport function configureCommandPresentation(command: Command): Command {\n const originalCreateCommand = command.createCommand.bind(command);\n command.createCommand = (name: string) =>\n configureCommandPresentation(originalCreateCommand(name));\n command.createHelp = () => new MagicalHelp();\n\n return command;\n}\n\nexport function createOperationHelpExamples(\n operationSpec: OperationSpec,\n): string[] {\n const baseCommand = `mgcl ${operationSpec.cli.path.join(' ')}`;\n const requiredOptions = operationSpec.cli.options\n .filter((optionSpec) => optionSpec.required)\n .map((optionSpec) => {\n if (optionSpec.valueType === 'boolean') {\n return `--${optionSpec.flagName}`;\n }\n\n if (optionSpec.valueType === 'number') {\n return `--${optionSpec.flagName} 10`;\n }\n\n if (optionSpec.valueType === 'json') {\n return `--${optionSpec.flagName} '{...}'`;\n }\n\n if (optionSpec.valueType === 'string-array') {\n return `--${optionSpec.flagName} value-a,value-b`;\n }\n\n return `--${optionSpec.flagName} <${optionSpec.flagName}>`;\n });\n const baseInvocation = [baseCommand, ...requiredOptions].join(' ');\n\n return [\n baseInvocation,\n `${baseInvocation} --org <org>`,\n `${baseInvocation} --json`,\n ];\n}\n","import keytar from 'keytar';\nimport type { CliAccount, RefreshTokenStore } from './state';\n\nfunction buildKeychainAccountName(account: CliAccount): string {\n return `${account.clientId}:${account.userId}`;\n}\n\nexport function createKeytarRefreshTokenStore(\n serviceName: string,\n): RefreshTokenStore {\n return {\n async clear(account) {\n await keytar.deletePassword(\n serviceName,\n buildKeychainAccountName(account),\n );\n },\n async load(account) {\n return keytar.getPassword(serviceName, buildKeychainAccountName(account));\n },\n async save(account, refreshToken) {\n await keytar.setPassword(\n serviceName,\n buildKeychainAccountName(account),\n refreshToken,\n );\n },\n };\n}\n","import { spawn } from 'node:child_process';\n\nexport async function openExternalUrl(url: string): Promise<void> {\n const command = resolveOpenCommand(url);\n\n const childProcess = spawn(command.executable, command.args, {\n detached: true,\n stdio: 'ignore',\n });\n\n await new Promise<void>((resolve, reject) => {\n childProcess.on('error', reject);\n childProcess.on('spawn', () => {\n childProcess.unref();\n resolve();\n });\n });\n}\n\nfunction resolveOpenCommand(url: string): {\n args: string[];\n executable: string;\n} {\n if (process.platform === 'darwin') {\n return { executable: 'open', args: [url] };\n }\n\n if (process.platform === 'win32') {\n return { executable: 'cmd', args: ['/c', 'start', '', url] };\n }\n\n return { executable: 'xdg-open', args: [url] };\n}\n","import { spawn } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { CliError } from './errors';\n\nexport const CLI_PACKAGE_NAME = '@getmagical/cli';\nexport const DEFAULT_CLI_DIST_TAG = 'latest';\nexport const DEFAULT_NPM_REGISTRY_URL = 'https://registry.npmjs.org/';\nexport const MANAGED_NODE_SUBPATH = 'runtime/node';\n\nexport interface SelfUpdateResult {\n installPrefix: string;\n packageSpecifier: string;\n registryUrl: string;\n}\n\ninterface NpmCommand {\n argsPrefix: string[];\n executable: string;\n}\n\nexport function resolveInstalledPackageRoot({\n entryFilePath,\n packageName,\n}: {\n entryFilePath: string;\n packageName: string;\n}): string | null {\n const packagePathSegments = packageName.split('/');\n let currentPath = path.dirname(entryFilePath);\n\n for (;;) {\n const currentPathSegments = currentPath.split(path.sep).filter(Boolean);\n const currentPackageSegments = currentPathSegments.slice(\n -packagePathSegments.length,\n );\n\n if (\n currentPackageSegments.length === packagePathSegments.length &&\n currentPackageSegments.every(\n (segment, index) => segment === packagePathSegments[index],\n )\n ) {\n return currentPath;\n }\n\n const parentPath = path.dirname(currentPath);\n if (parentPath === currentPath) {\n return null;\n }\n\n currentPath = parentPath;\n }\n}\n\nexport function resolveInstallPrefixFromPackageRoot(\n packageRootPath: string,\n): string | null {\n let currentPath = packageRootPath;\n\n for (;;) {\n if (path.basename(currentPath) === 'node_modules') {\n const nodeModulesParentPath = path.dirname(currentPath);\n if (path.basename(nodeModulesParentPath) === 'lib') {\n return path.dirname(nodeModulesParentPath);\n }\n\n return nodeModulesParentPath;\n }\n\n const parentPath = path.dirname(currentPath);\n if (parentPath === currentPath) {\n return null;\n }\n\n currentPath = parentPath;\n }\n}\n\nfunction resolveNpmCommandFromPath(): NpmCommand {\n return {\n argsPrefix: [],\n executable: process.platform === 'win32' ? 'npm.cmd' : 'npm',\n };\n}\n\nfunction resolveManagedNpmCommand(installPrefix: string): NpmCommand | null {\n if (process.platform === 'win32') {\n return null;\n }\n\n const managedNodeExecutable = path.join(\n installPrefix,\n MANAGED_NODE_SUBPATH,\n 'bin',\n 'node',\n );\n const managedNpmCli = path.join(\n installPrefix,\n MANAGED_NODE_SUBPATH,\n 'lib',\n 'node_modules',\n 'npm',\n 'bin',\n 'npm-cli.js',\n );\n\n if (!fs.existsSync(managedNodeExecutable) || !fs.existsSync(managedNpmCli)) {\n return null;\n }\n\n return {\n argsPrefix: [managedNpmCli],\n executable: managedNodeExecutable,\n };\n}\n\nexport async function installPublishedCli({\n distTag,\n installPrefix,\n packageName,\n registryUrl,\n}: {\n distTag: string;\n installPrefix: string;\n packageName: string;\n registryUrl: string;\n}): Promise<SelfUpdateResult> {\n const npmCommand =\n resolveManagedNpmCommand(installPrefix) ?? resolveNpmCommandFromPath();\n const packageSpecifier = `${packageName}@${distTag}`;\n const npmArguments = [\n ...npmCommand.argsPrefix,\n 'install',\n '--global',\n packageSpecifier,\n '--prefix',\n installPrefix,\n '--registry',\n registryUrl,\n ];\n\n await new Promise<void>((resolve, reject) => {\n const childProcess = spawn(npmCommand.executable, npmArguments, {\n stdio: 'inherit',\n });\n\n childProcess.on('error', (error: Error & { code?: string }) => {\n if (error.code === 'ENOENT') {\n reject(\n new CliError(\n 'npm is required to update mgcl. Install npm and rerun the command.',\n { cause: error },\n ),\n );\n return;\n }\n\n reject(error);\n });\n\n childProcess.on('exit', (exitCode) => {\n if (exitCode === 0) {\n resolve();\n return;\n }\n\n reject(\n new CliError(\n `npm install exited with status ${String(exitCode ?? 'unknown')}.`,\n ),\n );\n });\n });\n\n return {\n installPrefix,\n packageSpecifier,\n registryUrl,\n };\n}\n\nexport async function selfUpdateInstalledCli({\n distTag = DEFAULT_CLI_DIST_TAG,\n entryFilePath = fileURLToPath(import.meta.url),\n packageName = CLI_PACKAGE_NAME,\n registryUrl = DEFAULT_NPM_REGISTRY_URL,\n}: {\n distTag?: string;\n entryFilePath?: string;\n packageName?: string;\n registryUrl?: string;\n} = {}): Promise<SelfUpdateResult> {\n const packageRootPath = resolveInstalledPackageRoot({\n entryFilePath,\n packageName,\n });\n if (!packageRootPath) {\n throw new CliError(\n 'Self-update is only available for installed CLIs. Use the install script or \"npm install -g @getmagical/cli\".',\n );\n }\n\n const installPrefix = resolveInstallPrefixFromPackageRoot(packageRootPath);\n if (!installPrefix) {\n throw new CliError(\n 'Could not determine the installed npm prefix for this CLI. Reinstall with the install script and try again.',\n );\n }\n\n return installPublishedCli({\n distTag,\n installPrefix,\n packageName,\n registryUrl,\n });\n}\n","import { isErr } from '@magical/common/stdlib/result.util';\nimport { safeUrlConstructor } from '@magical/common/stdlib/url.utils';\nimport { Command, InvalidArgumentError, Option } from 'commander';\nimport { formatExamples } from './cli-formatting';\nimport { configureCommandPresentation } from './command-presentation';\nimport { CliError } from './errors';\nimport type { CliDependencies, CliIo } from './program';\nimport type { CliSettings, SettingsStore } from './settings';\n\ntype JsonCommandOptions = Record<string, unknown> & {\n json?: boolean;\n};\n\ntype SettingsBaseUrlCommandOptions = JsonCommandOptions & {\n reset?: boolean;\n};\n\nfunction writeJsonOutput(io: CliIo, value: unknown): void {\n io.info(JSON.stringify(value, null, 2));\n}\n\nfunction requireSettingsStore(\n settingsStore: SettingsStore | undefined,\n): SettingsStore {\n if (!settingsStore) {\n throw new CliError('CLI settings are not configured for this instance.');\n }\n\n return settingsStore;\n}\n\nfunction parseBaseUrl(value: string): string {\n const parsedUrl = safeUrlConstructor(value);\n if (isErr(parsedUrl)) {\n throw new InvalidArgumentError('Expected a valid URL for base-url.');\n }\n\n return parsedUrl.value.toString().replace(/\\/$/u, '');\n}\n\nasync function clearSavedAuth(dependencies: CliDependencies): Promise<boolean> {\n const state = await dependencies.stateStore.load();\n if (!state) {\n return false;\n }\n\n await dependencies.refreshTokenStore.clear(state.account);\n await dependencies.stateStore.clear();\n\n return true;\n}\n\nasync function handleSettingsEnvBaseUrl(\n dependencies: CliDependencies,\n rawBaseUrl: string | undefined,\n options: SettingsBaseUrlCommandOptions,\n): Promise<void> {\n if (options.reset && rawBaseUrl) {\n throw new CliError('Pass either a base URL or --reset, not both.');\n }\n\n if (!options.reset && !rawBaseUrl) {\n throw new CliError('Provide a base URL or pass --reset.');\n }\n\n const settingsStore = requireSettingsStore(dependencies.settingsStore);\n const currentSettings = await settingsStore.load();\n const { baseUrl: _baseUrl, ...remainingEnvSettings } = currentSettings.env;\n if (options.reset) {\n const nextSettings: CliSettings = {\n ...currentSettings,\n env: remainingEnvSettings,\n };\n await settingsStore.save(nextSettings);\n const authCleared = await clearSavedAuth(dependencies);\n\n if (options.json) {\n writeJsonOutput(dependencies.io, {\n authCleared,\n settings: nextSettings,\n });\n return;\n }\n\n dependencies.io.info(\n authCleared\n ? 'Cleared the persisted base-url override and removed saved auth. Run \"mgcl auth login\" again.'\n : 'Cleared the persisted base-url override.',\n );\n return;\n }\n\n const nextBaseUrl = parseBaseUrl(rawBaseUrl ?? '');\n const nextSettings: CliSettings = {\n ...currentSettings,\n env: {\n ...currentSettings.env,\n baseUrl: nextBaseUrl,\n },\n };\n await settingsStore.save(nextSettings);\n const authCleared = await clearSavedAuth(dependencies);\n\n if (options.json) {\n writeJsonOutput(dependencies.io, {\n authCleared,\n settings: nextSettings,\n });\n return;\n }\n\n dependencies.io.info(\n authCleared\n ? `Saved base-url override ${nextBaseUrl} and removed saved auth. Run \"mgcl auth login\" again.`\n : `Saved base-url override ${nextBaseUrl}.`,\n );\n}\n\nexport function createSettingsCommand(dependencies: CliDependencies): Command {\n const settingsCommand = configureCommandPresentation(\n new Command('settings').description('Manage persisted CLI settings.'),\n )\n .helpGroup('Workspace:')\n .addHelpText(\n 'after',\n `\\n${formatExamples('Examples', [\n 'mgcl settings env base-url http://main.localhost:1355',\n 'mgcl settings env base-url --reset',\n ])}`,\n );\n const settingsEnvCommand = settingsCommand\n .command('env')\n .description('Manage persisted environment overrides.');\n settingsEnvCommand\n .command('base-url [url]')\n .description('Set or clear the persisted Magical API base URL override.')\n .addOption(new Option('--reset', 'Clear the persisted base URL override.'))\n .action(async function (this: Command, baseUrl: string | undefined) {\n await handleSettingsEnvBaseUrl(\n dependencies,\n baseUrl,\n this.optsWithGlobals(),\n );\n });\n\n return settingsCommand;\n}\n","import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\n\nexport const cliAccountSchema = z.object({\n clientId: z.string().min(1),\n email: z.string().nullable(),\n userId: z.string().min(1),\n});\n\nexport const cliOrganizationSchema = z.object({\n id: z.string().min(1),\n name: z.string().min(1),\n primaryDomain: z.string().nullable().default(null),\n});\n\nexport const cliStateSchema = z.object({\n account: cliAccountSchema,\n defaultOrgId: z.string().nullable(),\n lastUsedOrgId: z.string().nullable(),\n organizations: z.array(cliOrganizationSchema),\n});\n\nexport type CliAccount = z.infer<typeof cliAccountSchema>;\nexport type CliOrganization = z.infer<typeof cliOrganizationSchema>;\nexport type CliState = z.infer<typeof cliStateSchema>;\n\nexport interface StateStore {\n clear: () => Promise<void>;\n load: () => Promise<CliState | null>;\n save: (state: CliState) => Promise<void>;\n}\n\nexport interface RefreshTokenStore {\n clear: (account: CliAccount) => Promise<void>;\n load: (account: CliAccount) => Promise<string | null>;\n save: (account: CliAccount, refreshToken: string) => Promise<void>;\n}\n\nexport function createFileStateStore(stateFilePath: string): StateStore {\n return {\n async clear() {\n await rm(stateFilePath, { force: true });\n },\n async load() {\n try {\n const fileContents = await readFile(stateFilePath, 'utf8');\n const parsed = cliStateSchema.safeParse(JSON.parse(fileContents));\n if (!parsed.success) {\n throw new CliError('Stored CLI state is invalid.');\n }\n\n return parsed.data;\n } catch (error: unknown) {\n if (\n error instanceof Error &&\n 'code' in error &&\n error.code === 'ENOENT'\n ) {\n return null;\n }\n\n if (error instanceof CliError) {\n throw error;\n }\n\n throw new CliError('Failed to load CLI state.', { cause: error });\n }\n },\n async save(state) {\n await mkdir(path.dirname(stateFilePath), { recursive: true });\n await writeFile(stateFilePath, `${JSON.stringify(state, null, 2)}\\n`);\n },\n };\n}\n\nexport function createMemoryRefreshTokenStore(): RefreshTokenStore {\n const values = new Map<string, string>();\n\n return {\n async clear(account) {\n values.delete(buildRefreshTokenKey(account));\n },\n async load(account) {\n return values.get(buildRefreshTokenKey(account)) ?? null;\n },\n async save(account, refreshToken) {\n values.set(buildRefreshTokenKey(account), refreshToken);\n },\n };\n}\n\nfunction buildRefreshTokenKey(account: CliAccount): string {\n return `${account.clientId}:${account.userId}`;\n}\n","import { z } from 'zod';\nimport { CliError } from './errors';\n\nconst DEFAULT_DEVICE_POLL_INTERVAL_SECONDS = 5;\n\nfunction buildFormHeaders(): Headers {\n const headers = new Headers();\n headers.set('content-type', 'application/x-www-form-urlencoded');\n return headers;\n}\n\nconst deviceAuthorizationSchema = z.object({\n device_code: z.string().min(1),\n expires_in: z.number().int().positive().optional(),\n interval: z.number().int().positive().optional(),\n user_code: z.string().min(1),\n verification_uri: z.url(),\n verification_uri_complete: z.url().optional(),\n});\n\nconst tokenResponseSchema = z.object({\n access_token: z.string().min(1),\n expires_in: z.number().int().positive().optional(),\n refresh_token: z.string().min(1),\n token_type: z.string().optional(),\n});\n\nconst tokenErrorSchema = z.object({\n error: z.string().min(1),\n error_description: z.string().optional(),\n});\n\nconst accessTokenClaimsSchema = z.object({\n org_id: z.string().min(1).optional(),\n sid: z.string().min(1).optional(),\n sub: z.string().min(1),\n});\n\nexport type DeviceAuthorization = z.infer<typeof deviceAuthorizationSchema>;\nexport type TokenResponse = z.infer<typeof tokenResponseSchema>;\nexport type AccessTokenClaims = z.infer<typeof accessTokenClaimsSchema>;\n\nexport interface AuthClient {\n decodeAccessTokenClaims: (accessToken: string) => AccessTokenClaims;\n pollForDeviceTokens: (input: {\n clientId: string;\n deviceCode: string;\n expiresInSeconds?: number;\n intervalSeconds?: number;\n }) => Promise<TokenResponse>;\n refreshTokens: (input: {\n clientId: string;\n organizationId?: string;\n refreshToken: string;\n }) => Promise<TokenResponse>;\n startDeviceAuthorization: (input: {\n clientId: string;\n }) => Promise<DeviceAuthorization>;\n}\n\nexport function createWorkosAuthClient({\n fetchFn = fetch,\n sleep = async (milliseconds): Promise<void> => {\n await new Promise((resolve) => {\n setTimeout(resolve, milliseconds);\n });\n },\n workosApiUrl,\n}: {\n fetchFn?: typeof fetch;\n sleep?: (milliseconds: number) => Promise<void>;\n workosApiUrl: string;\n}): AuthClient {\n async function postForm<TSchema extends z.ZodTypeAny>({\n endpointPath,\n formData,\n responseSchema,\n }: {\n endpointPath: string;\n formData: URLSearchParams;\n responseSchema: TSchema;\n }): Promise<z.infer<TSchema>> {\n const response = await fetchFn(`${workosApiUrl}${endpointPath}`, {\n method: 'POST',\n headers: buildFormHeaders(),\n body: formData,\n });\n\n const responseBody = await response.json();\n if (!response.ok) {\n const parsedError = tokenErrorSchema.safeParse(responseBody);\n if (parsedError.success) {\n throw new CliError(\n parsedError.data.error_description ?? parsedError.data.error,\n );\n }\n\n throw new CliError(\n `WorkOS request failed with status ${response.status}.`,\n );\n }\n\n const parsedResponse = responseSchema.safeParse(responseBody);\n if (!parsedResponse.success) {\n throw new CliError('WorkOS returned an unexpected response payload.');\n }\n\n return parsedResponse.data;\n }\n\n return {\n decodeAccessTokenClaims(accessToken) {\n const [, payloadSegment] = accessToken.split('.');\n if (!payloadSegment) {\n throw new CliError('WorkOS access token is malformed.');\n }\n\n const payload: unknown = JSON.parse(\n Buffer.from(payloadSegment, 'base64url').toString('utf8'),\n );\n const parsedClaims = accessTokenClaimsSchema.safeParse(payload);\n if (!parsedClaims.success) {\n throw new CliError('WorkOS access token is missing required claims.');\n }\n\n return parsedClaims.data;\n },\n\n async pollForDeviceTokens({\n clientId,\n deviceCode,\n expiresInSeconds,\n intervalSeconds,\n }): Promise<TokenResponse> {\n const timeoutAt = Date.now() + (expiresInSeconds ?? 15 * 60) * 1000;\n const initialIntervalMilliseconds =\n (intervalSeconds ?? DEFAULT_DEVICE_POLL_INTERVAL_SECONDS) * 1000;\n\n async function poll(\n nextIntervalMilliseconds: number,\n ): Promise<TokenResponse> {\n if (Date.now() >= timeoutAt) {\n throw new CliError(\n 'WorkOS device authorization expired before completion.',\n );\n }\n\n const formData = new URLSearchParams();\n formData.set('client_id', clientId);\n formData.set('device_code', deviceCode);\n formData.set(\n 'grant_type',\n 'urn:ietf:params:oauth:grant-type:device_code',\n );\n\n const response = await fetchFn(\n `${workosApiUrl}/user_management/authenticate`,\n {\n method: 'POST',\n headers: buildFormHeaders(),\n body: formData,\n },\n );\n\n const responseBody = await response.json();\n if (response.ok) {\n const parsedTokens = tokenResponseSchema.safeParse(responseBody);\n if (!parsedTokens.success) {\n throw new CliError('WorkOS returned an unexpected token response.');\n }\n\n return parsedTokens.data;\n }\n\n const parsedError = tokenErrorSchema.safeParse(responseBody);\n if (!parsedError.success) {\n throw new CliError(\n `WorkOS device authorization failed with status ${response.status}.`,\n );\n }\n\n if (parsedError.data.error === 'authorization_pending') {\n await sleep(nextIntervalMilliseconds);\n return poll(nextIntervalMilliseconds);\n }\n\n if (parsedError.data.error === 'slow_down') {\n const slowedIntervalMilliseconds = nextIntervalMilliseconds + 5000;\n await sleep(slowedIntervalMilliseconds);\n return poll(slowedIntervalMilliseconds);\n }\n\n throw new CliError(\n parsedError.data.error_description ?? parsedError.data.error,\n );\n }\n\n return poll(initialIntervalMilliseconds);\n },\n\n async refreshTokens({\n clientId,\n organizationId,\n refreshToken,\n }): Promise<TokenResponse> {\n const formData = new URLSearchParams();\n formData.set('client_id', clientId);\n formData.set('grant_type', 'refresh_token');\n formData.set('refresh_token', refreshToken);\n\n if (organizationId) {\n formData.set('organization_id', organizationId);\n }\n\n return postForm({\n endpointPath: '/user_management/authenticate',\n formData,\n responseSchema: tokenResponseSchema,\n });\n },\n\n async startDeviceAuthorization({ clientId }): Promise<DeviceAuthorization> {\n const formData = new URLSearchParams();\n formData.set('client_id', clientId);\n\n return postForm({\n endpointPath: '/user_management/authorize/device',\n formData,\n responseSchema: deviceAuthorizationSchema,\n });\n },\n };\n}\n","#!/usr/bin/env node\n\nimport { formatCliError } from './cli-formatting';\nimport { getErrorMessage } from './errors';\nimport { buildProgram, createDefaultDependencies } from './program';\n\nconst program = buildProgram(createDefaultDependencies());\n\nprogram.parseAsync(process.argv).catch((error: unknown) => {\n process.stderr.write(`${formatCliError(getErrorMessage(error))}\\n`);\n process.exitCode = 1;\n});\n"],"mappings":";;;AAAA,SAAS,SAAS,0BAA0B,iBAAiB;AAC7D,SAAS,YAAY;AAGrB,IAAM,cAAc;AACpB,IAAM,YAAY;AAGlB,SAAS,WACP,OACA,OACA,UAAU,MACF;AACR,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,UAAU,OAAO,KAAK;AAC/B;AAEA,SAAS,OAAO,MAAc,QAAQ,GAAW;AAC/C,QAAM,UAAU,IAAI,OAAO,KAAK;AAChC,SAAO,KACJ,MAAM,IAAI,EACV,IAAI,CAAC,SAAS,GAAG,OAAO,GAAG,IAAI,EAAE,EACjC,KAAK,IAAI;AACd;AAEA,SAAS,UAAU,OAAuB;AACxC,SAAO,yBAAyB,KAAK;AACvC;AAEA,SAAS,aAAa,OAAuB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ClD,UAAM,iBAAiB,cAAc,KAAK,gBAAgB,CAAC;AAAA,EAC7D,CAAC;AACD,EAAAF,SAAQ,WAAW,aAAa;AAEhC,QAAM,2BAA2B,oBAAI,IAAqB;AAC1D,aAAW,iBAAiB,gBAAgB;AAC1C,gCAA4B;AAAA,MAC1B,SAAAA;AAAA,MACA,eAAe;AAAA,MACf;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAOA;AACT;;;AYtpBA,IAAM,UAAU,aAAa,0BAA0B,CAAC;AAExD,QAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,UAAmB;AACzD,UAAQ,OAAO,MAAM,GAAG,eAAe,gBAAgB,KAAK,CAAC,CAAC;AAAA,CAAI;AAClE,UAAQ,WAAW;AACrB,CAAC;","names":["Command","InvalidArgumentError","Option","z","z","path","path","z","z","path","spawn","path","DEFAULT_CLI_DIST_TAG","path","spawn","isErr","writeJsonOutput","isErr","nextSettings","authCleared","mkdir","readFile","rm","writeFile","path","z","z","rm","readFile","mkdir","path","writeFile","z","z","InvalidArgumentError","isRecord","writeJsonOutput","program","Option","Command"]}