Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

auth.ts

56 lines1.9 KB

1/** ACP auth methods advertised by `grok agent` (see harness `initialize`). */
2export type GrokBuildAcpAuthMethod = 'xai.api_key' | 'grok.com'
3​
4/**
5 * How the harness should sign in.
6 *
7 * - `'api-key'` (default): call `authenticate` with `xai.api_key`.
8 * - `'host'`: skip ACP `authenticate`. Use `grok login` on the machine.
9 *
10 * This is not inferred from the sandbox. A local-process run can be a laptop
11 * with a login, or a runner that only has `XAI_API_KEY`.
12 */
13export type GrokBuildAuthMode = 'host' | 'api-key'
14​
15/** Isolated sandboxes have no host CLI login, so this is the default. */
16const DEFAULT_GROK_AUTH_MODE: GrokBuildAuthMode = 'api-key'
17​
18/**
19 * Pick the Grok ACP auth method for {@link startAcpSession} when using
20 * `authMode: 'api-key'`.
21 */
22export function resolveGrokAcpAuthMethod(
23 env?: Record<string, string | undefined>,
24): GrokBuildAcpAuthMethod | undefined {
25 const key =
26 env?.XAI_API_KEY ??
27 env?.GROK_API_KEY ??
28 process.env.XAI_API_KEY ??
29 process.env.GROK_API_KEY
30 return key ? 'xai.api_key' : undefined
32​
33export function resolveGrokSessionAuthMethod(
34 authMode: GrokBuildAuthMode | undefined,
35 explicitId: string | undefined,
36 env?: Record<string, string | undefined>,
37): string | undefined {
38 if (explicitId !== undefined) return explicitId
39 const mode = authMode ?? DEFAULT_GROK_AUTH_MODE
40 if (mode === 'api-key') {
41 return resolveGrokAcpAuthMethod(env) ?? 'xai.api_key'
42 }
43 return undefined
45​
46/** Prefer ACP `RequestError.data` over the generic `Internal error` message. */
47export function formatAcpRequestError(error: unknown): string {
48 if (error !== null && typeof error === 'object' && 'data' in error) {
49 const data = error.data
50 if (typeof data === 'string' && data.trim() !== '') return data.trim()
51 }
52 if (error instanceof Error && error.message.trim() !== '') {
53 return error.message
54 }
55 return 'Unknown error occurred'