zidane 6.5.3 → 6.5.4
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/acp-cli.js +2 -2
- package/dist/acp.d.ts +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/{anthropic-_Hn1YiWr.js → anthropic-qaw8XAc9.js} +2 -2
- package/dist/{anthropic-_Hn1YiWr.js.map → anthropic-qaw8XAc9.js.map} +1 -1
- package/dist/{auth-CS_e8ng1.js → auth-BLy7X1SY.js} +7 -5
- package/dist/{auth-CS_e8ng1.js.map → auth-BLy7X1SY.js.map} +1 -1
- package/dist/chat/pure.d.ts +3 -3
- package/dist/chat.d.ts +4 -4
- package/dist/chat.js +2 -2
- package/dist/contexts/daytona.d.ts +1 -1
- package/dist/contexts/e2b.d.ts +1 -1
- package/dist/cursor-iojRXHF9.js +139 -0
- package/dist/cursor-iojRXHF9.js.map +1 -0
- package/dist/eval.d.ts +1 -1
- package/dist/extensions.d.ts +1 -1
- package/dist/headless.d.ts +1 -1
- package/dist/{index-BKyWhILQ.d.ts → index-BSNr0OQn.d.ts} +19 -2
- package/dist/index-BSNr0OQn.d.ts.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -4
- package/dist/mcp.d.ts +1 -1
- package/dist/{oauth-BYjlFR-J.js → oauth-ZebH9NHb.js} +24 -4
- package/dist/oauth-ZebH9NHb.js.map +1 -0
- package/dist/output/stream-json.d.ts +1 -1
- package/dist/output/terminal.d.ts +1 -1
- package/dist/pkce-t8BcPyEi.js +30 -0
- package/dist/pkce-t8BcPyEi.js.map +1 -0
- package/dist/plugins.d.ts +1 -1
- package/dist/presets.d.ts +1 -1
- package/dist/providers/anthropic.d.ts +1 -1
- package/dist/providers/anthropic.js +1 -1
- package/dist/providers/arcee.d.ts +1 -1
- package/dist/providers/baseten.d.ts +1 -1
- package/dist/providers/cerebras.d.ts +1 -1
- package/dist/providers/local.d.ts +1 -1
- package/dist/providers/openai-compat.d.ts +1 -1
- package/dist/providers/openai.d.ts +1 -1
- package/dist/providers/openai.js +1 -1
- package/dist/providers/openrouter.d.ts +1 -1
- package/dist/providers/xai.d.ts +1 -1
- package/dist/providers/xai.js +2 -2
- package/dist/providers-Bxs-XHir.js +137 -0
- package/dist/providers-Bxs-XHir.js.map +1 -0
- package/dist/providers.d.ts +2 -2
- package/dist/providers.js +4 -4
- package/dist/restate.d.ts +1 -1
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/session.d.ts +1 -1
- package/dist/skills.d.ts +1 -1
- package/dist/{tool-formatters-DMr62Hpy.d.ts → tool-formatters-BfKqWm5N.d.ts} +2 -2
- package/dist/{tool-formatters-DMr62Hpy.d.ts.map → tool-formatters-BfKqWm5N.d.ts.map} +1 -1
- package/dist/tools/fetch-url.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tools.d.ts +1 -1
- package/dist/{transcript-anchors-uU_KZLsp.js → transcript-anchors-Bv8HQ3S2.js} +2 -2
- package/dist/{transcript-anchors-uU_KZLsp.js.map → transcript-anchors-Bv8HQ3S2.js.map} +1 -1
- package/dist/{transcript-anchors-BHihk9nf.d.ts → transcript-anchors-CNqDbrc9.d.ts} +2 -2
- package/dist/{transcript-anchors-BHihk9nf.d.ts.map → transcript-anchors-CNqDbrc9.d.ts.map} +1 -1
- package/dist/tui.d.ts +3 -3
- package/dist/tui.js +2 -2
- package/dist/{turn-operations-BgqVUjtl.d.ts → turn-operations-CnIpcenJ.d.ts} +3 -3
- package/dist/{turn-operations-BgqVUjtl.d.ts.map → turn-operations-CnIpcenJ.d.ts.map} +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/{xai-CfmI5Y5k.js → xai-DILdFGzN.js} +3 -29
- package/dist/xai-DILdFGzN.js.map +1 -0
- package/package.json +1 -1
- package/dist/index-BKyWhILQ.d.ts.map +0 -1
- package/dist/oauth-BYjlFR-J.js.map +0 -1
- package/dist/providers-VypZh7rD.js +0 -264
- package/dist/providers-VypZh7rD.js.map +0 -1
- package/dist/xai-CfmI5Y5k.js.map +0 -1
|
@@ -1,264 +0,0 @@
|
|
|
1
|
-
import { m as openaiCompat } from "./openai-compat-CnHeo4Lz.js";
|
|
2
|
-
import { s as resolveOAuthApiKey } from "./oauth-BYjlFR-J.js";
|
|
3
|
-
import { a as generatePkce } from "./xai-CfmI5Y5k.js";
|
|
4
|
-
//#region src/chat/oauth-page/cursor.ts
|
|
5
|
-
/** pi-ai / zidane OAuth provider id. Also the credentials-file key. */
|
|
6
|
-
const CURSOR_OAUTH_PROVIDER_ID = "cursor";
|
|
7
|
-
const CURSOR_LOGIN_URL = "https://cursor.com/loginDeepControl";
|
|
8
|
-
const CURSOR_POLL_URL = "https://api2.cursor.sh/auth/poll";
|
|
9
|
-
const CURSOR_REFRESH_URL = "https://api2.cursor.sh/auth/exchange_user_api_key";
|
|
10
|
-
const POLL_MAX_ATTEMPTS = 150;
|
|
11
|
-
const POLL_BASE_DELAY_MS = 1e3;
|
|
12
|
-
const POLL_MAX_DELAY_MS = 1e4;
|
|
13
|
-
const POLL_BACKOFF_MULTIPLIER = 1.2;
|
|
14
|
-
const POLL_MAX_CONSECUTIVE_ERRORS = 3;
|
|
15
|
-
/** Fallback lifetime when the JWT carries no `exp`. */
|
|
16
|
-
const DEFAULT_TOKEN_TTL_MS = 3600 * 1e3;
|
|
17
|
-
/** Refresh slightly early so requests don't race expiry. */
|
|
18
|
-
const TOKEN_EXPIRY_SKEW_MS = 300 * 1e3;
|
|
19
|
-
/**
|
|
20
|
-
* Derive expiry (epoch ms) from a JWT's `exp` claim, minus a safety skew.
|
|
21
|
-
* Returns `now + 1h` for malformed tokens so a missing claim never wedges
|
|
22
|
-
* refresh into an immediate-expire loop.
|
|
23
|
-
*/
|
|
24
|
-
function cursorTokenExpiry(token) {
|
|
25
|
-
try {
|
|
26
|
-
const parts = token.split(".");
|
|
27
|
-
const payload = parts[1];
|
|
28
|
-
if (parts.length !== 3 || !payload) return Date.now() + DEFAULT_TOKEN_TTL_MS;
|
|
29
|
-
const json = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
|
|
30
|
-
if (typeof json.exp === "number") return json.exp * 1e3 - TOKEN_EXPIRY_SKEW_MS;
|
|
31
|
-
} catch {}
|
|
32
|
-
return Date.now() + DEFAULT_TOKEN_TTL_MS;
|
|
33
|
-
}
|
|
34
|
-
function delay(ms) {
|
|
35
|
-
return new Promise((r) => setTimeout(r, ms));
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Poll Cursor's auth endpoint until login completes. `404` means the user
|
|
39
|
-
* hasn't finished the browser flow yet; anything else non-2xx is a hard error.
|
|
40
|
-
*/
|
|
41
|
-
async function pollForTokens(uuid, verifier, callbacks) {
|
|
42
|
-
let wait = POLL_BASE_DELAY_MS;
|
|
43
|
-
let consecutiveErrors = 0;
|
|
44
|
-
for (let attempt = 0; attempt < POLL_MAX_ATTEMPTS; attempt++) {
|
|
45
|
-
if (callbacks.signal?.aborted) throw new Error("Cursor login aborted");
|
|
46
|
-
await delay(wait);
|
|
47
|
-
try {
|
|
48
|
-
const url = `${CURSOR_POLL_URL}?uuid=${encodeURIComponent(uuid)}&verifier=${encodeURIComponent(verifier)}`;
|
|
49
|
-
const response = await fetch(url, { signal: callbacks.signal });
|
|
50
|
-
if (response.status === 404) {
|
|
51
|
-
consecutiveErrors = 0;
|
|
52
|
-
wait = Math.min(wait * POLL_BACKOFF_MULTIPLIER, POLL_MAX_DELAY_MS);
|
|
53
|
-
continue;
|
|
54
|
-
}
|
|
55
|
-
if (response.ok) {
|
|
56
|
-
const data = await response.json();
|
|
57
|
-
if (!data.accessToken || !data.refreshToken) throw new Error(`Cursor poll response missing tokens: ${JSON.stringify(data)}`);
|
|
58
|
-
return {
|
|
59
|
-
accessToken: data.accessToken,
|
|
60
|
-
refreshToken: data.refreshToken
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
throw new Error(`Cursor poll failed (${response.status})`);
|
|
64
|
-
} catch (err) {
|
|
65
|
-
if (callbacks.signal?.aborted) throw new Error("Cursor login aborted");
|
|
66
|
-
consecutiveErrors++;
|
|
67
|
-
if (consecutiveErrors >= POLL_MAX_CONSECUTIVE_ERRORS) throw err instanceof Error ? err : new Error(String(err));
|
|
68
|
-
callbacks.onProgress?.("Waiting for Cursor login to complete…");
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
throw new Error("Cursor authentication timed out");
|
|
72
|
-
}
|
|
73
|
-
async function loginCursor(callbacks) {
|
|
74
|
-
const { verifier, challenge } = await generatePkce();
|
|
75
|
-
const uuid = crypto.randomUUID();
|
|
76
|
-
const authUrl = new URL(CURSOR_LOGIN_URL);
|
|
77
|
-
authUrl.searchParams.set("challenge", challenge);
|
|
78
|
-
authUrl.searchParams.set("uuid", uuid);
|
|
79
|
-
authUrl.searchParams.set("mode", "login");
|
|
80
|
-
authUrl.searchParams.set("redirectTarget", "cli");
|
|
81
|
-
callbacks.onAuth({
|
|
82
|
-
url: authUrl.toString(),
|
|
83
|
-
instructions: "A browser window should open. Complete login in Cursor to finish."
|
|
84
|
-
});
|
|
85
|
-
const tokens = await pollForTokens(uuid, verifier, callbacks);
|
|
86
|
-
return {
|
|
87
|
-
access: tokens.accessToken,
|
|
88
|
-
refresh: tokens.refreshToken,
|
|
89
|
-
expires: cursorTokenExpiry(tokens.accessToken)
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
async function refreshCursorToken(credentials) {
|
|
93
|
-
const response = await fetch(CURSOR_REFRESH_URL, {
|
|
94
|
-
method: "POST",
|
|
95
|
-
headers: {
|
|
96
|
-
"Authorization": `Bearer ${credentials.refresh}`,
|
|
97
|
-
"Content-Type": "application/json"
|
|
98
|
-
},
|
|
99
|
-
body: "{}"
|
|
100
|
-
});
|
|
101
|
-
if (!response.ok) {
|
|
102
|
-
const text = await response.text().catch(() => "");
|
|
103
|
-
throw new Error(`Cursor token refresh failed (${response.status}): ${text || response.statusText}`);
|
|
104
|
-
}
|
|
105
|
-
const data = await response.json();
|
|
106
|
-
if (!data.accessToken) throw new Error(`Cursor token refresh response missing access token: ${JSON.stringify(data)}`);
|
|
107
|
-
return {
|
|
108
|
-
access: data.accessToken,
|
|
109
|
-
refresh: data.refreshToken || credentials.refresh,
|
|
110
|
-
expires: cursorTokenExpiry(data.accessToken)
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Build a Cursor `OAuthProviderInterface`. Shape matches Anthropic / Codex so
|
|
115
|
-
* it drops into `BUILTIN_PROVIDERS` and `src/auth.ts` unchanged.
|
|
116
|
-
*
|
|
117
|
-
* No `renderPage` parameter: Cursor's poll flow has no local callback server,
|
|
118
|
-
* so there is no post-redirect page to theme.
|
|
119
|
-
*/
|
|
120
|
-
function createCursorOAuthProvider() {
|
|
121
|
-
return {
|
|
122
|
-
id: CURSOR_OAUTH_PROVIDER_ID,
|
|
123
|
-
name: "Cursor",
|
|
124
|
-
usesCallbackServer: false,
|
|
125
|
-
login: loginCursor,
|
|
126
|
-
refreshToken: refreshCursorToken,
|
|
127
|
-
getApiKey: (credentials) => credentials.access
|
|
128
|
-
};
|
|
129
|
-
}
|
|
130
|
-
//#endregion
|
|
131
|
-
//#region src/providers/cursor.ts
|
|
132
|
-
const DEFAULT_MODEL = "claude-4.6-sonnet";
|
|
133
|
-
const NOT_IMPLEMENTED_MESSAGE = "Cursor OAuth login works, but inference over Cursor is not implemented yet. Cursor uses a protobuf/HTTP-2 agent protocol (not an OpenAI-compatible API), so the streaming transport still needs to be ported. Use another provider for now.";
|
|
134
|
-
function cursor(params) {
|
|
135
|
-
const defaultModel = params?.defaultModel || DEFAULT_MODEL;
|
|
136
|
-
const base = openaiCompat({
|
|
137
|
-
name: "cursor",
|
|
138
|
-
apiKey: params?.apiKey ?? "oauth",
|
|
139
|
-
baseURL: "https://api2.cursor.sh",
|
|
140
|
-
defaultModel,
|
|
141
|
-
capabilities: {
|
|
142
|
-
vision: true,
|
|
143
|
-
imageInToolResult: false
|
|
144
|
-
},
|
|
145
|
-
extraHeaders: params?.extraHeaders
|
|
146
|
-
});
|
|
147
|
-
return {
|
|
148
|
-
...base,
|
|
149
|
-
meta: {
|
|
150
|
-
...base.meta,
|
|
151
|
-
defaultModel
|
|
152
|
-
},
|
|
153
|
-
async stream(options, callbacks) {
|
|
154
|
-
await resolveOAuthApiKey({
|
|
155
|
-
provider: "cursor",
|
|
156
|
-
providerId: CURSOR_OAUTH_PROVIDER_ID,
|
|
157
|
-
params,
|
|
158
|
-
missingError: "No Cursor credentials found. Run `bun run auth --cursor` first.",
|
|
159
|
-
refreshError: (reason) => `Cursor OAuth token refresh failed. Run \`bun run auth --cursor\` again. ${reason}`
|
|
160
|
-
}, callbacks);
|
|
161
|
-
throw new Error(NOT_IMPLEMENTED_MESSAGE);
|
|
162
|
-
}
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
//#endregion
|
|
166
|
-
//#region src/providers/mistral.ts
|
|
167
|
-
const BASE_URL$1 = "https://api.mistral.ai/v1";
|
|
168
|
-
function getApiKey$1(params) {
|
|
169
|
-
if (typeof params?.apiKey === "string" && params.apiKey.length > 0) return params.apiKey;
|
|
170
|
-
if (process.env.MISTRAL_API_KEY) return process.env.MISTRAL_API_KEY;
|
|
171
|
-
throw new Error("No Mistral API key found. Pass `apiKey` or set MISTRAL_API_KEY in your environment.");
|
|
172
|
-
}
|
|
173
|
-
/**
|
|
174
|
-
* Model ids that accept `reasoning_effort`. Mistral rejects unknown request
|
|
175
|
-
* fields on some routes, so the knob is sent only for the families that
|
|
176
|
-
* document it (`mistral-small-*`, `mistral-medium-3.5` / `-2604`, and the
|
|
177
|
-
* deprecated-but-live `magistral-*`); `codestral` / `devstral` / `ministral`
|
|
178
|
-
* requests stay byte-identical to what they were without this planner.
|
|
179
|
-
*/
|
|
180
|
-
const REASONING_MODELS = /^(?:magistral-|mistral-small-|mistral-medium-(?:3\.5|2604))/;
|
|
181
|
-
/**
|
|
182
|
-
* Map zidane's thinking level to Mistral's `reasoning_effort`. Only the two
|
|
183
|
-
* documented values are emitted — `'none'` (thinking chunk omitted, `content`
|
|
184
|
-
* stays a plain string) and `'high'` (full thinking chunk). `adaptive` sends
|
|
185
|
-
* nothing so the model's own default applies.
|
|
186
|
-
*
|
|
187
|
-
* Exported for tests.
|
|
188
|
-
*/
|
|
189
|
-
function planMistralReasoning(ctx) {
|
|
190
|
-
if (!REASONING_MODELS.test(ctx.model)) return void 0;
|
|
191
|
-
if (ctx.thinking === void 0 || ctx.thinking === "adaptive") return void 0;
|
|
192
|
-
return { reasoning_effort: ctx.thinking === "off" ? "none" : "high" };
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* Mistral provider (La Plateforme).
|
|
196
|
-
*
|
|
197
|
-
* Thin wrapper around {@link openaiCompat} with Mistral-specific defaults
|
|
198
|
-
* (base URL, default model, `reasoning_effort` planner). `supportsReasoning`
|
|
199
|
-
* stays off: Mistral carries thinking inside `content` chunks rather than a
|
|
200
|
-
* `reasoning_content` field, so there is nothing to echo back upstream —
|
|
201
|
-
* thinking streams to the UI and is dropped from subsequent requests.
|
|
202
|
-
*/
|
|
203
|
-
function mistral(params) {
|
|
204
|
-
return openaiCompat({
|
|
205
|
-
name: "mistral",
|
|
206
|
-
apiKey: getApiKey$1(params),
|
|
207
|
-
baseURL: params?.baseURL || BASE_URL$1,
|
|
208
|
-
defaultModel: params?.defaultModel || "mistral-medium-latest",
|
|
209
|
-
capabilities: params?.capabilities ?? {
|
|
210
|
-
vision: true,
|
|
211
|
-
imageInToolResult: false
|
|
212
|
-
},
|
|
213
|
-
planReasoningRequest: planMistralReasoning,
|
|
214
|
-
extraHeaders: params?.extraHeaders
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
//#endregion
|
|
218
|
-
//#region src/providers/zai.ts
|
|
219
|
-
const BASE_URL = "https://api.z.ai/api/paas/v4";
|
|
220
|
-
function getApiKey(params) {
|
|
221
|
-
if (typeof params?.apiKey === "string" && params.apiKey.length > 0) return params.apiKey;
|
|
222
|
-
if (process.env.ZAI_API_KEY) return process.env.ZAI_API_KEY;
|
|
223
|
-
throw new Error("No Z.ai API key found. Pass `apiKey` or set ZAI_API_KEY in your environment.");
|
|
224
|
-
}
|
|
225
|
-
/**
|
|
226
|
-
* Map zidane's thinking level to Z.ai's `extra_body.thinking` request shape.
|
|
227
|
-
* GLM has no depth knob — thinking is a binary switch — so any non-`off`
|
|
228
|
-
* level enables it and `off` explicitly disables it (GLM-5.x/4.7 think by
|
|
229
|
-
* default, so a silent omission would not turn thinking off).
|
|
230
|
-
*
|
|
231
|
-
* Exported for tests.
|
|
232
|
-
*/
|
|
233
|
-
function planZaiReasoning(ctx) {
|
|
234
|
-
return { thinking: { type: !!ctx.thinking && ctx.thinking !== "off" ? "enabled" : "disabled" } };
|
|
235
|
-
}
|
|
236
|
-
/**
|
|
237
|
-
* Z.ai (Zhipu) GLM provider.
|
|
238
|
-
*
|
|
239
|
-
* Thin wrapper around {@link openaiCompat} pinned to the `reasoning_content`
|
|
240
|
-
* round-trip mode: thinking arrives in the `reasoning_content` delta field and
|
|
241
|
-
* is echoed back on assistant messages under the same name, keeping GLM's
|
|
242
|
-
* interleaved/preserved thinking coherent across tool calls.
|
|
243
|
-
*/
|
|
244
|
-
function zai(params) {
|
|
245
|
-
return openaiCompat({
|
|
246
|
-
name: "zai",
|
|
247
|
-
apiKey: getApiKey(params),
|
|
248
|
-
baseURL: params?.baseURL || BASE_URL,
|
|
249
|
-
defaultModel: params?.defaultModel || "glm-4.7-flash",
|
|
250
|
-
capabilities: params?.capabilities ?? {
|
|
251
|
-
vision: false,
|
|
252
|
-
imageInToolResult: false
|
|
253
|
-
},
|
|
254
|
-
supportsReasoning: true,
|
|
255
|
-
reasoningMode: "reasoning_content",
|
|
256
|
-
reasoningContentField: "reasoning_content",
|
|
257
|
-
planReasoningRequest: planZaiReasoning,
|
|
258
|
-
extraHeaders: params?.extraHeaders
|
|
259
|
-
});
|
|
260
|
-
}
|
|
261
|
-
//#endregion
|
|
262
|
-
export { cursor as a, planMistralReasoning as i, zai as n, createCursorOAuthProvider as o, mistral as r, planZaiReasoning as t };
|
|
263
|
-
|
|
264
|
-
//# sourceMappingURL=providers-VypZh7rD.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"providers-VypZh7rD.js","names":["BASE_URL","getApiKey"],"sources":["../src/chat/oauth-page/cursor.ts","../src/providers/cursor.ts","../src/providers/mistral.ts","../src/providers/zai.ts"],"sourcesContent":["/**\n * Cursor OAuth flow.\n *\n * Unlike Anthropic / OpenAI Codex (loopback-redirect PKCE), Cursor uses a\n * **poll-based** PKCE flow with no local callback server:\n *\n * 1. Generate a PKCE verifier + challenge and a random UUID.\n * 2. Open the browser to `cursor.com/loginDeepControl?challenge&uuid&mode&redirectTarget`.\n * 3. Poll `api2.cursor.sh/auth/poll?uuid&verifier` until tokens come back\n * (HTTP 404 = \"not ready yet\", keep polling with backoff).\n * 4. Refresh via `POST api2.cursor.sh/auth/exchange_user_api_key` with\n * `Authorization: Bearer <refresh>`.\n *\n * Token expiry is derived from the access token's JWT `exp` claim (minus a\n * 5-minute safety margin), falling back to +1h when the claim is missing.\n *\n * Flow adapted from https://github.com/ndraiman/pi-cursor-provider, itself\n * derived from https://github.com/ephraimduncan/opencode-cursor.\n *\n * Cursor's auth + inference protocol is unofficial and undocumented — re-verify\n * the endpoints/params below if login starts failing.\n */\n\nimport type {\n OAuthCredentials,\n OAuthLoginCallbacks,\n} from '@earendil-works/pi-ai/oauth'\nimport type { OAuthProviderInterface } from '../../providers/oauth-registry'\nimport { generatePkce } from './pkce'\n\n/** pi-ai / zidane OAuth provider id. Also the credentials-file key. */\nexport const CURSOR_OAUTH_PROVIDER_ID = 'cursor'\n\nconst CURSOR_LOGIN_URL = 'https://cursor.com/loginDeepControl'\nconst CURSOR_POLL_URL = 'https://api2.cursor.sh/auth/poll'\nconst CURSOR_REFRESH_URL = 'https://api2.cursor.sh/auth/exchange_user_api_key'\n\nconst POLL_MAX_ATTEMPTS = 150\nconst POLL_BASE_DELAY_MS = 1000\nconst POLL_MAX_DELAY_MS = 10_000\nconst POLL_BACKOFF_MULTIPLIER = 1.2\nconst POLL_MAX_CONSECUTIVE_ERRORS = 3\n\n/** Fallback lifetime when the JWT carries no `exp`. */\nconst DEFAULT_TOKEN_TTL_MS = 3600 * 1000\n/** Refresh slightly early so requests don't race expiry. */\nconst TOKEN_EXPIRY_SKEW_MS = 5 * 60 * 1000\n\ninterface CursorTokenResponse {\n accessToken: string\n refreshToken: string\n}\n\n/**\n * Derive expiry (epoch ms) from a JWT's `exp` claim, minus a safety skew.\n * Returns `now + 1h` for malformed tokens so a missing claim never wedges\n * refresh into an immediate-expire loop.\n */\nexport function cursorTokenExpiry(token: string): number {\n try {\n const parts = token.split('.')\n const payload = parts[1]\n if (parts.length !== 3 || !payload)\n return Date.now() + DEFAULT_TOKEN_TTL_MS\n\n const json = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/'))) as { exp?: unknown }\n if (typeof json.exp === 'number')\n return json.exp * 1000 - TOKEN_EXPIRY_SKEW_MS\n }\n catch {\n // fall through to default\n }\n return Date.now() + DEFAULT_TOKEN_TTL_MS\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise(r => setTimeout(r, ms))\n}\n\n/**\n * Poll Cursor's auth endpoint until login completes. `404` means the user\n * hasn't finished the browser flow yet; anything else non-2xx is a hard error.\n */\nasync function pollForTokens(\n uuid: string,\n verifier: string,\n callbacks: OAuthLoginCallbacks,\n): Promise<CursorTokenResponse> {\n let wait = POLL_BASE_DELAY_MS\n let consecutiveErrors = 0\n\n for (let attempt = 0; attempt < POLL_MAX_ATTEMPTS; attempt++) {\n if (callbacks.signal?.aborted)\n throw new Error('Cursor login aborted')\n\n await delay(wait)\n\n try {\n const url = `${CURSOR_POLL_URL}?uuid=${encodeURIComponent(uuid)}&verifier=${encodeURIComponent(verifier)}`\n const response = await fetch(url, { signal: callbacks.signal })\n\n if (response.status === 404) {\n consecutiveErrors = 0\n wait = Math.min(wait * POLL_BACKOFF_MULTIPLIER, POLL_MAX_DELAY_MS)\n continue\n }\n\n if (response.ok) {\n const data = await response.json() as Partial<CursorTokenResponse>\n if (!data.accessToken || !data.refreshToken)\n throw new Error(`Cursor poll response missing tokens: ${JSON.stringify(data)}`)\n return { accessToken: data.accessToken, refreshToken: data.refreshToken }\n }\n\n throw new Error(`Cursor poll failed (${response.status})`)\n }\n catch (err) {\n if (callbacks.signal?.aborted)\n throw new Error('Cursor login aborted')\n consecutiveErrors++\n if (consecutiveErrors >= POLL_MAX_CONSECUTIVE_ERRORS)\n throw err instanceof Error ? err : new Error(String(err))\n callbacks.onProgress?.('Waiting for Cursor login to complete…')\n }\n }\n\n throw new Error('Cursor authentication timed out')\n}\n\nexport async function loginCursor(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n const { verifier, challenge } = await generatePkce()\n const uuid = crypto.randomUUID()\n\n const authUrl = new URL(CURSOR_LOGIN_URL)\n authUrl.searchParams.set('challenge', challenge)\n authUrl.searchParams.set('uuid', uuid)\n authUrl.searchParams.set('mode', 'login')\n authUrl.searchParams.set('redirectTarget', 'cli')\n\n callbacks.onAuth({\n url: authUrl.toString(),\n instructions: 'A browser window should open. Complete login in Cursor to finish.',\n })\n\n const tokens = await pollForTokens(uuid, verifier, callbacks)\n\n return {\n access: tokens.accessToken,\n refresh: tokens.refreshToken,\n expires: cursorTokenExpiry(tokens.accessToken),\n }\n}\n\nexport async function refreshCursorToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n const response = await fetch(CURSOR_REFRESH_URL, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${credentials.refresh}`,\n 'Content-Type': 'application/json',\n },\n body: '{}',\n })\n\n if (!response.ok) {\n const text = await response.text().catch(() => '')\n throw new Error(`Cursor token refresh failed (${response.status}): ${text || response.statusText}`)\n }\n\n const data = await response.json() as Partial<CursorTokenResponse>\n if (!data.accessToken)\n throw new Error(`Cursor token refresh response missing access token: ${JSON.stringify(data)}`)\n\n return {\n access: data.accessToken,\n // Cursor may omit a rotated refresh token — keep the existing one.\n refresh: data.refreshToken || credentials.refresh,\n expires: cursorTokenExpiry(data.accessToken),\n }\n}\n\n/**\n * Build a Cursor `OAuthProviderInterface`. Shape matches Anthropic / Codex so\n * it drops into `BUILTIN_PROVIDERS` and `src/auth.ts` unchanged.\n *\n * No `renderPage` parameter: Cursor's poll flow has no local callback server,\n * so there is no post-redirect page to theme.\n */\nexport function createCursorOAuthProvider(): OAuthProviderInterface {\n return {\n id: CURSOR_OAUTH_PROVIDER_ID,\n name: 'Cursor',\n usesCallbackServer: false,\n login: loginCursor,\n refreshToken: refreshCursorToken,\n getApiKey: credentials => credentials.access,\n }\n}\n","import type { Provider, StreamCallbacks } from '.'\nimport { CURSOR_OAUTH_PROVIDER_ID } from '../chat/oauth-page/cursor'\nimport { resolveOAuthApiKey } from './oauth'\nimport { openaiCompat } from './openai-compat'\n\n/**\n * Cursor provider (OAuth).\n *\n * Auth is fully wired: `bun run auth --cursor` (or the TUI wizard) logs in via\n * Cursor's poll-based PKCE flow and persists credentials; this provider resolves\n * + refreshes the OAuth token on every turn via {@link resolveOAuthApiKey}.\n *\n * Inference is **not** wired yet. Cursor does not expose an OpenAI-compatible\n * HTTP endpoint — it speaks a protobuf/Connect agent protocol over HTTP/2 to\n * `api2.cursor.sh`. Implementing `stream()` requires porting that transport\n * (generated protobuf schemas + an HTTP/2 streaming client) in-process, which\n * is intentionally left as a follow-up. Until then `stream()` resolves the\n * token (proving auth works) and then throws a clear, actionable error.\n *\n * The `openaiCompat` base supplies the message-format helpers (`formatTools`,\n * `userMessage`, `toolResultsMessage`, …) so the provider satisfies the full\n * `Provider` contract and slots into the registry; only `stream` is overridden.\n */\nexport interface CursorParams {\n /** Bypass OAuth resolution with an explicit token (mainly for tests). */\n apiKey?: string\n defaultModel?: string\n /**\n * Extra HTTP headers for the eventual Cursor transport. Accepted for API\n * parity with the other providers and forwarded to the openai-compat base,\n * but inert until Cursor inference is implemented (the `stream` override\n * currently throws before any request is made).\n */\n extraHeaders?: Record<string, string>\n}\n\nconst DEFAULT_MODEL = 'claude-4.6-sonnet'\n\nconst NOT_IMPLEMENTED_MESSAGE\n = 'Cursor OAuth login works, but inference over Cursor is not implemented yet. '\n + 'Cursor uses a protobuf/HTTP-2 agent protocol (not an OpenAI-compatible API), '\n + 'so the streaming transport still needs to be ported. Use another provider for now.'\n\nexport function cursor(params?: CursorParams): Provider {\n const defaultModel = params?.defaultModel || DEFAULT_MODEL\n\n // Base only provides the format/serialization methods; `baseURL` is never\n // hit because we override `stream` below.\n const base = openaiCompat({\n name: 'cursor',\n apiKey: params?.apiKey ?? 'oauth',\n baseURL: 'https://api2.cursor.sh',\n defaultModel,\n capabilities: { vision: true, imageInToolResult: false },\n extraHeaders: params?.extraHeaders,\n })\n\n return {\n ...base,\n meta: { ...base.meta, defaultModel },\n async stream(options, callbacks: StreamCallbacks) {\n // Resolve (and lazily refresh) the OAuth token so auth failures surface\n // here with the right remediation, distinct from the not-implemented path.\n await resolveOAuthApiKey(\n {\n provider: 'cursor',\n providerId: CURSOR_OAUTH_PROVIDER_ID,\n params,\n missingError: 'No Cursor credentials found. Run `bun run auth --cursor` first.',\n refreshError: reason => `Cursor OAuth token refresh failed. Run \\`bun run auth --cursor\\` again. ${reason}`,\n },\n callbacks,\n )\n void options\n throw new Error(NOT_IMPLEMENTED_MESSAGE)\n },\n }\n}\n","import type { Provider, ProviderCapabilities } from '.'\nimport type { ThinkingLevel } from '../types'\nimport { openaiCompat } from './openai-compat'\n\n// Mistral La Plateforme — OpenAI-compatible `/v1/chat/completions`. Model ids\n// are plain slugs (`mistral-medium-latest`, `devstral-2512`, …). Reasoning is\n// NOT a separate wire field here: with `reasoning_effort: 'high'` the response\n// `content` becomes a list of `thinking` / `text` chunks (handled by\n// `openaiCompat`'s content-chunk path), and with `'none'` it stays a plain\n// string. See https://docs.mistral.ai/studio-api/conversations/reasoning.\nconst BASE_URL = 'https://api.mistral.ai/v1'\n\nexport interface MistralParams {\n apiKey?: string\n defaultModel?: string\n /**\n * Override the base URL — e.g. point at a regional endpoint or a gateway in\n * front of La Plateforme.\n */\n baseURL?: string\n /**\n * Provider capability flags. The `mistral-medium` / `mistral-large` /\n * `pixtral` families accept `image_url` parts — default:\n * `{ vision: true, imageInToolResult: false }`. Set `vision: false` when\n * pinning a text-only model (`codestral`, `devstral`, `ministral`).\n */\n capabilities?: ProviderCapabilities\n /**\n * Extra HTTP headers sent on every request. Forwarded to the underlying\n * {@link openaiCompat} client.\n */\n extraHeaders?: Record<string, string>\n}\n\nfunction getApiKey(params?: MistralParams): string {\n // Resolution order aligned with the other providers: explicit > env > fail.\n if (typeof params?.apiKey === 'string' && params.apiKey.length > 0)\n return params.apiKey\n\n if (process.env.MISTRAL_API_KEY)\n return process.env.MISTRAL_API_KEY\n\n throw new Error('No Mistral API key found. Pass `apiKey` or set MISTRAL_API_KEY in your environment.')\n}\n\n/**\n * Model ids that accept `reasoning_effort`. Mistral rejects unknown request\n * fields on some routes, so the knob is sent only for the families that\n * document it (`mistral-small-*`, `mistral-medium-3.5` / `-2604`, and the\n * deprecated-but-live `magistral-*`); `codestral` / `devstral` / `ministral`\n * requests stay byte-identical to what they were without this planner.\n */\nconst REASONING_MODELS = /^(?:magistral-|mistral-small-|mistral-medium-(?:3\\.5|2604))/\n\n/**\n * Map zidane's thinking level to Mistral's `reasoning_effort`. Only the two\n * documented values are emitted — `'none'` (thinking chunk omitted, `content`\n * stays a plain string) and `'high'` (full thinking chunk). `adaptive` sends\n * nothing so the model's own default applies.\n *\n * Exported for tests.\n */\nexport function planMistralReasoning(\n ctx: { model: string, thinking?: ThinkingLevel },\n): Record<string, unknown> | undefined {\n if (!REASONING_MODELS.test(ctx.model))\n return undefined\n if (ctx.thinking === undefined || ctx.thinking === 'adaptive')\n return undefined\n return { reasoning_effort: ctx.thinking === 'off' ? 'none' : 'high' }\n}\n\n/**\n * Mistral provider (La Plateforme).\n *\n * Thin wrapper around {@link openaiCompat} with Mistral-specific defaults\n * (base URL, default model, `reasoning_effort` planner). `supportsReasoning`\n * stays off: Mistral carries thinking inside `content` chunks rather than a\n * `reasoning_content` field, so there is nothing to echo back upstream —\n * thinking streams to the UI and is dropped from subsequent requests.\n */\nexport function mistral(params?: MistralParams): Provider {\n return openaiCompat({\n name: 'mistral',\n apiKey: getApiKey(params),\n baseURL: params?.baseURL || BASE_URL,\n defaultModel: params?.defaultModel || 'mistral-medium-latest',\n capabilities: params?.capabilities ?? { vision: true, imageInToolResult: false },\n planReasoningRequest: planMistralReasoning,\n extraHeaders: params?.extraHeaders,\n })\n}\n","import type { Provider, ProviderCapabilities } from '.'\nimport type { ThinkingLevel } from '../types'\nimport { openaiCompat } from './openai-compat'\n\n// Z.ai (Zhipu) GLM Open Platform — OpenAI-compatible endpoint. Model ids are\n// plain lowercase slugs (`glm-4.7`, `glm-4.7-flash`, …), reasoning streams in\n// the `reasoning_content` delta field, and thinking is toggled via an\n// `extra_body.thinking` object rather than a `reasoning_effort` string.\n// See https://docs.z.ai/guides/develop/http/introduction and\n// https://docs.z.ai/guides/capabilities/thinking-mode.\nconst BASE_URL = 'https://api.z.ai/api/paas/v4'\n\nexport interface ZaiParams {\n apiKey?: string\n defaultModel?: string\n /**\n * Override the base URL — e.g. point at the dedicated Coding Plan endpoint\n * instead of the standard API endpoint.\n */\n baseURL?: string\n /**\n * Provider capability flags. GLM text models are text-only — default:\n * `{ vision: false, imageInToolResult: false }`.\n */\n capabilities?: ProviderCapabilities\n /**\n * Extra HTTP headers sent on every request. Forwarded to the underlying\n * {@link openaiCompat} client.\n */\n extraHeaders?: Record<string, string>\n}\n\nfunction getApiKey(params?: ZaiParams): string {\n // Resolution order aligned with the other providers: explicit > env > fail.\n if (typeof params?.apiKey === 'string' && params.apiKey.length > 0)\n return params.apiKey\n\n if (process.env.ZAI_API_KEY)\n return process.env.ZAI_API_KEY\n\n throw new Error('No Z.ai API key found. Pass `apiKey` or set ZAI_API_KEY in your environment.')\n}\n\n/**\n * Map zidane's thinking level to Z.ai's `extra_body.thinking` request shape.\n * GLM has no depth knob — thinking is a binary switch — so any non-`off`\n * level enables it and `off` explicitly disables it (GLM-5.x/4.7 think by\n * default, so a silent omission would not turn thinking off).\n *\n * Exported for tests.\n */\nexport function planZaiReasoning(\n ctx: { thinking?: ThinkingLevel },\n): Record<string, unknown> {\n const enabled = !!ctx.thinking && ctx.thinking !== 'off'\n return { thinking: { type: enabled ? 'enabled' : 'disabled' } }\n}\n\n/**\n * Z.ai (Zhipu) GLM provider.\n *\n * Thin wrapper around {@link openaiCompat} pinned to the `reasoning_content`\n * round-trip mode: thinking arrives in the `reasoning_content` delta field and\n * is echoed back on assistant messages under the same name, keeping GLM's\n * interleaved/preserved thinking coherent across tool calls.\n */\nexport function zai(params?: ZaiParams): Provider {\n return openaiCompat({\n name: 'zai',\n apiKey: getApiKey(params),\n baseURL: params?.baseURL || BASE_URL,\n defaultModel: params?.defaultModel || 'glm-4.7-flash',\n capabilities: params?.capabilities ?? { vision: false, imageInToolResult: false },\n supportsReasoning: true,\n reasoningMode: 'reasoning_content',\n reasoningContentField: 'reasoning_content',\n planReasoningRequest: planZaiReasoning,\n extraHeaders: params?.extraHeaders,\n })\n}\n"],"mappings":";;;;;AA+BA,MAAa,2BAA2B;AAExC,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAE3B,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAChC,MAAM,8BAA8B;;AAGpC,MAAM,uBAAuB,OAAO;;AAEpC,MAAM,uBAAuB,MAAS;;;;;;AAYtC,SAAgB,kBAAkB,OAAuB;CACvD,IAAI;EACF,MAAM,QAAQ,MAAM,MAAM,GAAG;EAC7B,MAAM,UAAU,MAAM;EACtB,IAAI,MAAM,WAAW,KAAK,CAAC,SACzB,OAA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AsB;EACtB,cAAc,QAAQ;CACxB,CAAC;AACH;;;ACjFA,MAAM,WAAW;AAsBjB,SAAS,UAAU,QAA4B;CAE7C,IAAI,OAAO,QAAQ,WAAW,YAAY,OAAO,OAAO,SAAS,GAC/D,OAAO,OAAO;CAEhB,IAAI,QAAQ,IAAI,aACd,OAAO,QAAQ,IAAI;CAErB,MAAM,IAAI,MAAM,8EAA8E;AAChG;;;;;;;;;AAUA,SAAgB,iBACd,KACyB;CAEzB,OAAO,EAAE,UAAU,EAAE,MADL,CAAC,CAAC,IAAI,YAAY,IAAI,aAAa,QACd,YAAY,WAAW,EAAE;AAChE;;;;;;;;;AAUA,SAAgB,IAAI,QAA8B;CAChD,OAAO,aAAa;EAClB,MAAM;EACN,QAAQ,UAAU,MAAM;EACxB,SAAS,QAAQ,WAAW;EAC5B,cAAc,QAAQ,gBAAgB;EACtC,cAAc,QAAQ,gBAAgB;GAAE,QAAQ;GAAO,mBAAmB;EAAM;EAChF,mBAAmB;EACnB,eAAe;EACf,uBAAuB;EACvB,sBAAsB;EACtB,cAAc,QAAQ;CACxB,CAAC;AACH"}
|
package/dist/xai-CfmI5Y5k.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"xai-CfmI5Y5k.js","names":[],"sources":["../src/chat/oauth-page/pkce.ts","../src/chat/oauth-page/xai.ts"],"sourcesContent":["/**\n * PKCE helper. Inlined here (rather than imported from pi-ai) because\n * `@earendil-works/pi-ai/oauth` does not re-export it, and we don't want\n * to reach into `node_modules/.../utils/oauth/pkce.js` — that's an\n * implementation-detail path that breaks on minor upstream rearrangements.\n *\n * Web Crypto API only. Works under Bun + Node 22+ without any node:crypto\n * import (matches pi-ai's own behavior). Output is base64url per RFC 7636.\n */\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let binary = ''\n for (const byte of bytes)\n binary += String.fromCharCode(byte)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '')\n}\n\nexport interface PkcePair {\n /** Random verifier used in the token-exchange step. */\n verifier: string\n /** SHA-256(verifier) sent on the authorize URL. */\n challenge: string\n}\n\nexport async function generatePkce(): Promise<PkcePair> {\n const verifierBytes = new Uint8Array(32)\n crypto.getRandomValues(verifierBytes)\n const verifier = base64UrlEncode(verifierBytes)\n\n const data = new TextEncoder().encode(verifier)\n const hashBuffer = await crypto.subtle.digest('SHA-256', data)\n const challenge = base64UrlEncode(new Uint8Array(hashBuffer))\n\n return { verifier, challenge }\n}\n","/**\n * xAI Grok OAuth flow (SuperGrok / X Premium+).\n *\n * xAI is **not** built into pi-ai, so — like Cursor — we implement the flow\n * here and register it with pi-ai's OAuth registry (`registerXaiOAuthProvider`)\n * so `getOAuthApiKey('xai-oauth', …)` resolves to it during lazy token refresh.\n *\n * Auth shape: OAuth 2.0 + PKCE with a loopback callback server, against xAI's\n * OIDC issuer (`https://auth.x.ai`). Differs from the Anthropic / Codex flows\n * (which use the shared `startCallbackServer`) on three points, so it gets its\n * own login impl rather than reusing that primitive:\n *\n * 1. The `redirect_uri` must be `http://127.0.0.1:56121/callback` verbatim\n * (xAI matches the registered loopback IP, not `localhost`).\n * 2. Endpoints come from OIDC discovery, not hard-coded constants.\n * 3. Token exchange + refresh are `application/x-www-form-urlencoded`\n * (the Anthropic flow posts JSON).\n *\n * The callback page still routes through {@link OAuthCallbackPageRenderer} so\n * the post-redirect HTML matches the rest of zidane's themed flows.\n *\n * Flow + constants adapted from the public reference implementations\n * (`stnly/pi-grok`, `BlockedPath/pi-xai-oauth`) and the Hermes Agent docs.\n * xAI's OAuth surface is unofficial/undocumented — re-verify the client id,\n * scopes, and callback port if login starts failing.\n */\n\nimport type {\n OAuthCredentials,\n OAuthLoginCallbacks,\n} from '@earendil-works/pi-ai/oauth'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { OAuthProviderInterface } from '../../providers/oauth-registry'\nimport type { OAuthCallbackPageRenderer } from './render'\nimport { createServer } from 'node:http'\nimport { generatePkce } from './pkce'\n\n/** pi-ai / zidane OAuth provider id. Also the credentials-file key. */\nexport const XAI_OAUTH_PROVIDER_ID = 'xai-oauth'\n\nconst DEFAULT_BASE_URL = 'https://api.x.ai/v1'\nconst ISSUER = 'https://auth.x.ai'\nconst DISCOVERY_URL = `${ISSUER}/.well-known/openid-configuration`\n/** Public client id used by the Grok CLI OAuth surface. */\nconst DEFAULT_CLIENT_ID = 'b1a00492-073a-47ea-816f-4c329264a828'\nconst DEFAULT_SCOPE = 'openid profile email offline_access grok-cli:access api:access'\n/** xAI matches the registered loopback IP exactly — `localhost` is rejected. */\nconst DEFAULT_CALLBACK_HOST = '127.0.0.1'\nconst DEFAULT_CALLBACK_PORT = 56121\nconst CALLBACK_PATH = '/callback'\nconst PROVIDER_NAME = 'xAI Grok'\n/** Refresh slightly early so requests don't race expiry. */\nconst REFRESH_SKEW_MS = 120_000\nconst CALLBACK_TIMEOUT_MS = 180_000\n\nfunction xaiOAuthClientId(): string {\n return process.env.PI_XAI_OAUTH_CLIENT_ID || DEFAULT_CLIENT_ID\n}\n\nfunction xaiOAuthScope(): string {\n return process.env.PI_XAI_OAUTH_SCOPE || DEFAULT_SCOPE\n}\n\nfunction xaiOAuthCallbackHost(): string {\n return process.env.PI_XAI_OAUTH_CALLBACK_HOST || DEFAULT_CALLBACK_HOST\n}\n\nfunction xaiOAuthCallbackPort(): number {\n const parsed = Number.parseInt(process.env.PI_XAI_OAUTH_CALLBACK_PORT || String(DEFAULT_CALLBACK_PORT), 10)\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_CALLBACK_PORT\n}\n\n/** Resolve the xAI API base URL (env override → default). */\nexport function xaiBaseUrl(): string {\n return (process.env.PI_XAI_BASE_URL || process.env.XAI_BASE_URL || DEFAULT_BASE_URL)\n .replace(/\\/+$/, '')\n}\n\ninterface XaiDiscovery {\n authorization_endpoint: string\n token_endpoint: string\n}\n\n/**\n * xAI OAuth credentials. Extends the base `{ access, refresh, expires }` with\n * the resolved `token_endpoint` so refresh doesn't need a second discovery\n * round-trip, plus the cached discovery doc for validation.\n */\nexport interface XaiOAuthCredentials extends OAuthCredentials {\n tokenEndpoint?: string\n discovery?: XaiDiscovery\n}\n\nfunction base64Url(bytes: Uint8Array): string {\n let binary = ''\n for (const b of bytes)\n binary += String.fromCharCode(b)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nfunction randomToken(byteLength = 16): string {\n return base64Url(crypto.getRandomValues(new Uint8Array(byteLength)))\n}\n\n/**\n * Refuse any OIDC endpoint that isn't HTTPS on an xAI origin.\n *\n * The discovery doc is cached long-term in `credentials.json`. A single MITM\n * during initial login could otherwise pin a malicious `token_endpoint` that\n * receives every subsequent refresh token. Validating scheme + host keeps the\n * endpoint on `x.ai` / `*.x.ai`.\n */\nfunction validateEndpoint(value: string, field: string): string {\n let url: URL\n try {\n url = new URL(value)\n }\n catch {\n throw new Error(`xAI OAuth discovery returned an invalid ${field}: ${value}`)\n }\n if (url.protocol !== 'https:')\n throw new Error(`xAI OAuth ${field} must use HTTPS: ${value}`)\n const host = url.hostname.toLowerCase()\n if (host !== 'x.ai' && !host.endsWith('.x.ai'))\n throw new Error(`Refusing non-xAI OAuth ${field}: ${value}`)\n return url.toString()\n}\n\nasync function discover(): Promise<XaiDiscovery> {\n let response: Response\n try {\n response = await fetch(DISCOVERY_URL, {\n headers: { Accept: 'application/json' },\n signal: AbortSignal.timeout(15_000),\n })\n }\n catch (cause) {\n throw new Error(`xAI OIDC discovery failed: ${cause instanceof Error ? cause.message : String(cause)}`)\n }\n if (!response.ok)\n throw new Error(`xAI OIDC discovery returned ${response.status}`)\n\n const payload = await response.json() as Record<string, unknown>\n return {\n authorization_endpoint: validateEndpoint(String(payload.authorization_endpoint ?? ''), 'authorization_endpoint'),\n token_endpoint: validateEndpoint(String(payload.token_endpoint ?? ''), 'token_endpoint'),\n }\n}\n\ninterface CallbackResult {\n code?: string\n state?: string\n error?: string\n errorDescription?: string\n}\n\ninterface XaiCallbackServer {\n redirectUri: string\n waitForCallback: (timeoutMs: number) => Promise<CallbackResult>\n close: () => void\n}\n\n/**\n * Start the loopback callback server on `127.0.0.1:56121`. Falls back to an\n * OS-assigned port if 56121 is taken — xAI accepts any loopback port as long\n * as the `redirect_uri` we send on the authorize URL matches the listener.\n */\nasync function startXaiCallbackServer(renderPage: OAuthCallbackPageRenderer): Promise<XaiCallbackServer> {\n const callbackHost = xaiOAuthCallbackHost()\n const callbackPort = xaiOAuthCallbackPort()\n let settle: ((value: CallbackResult) => void) | undefined\n let settled = false\n const callbackPromise = new Promise<CallbackResult>((resolve) => {\n settle = (value) => {\n if (settled)\n return\n settled = true\n resolve(value)\n }\n })\n\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n try {\n // accounts.x.ai may issue a CORS preflight against the loopback listener.\n const origin = req.headers.origin\n if (origin === 'https://accounts.x.ai' || origin === 'https://auth.x.ai') {\n res.setHeader('Access-Control-Allow-Origin', origin)\n res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS')\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type')\n res.setHeader('Access-Control-Allow-Private-Network', 'true')\n res.setHeader('Vary', 'Origin')\n }\n if (req.method === 'OPTIONS') {\n res.statusCode = 204\n res.end()\n return\n }\n\n const url = new URL(req.url ?? '/', `http://${callbackHost}`)\n if (url.pathname !== CALLBACK_PATH) {\n res.statusCode = 404\n res.end('Not found')\n return\n }\n\n const result: CallbackResult = {\n code: url.searchParams.get('code') ?? undefined,\n state: url.searchParams.get('state') ?? undefined,\n error: url.searchParams.get('error') ?? undefined,\n errorDescription: url.searchParams.get('error_description') ?? undefined,\n }\n\n res.statusCode = result.error ? 400 : 200\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.end(renderPage(result.error\n ? {\n kind: 'error',\n provider: PROVIDER_NAME,\n message: `${PROVIDER_NAME} authentication did not complete.`,\n details: result.errorDescription ?? result.error,\n }\n : {\n kind: 'success',\n provider: PROVIDER_NAME,\n message: 'xAI authentication completed. You can close this window.',\n }))\n settle?.(result)\n }\n catch {\n res.statusCode = 500\n res.end('Internal error')\n }\n })\n\n const listen = (port: number) => new Promise<number>((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, callbackHost, () => {\n server.removeListener('error', reject)\n const addr = server.address()\n resolve(typeof addr === 'object' && addr ? addr.port : port)\n })\n })\n\n let actualPort: number\n try {\n actualPort = await listen(callbackPort)\n }\n catch {\n actualPort = await listen(0)\n }\n\n return {\n redirectUri: `http://${callbackHost}:${actualPort}${CALLBACK_PATH}`,\n waitForCallback: timeoutMs => Promise.race([\n callbackPromise,\n new Promise<CallbackResult>(resolve =>\n setTimeout(\n resolve,\n timeoutMs,\n { error: 'timeout', errorDescription: 'Timed out waiting for the xAI OAuth callback.' },\n )),\n ]),\n close: () => {\n try { server.close() }\n catch { /* already closed */ }\n },\n }\n}\n\nfunction expiryFromPayload(payload: Record<string, unknown>): number {\n const expiresIn = typeof payload.expires_in === 'number'\n ? payload.expires_in\n : Number(payload.expires_in ?? 3600)\n return Date.now() + expiresIn * 1000 - REFRESH_SKEW_MS\n}\n\nasync function exchangeCode(\n tokenEndpoint: string,\n code: string,\n redirectUri: string,\n verifier: string,\n discovery: XaiDiscovery,\n): Promise<XaiOAuthCredentials> {\n const clientId = xaiOAuthClientId()\n const response = await fetch(tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: clientId,\n code,\n redirect_uri: redirectUri,\n code_verifier: verifier,\n }),\n signal: AbortSignal.timeout(30_000),\n })\n if (!response.ok)\n throw new Error(`xAI token exchange failed: ${response.status} ${await response.text().catch(() => '')}`)\n\n const payload = await response.json() as Record<string, unknown>\n const access = String(payload.access_token ?? '')\n const refresh = String(payload.refresh_token ?? '')\n if (!access)\n throw new Error('xAI token exchange did not return an access_token.')\n if (!refresh)\n throw new Error('xAI token exchange did not return a refresh_token.')\n\n return { access, refresh, expires: expiryFromPayload(payload), tokenEndpoint, discovery }\n}\n\nexport async function loginXai(\n renderPage: OAuthCallbackPageRenderer,\n callbacks: OAuthLoginCallbacks,\n): Promise<XaiOAuthCredentials> {\n const discovery = await discover()\n const { verifier, challenge } = await generatePkce()\n const state = randomToken()\n const nonce = randomToken()\n const server = await startXaiCallbackServer(renderPage)\n\n try {\n const authUrl = new URL(discovery.authorization_endpoint)\n authUrl.searchParams.set('response_type', 'code')\n authUrl.searchParams.set('client_id', xaiOAuthClientId())\n authUrl.searchParams.set('redirect_uri', server.redirectUri)\n authUrl.searchParams.set('scope', xaiOAuthScope())\n authUrl.searchParams.set('code_challenge', challenge)\n authUrl.searchParams.set('code_challenge_method', 'S256')\n authUrl.searchParams.set('state', state)\n authUrl.searchParams.set('nonce', nonce)\n // Opt into xAI's generic OAuth plan tier (SuperGrok / X Premium+).\n authUrl.searchParams.set('plan', 'generic')\n authUrl.searchParams.set('referrer', 'zidane')\n\n callbacks.onAuth({\n url: authUrl.toString(),\n instructions: `Sign in to xAI and approve access. If the browser is on another machine, the callback listener is ${server.redirectUri}.`,\n })\n\n const result = await server.waitForCallback(CALLBACK_TIMEOUT_MS)\n if (result.error)\n throw new Error(result.errorDescription ?? result.error)\n if (result.state !== state)\n throw new Error('xAI OAuth state mismatch — possible CSRF. Please retry.')\n if (!result.code)\n throw new Error('xAI OAuth callback did not include an authorization code.')\n\n callbacks.onProgress?.('Exchanging authorization code for tokens...')\n return await exchangeCode(discovery.token_endpoint, result.code, server.redirectUri, verifier, discovery)\n }\n finally {\n server.close()\n }\n}\n\nexport async function refreshXaiToken(credentials: OAuthCredentials): Promise<XaiOAuthCredentials> {\n const xai = credentials as XaiOAuthCredentials\n const clientId = xaiOAuthClientId()\n if (!credentials.refresh)\n throw new Error('xAI credentials are missing a refresh token — re-login required.')\n\n const tokenEndpoint = xai.tokenEndpoint\n ?? xai.discovery?.token_endpoint\n ?? (await discover()).token_endpoint\n validateEndpoint(tokenEndpoint, 'token_endpoint')\n\n const response = await fetch(tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: clientId,\n refresh_token: credentials.refresh,\n }),\n signal: AbortSignal.timeout(30_000),\n })\n if (!response.ok)\n throw new Error(`xAI token refresh failed: ${response.status} ${await response.text().catch(() => '')}`)\n\n const payload = await response.json() as Record<string, unknown>\n const access = String(payload.access_token ?? '')\n if (!access)\n throw new Error('xAI token refresh did not return an access_token.')\n\n return {\n ...xai,\n access,\n // xAI may omit a rotated refresh token — keep the existing one.\n refresh: String(payload.refresh_token ?? credentials.refresh),\n expires: expiryFromPayload(payload),\n tokenEndpoint,\n }\n}\n\n/**\n * Build an xAI `OAuthProviderInterface`. Shape matches Anthropic / Codex /\n * Cursor so it drops into `BUILTIN_PROVIDERS` and `src/auth.ts` unchanged.\n *\n * `usesCallbackServer: true` — the loopback flow has a real callback server,\n * so the TUI doesn't need to prompt for a manual code paste.\n */\nexport function createXaiOAuthProvider(renderPage: OAuthCallbackPageRenderer): OAuthProviderInterface {\n return {\n id: XAI_OAUTH_PROVIDER_ID,\n name: 'xAI Grok (SuperGrok / X Premium+)',\n usesCallbackServer: true,\n login: callbacks => loginXai(renderPage, callbacks),\n refreshToken: refreshXaiToken,\n getApiKey: credentials => credentials.access,\n }\n}\n"],"mappings":";;;;;;;;;;;;AAUA,SAAS,gBAAgB,OAA2B;CAClD,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,OACjB,UAAU,OAAO,aAAa,IAAI;CACpC,OAAO,KAAK,MAAM,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,MAAM,EAAE;AAC9E;AASA,eAAsB,eAAkC;CACtD,MAAM,gCAAgB,IAAI,WAAW,EAAE;CACvC,OAAO,gBAAgB,aAAa;CACpC,MAAM,WAAW,g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