index.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /**
  2. * GitLab Duo Provider Extension
  3. *
  4. * Provides access to GitLab Duo AI models (Claude and GPT) through GitLab's AI Gateway.
  5. * Delegates to pi-ai's built-in Anthropic and OpenAI streaming implementations.
  6. *
  7. * Usage:
  8. * pi -e ./packages/coding-agent/examples/extensions/custom-provider-gitlab-duo
  9. * # Then /login gitlab-duo, or set GITLAB_TOKEN=glpat-...
  10. */
  11. import {
  12. type Api,
  13. type AssistantMessageEventStream,
  14. type Context,
  15. createAssistantMessageEventStream,
  16. type Model,
  17. type OAuthCredentials,
  18. type OAuthLoginCallbacks,
  19. type SimpleStreamOptions,
  20. streamSimpleAnthropic,
  21. streamSimpleOpenAIResponses,
  22. type ThinkingLevelMap,
  23. } from "@earendil-works/pi-ai";
  24. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  25. // =============================================================================
  26. // Constants
  27. // =============================================================================
  28. const GITLAB_COM_URL = "https://gitlab.com";
  29. const AI_GATEWAY_URL = "https://cloud.gitlab.com";
  30. const ANTHROPIC_PROXY_URL = `${AI_GATEWAY_URL}/ai/v1/proxy/anthropic/`;
  31. const OPENAI_PROXY_URL = `${AI_GATEWAY_URL}/ai/v1/proxy/openai/v1`;
  32. const BUNDLED_CLIENT_ID = "da4edff2e6ebd2bc3208611e2768bc1c1dd7be791dc5ff26ca34ca9ee44f7d4b";
  33. const OAUTH_SCOPES = ["api"];
  34. const REDIRECT_URI = "http://127.0.0.1:8080/callback";
  35. const DIRECT_ACCESS_TTL = 25 * 60 * 1000;
  36. // =============================================================================
  37. // Models - exported for use by tests
  38. // =============================================================================
  39. type Backend = "anthropic" | "openai";
  40. interface GitLabModel {
  41. id: string;
  42. name: string;
  43. backend: Backend;
  44. baseUrl: string;
  45. reasoning: boolean;
  46. thinkingLevelMap?: ThinkingLevelMap;
  47. input: ("text" | "image")[];
  48. cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
  49. contextWindow: number;
  50. maxTokens: number;
  51. }
  52. export const MODELS: GitLabModel[] = [
  53. // Anthropic
  54. {
  55. id: "claude-opus-4-8",
  56. name: "Claude Opus 4.8",
  57. backend: "anthropic",
  58. baseUrl: ANTHROPIC_PROXY_URL,
  59. reasoning: true,
  60. thinkingLevelMap: { xhigh: "max" },
  61. input: ["text", "image"],
  62. cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
  63. contextWindow: 1000000,
  64. maxTokens: 128000,
  65. },
  66. {
  67. id: "claude-sonnet-4-6",
  68. name: "Claude Sonnet 4.6",
  69. backend: "anthropic",
  70. baseUrl: ANTHROPIC_PROXY_URL,
  71. reasoning: true,
  72. thinkingLevelMap: { xhigh: "max" },
  73. input: ["text", "image"],
  74. cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
  75. contextWindow: 1000000,
  76. maxTokens: 64000,
  77. },
  78. {
  79. id: "claude-opus-4-5-20251101",
  80. name: "Claude Opus 4.5",
  81. backend: "anthropic",
  82. baseUrl: ANTHROPIC_PROXY_URL,
  83. reasoning: true,
  84. thinkingLevelMap: { xhigh: "max" },
  85. input: ["text", "image"],
  86. cost: { input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75 },
  87. contextWindow: 200000,
  88. maxTokens: 32000,
  89. },
  90. {
  91. id: "claude-sonnet-4-5-20250929",
  92. name: "Claude Sonnet 4.5",
  93. backend: "anthropic",
  94. baseUrl: ANTHROPIC_PROXY_URL,
  95. reasoning: true,
  96. thinkingLevelMap: { xhigh: "max" },
  97. input: ["text", "image"],
  98. cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
  99. contextWindow: 200000,
  100. maxTokens: 16384,
  101. },
  102. {
  103. id: "claude-haiku-4-5-20251001",
  104. name: "Claude Haiku 4.5",
  105. backend: "anthropic",
  106. baseUrl: ANTHROPIC_PROXY_URL,
  107. reasoning: true,
  108. thinkingLevelMap: { xhigh: "max" },
  109. input: ["text", "image"],
  110. cost: { input: 1, output: 5, cacheRead: 0.1, cacheWrite: 1.25 },
  111. contextWindow: 200000,
  112. maxTokens: 8192,
  113. },
  114. // OpenAI (all use Responses API)
  115. {
  116. id: "gpt-5.5-2026-04-23",
  117. name: "GPT-5.5",
  118. backend: "openai",
  119. baseUrl: OPENAI_PROXY_URL,
  120. reasoning: true,
  121. input: ["text", "image"],
  122. cost: { input: 5, output: 30, cacheRead: 0.5, cacheWrite: 0 },
  123. contextWindow: 272000,
  124. maxTokens: 128000,
  125. },
  126. {
  127. id: "gpt-5.1-2025-11-13",
  128. name: "GPT-5.1",
  129. backend: "openai",
  130. baseUrl: OPENAI_PROXY_URL,
  131. reasoning: true,
  132. input: ["text", "image"],
  133. cost: { input: 2.5, output: 10, cacheRead: 0, cacheWrite: 0 },
  134. contextWindow: 128000,
  135. maxTokens: 16384,
  136. },
  137. {
  138. id: "gpt-5-mini-2025-08-07",
  139. name: "GPT-5 Mini",
  140. backend: "openai",
  141. baseUrl: OPENAI_PROXY_URL,
  142. reasoning: true,
  143. input: ["text", "image"],
  144. cost: { input: 0.15, output: 0.6, cacheRead: 0, cacheWrite: 0 },
  145. contextWindow: 128000,
  146. maxTokens: 16384,
  147. },
  148. {
  149. id: "gpt-5-codex",
  150. name: "GPT-5 Codex",
  151. backend: "openai",
  152. baseUrl: OPENAI_PROXY_URL,
  153. reasoning: true,
  154. input: ["text", "image"],
  155. cost: { input: 2.5, output: 10, cacheRead: 0, cacheWrite: 0 },
  156. contextWindow: 128000,
  157. maxTokens: 16384,
  158. },
  159. ];
  160. const MODEL_MAP = new Map(MODELS.map((m) => [m.id, m]));
  161. // =============================================================================
  162. // Direct Access Token Cache
  163. // =============================================================================
  164. interface DirectAccessToken {
  165. token: string;
  166. headers: Record<string, string>;
  167. expiresAt: number;
  168. }
  169. let cachedDirectAccess: DirectAccessToken | null = null;
  170. async function getDirectAccessToken(gitlabAccessToken: string): Promise<DirectAccessToken> {
  171. const now = Date.now();
  172. if (cachedDirectAccess && cachedDirectAccess.expiresAt > now) {
  173. return cachedDirectAccess;
  174. }
  175. const response = await fetch(`${GITLAB_COM_URL}/api/v4/ai/third_party_agents/direct_access`, {
  176. method: "POST",
  177. headers: { Authorization: `Bearer ${gitlabAccessToken}`, "Content-Type": "application/json" },
  178. body: JSON.stringify({ feature_flags: { DuoAgentPlatformNext: true } }),
  179. });
  180. if (!response.ok) {
  181. const errorText = await response.text();
  182. if (response.status === 403) {
  183. throw new Error(
  184. `GitLab Duo access denied. Ensure GitLab Duo is enabled for your account. Error: ${errorText}`,
  185. );
  186. }
  187. throw new Error(`Failed to get direct access token: ${response.status} ${errorText}`);
  188. }
  189. const data = (await response.json()) as { token: string; headers: Record<string, string> };
  190. cachedDirectAccess = { token: data.token, headers: data.headers, expiresAt: now + DIRECT_ACCESS_TTL };
  191. return cachedDirectAccess;
  192. }
  193. function invalidateDirectAccessToken() {
  194. cachedDirectAccess = null;
  195. }
  196. // =============================================================================
  197. // OAuth
  198. // =============================================================================
  199. async function generatePKCE(): Promise<{ verifier: string; challenge: string }> {
  200. const array = new Uint8Array(32);
  201. crypto.getRandomValues(array);
  202. const verifier = btoa(String.fromCharCode(...array))
  203. .replace(/\+/g, "-")
  204. .replace(/\//g, "_")
  205. .replace(/=+$/, "");
  206. const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
  207. const challenge = btoa(String.fromCharCode(...new Uint8Array(hash)))
  208. .replace(/\+/g, "-")
  209. .replace(/\//g, "_")
  210. .replace(/=+$/, "");
  211. return { verifier, challenge };
  212. }
  213. async function loginGitLab(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
  214. const { verifier, challenge } = await generatePKCE();
  215. const authParams = new URLSearchParams({
  216. client_id: BUNDLED_CLIENT_ID,
  217. redirect_uri: REDIRECT_URI,
  218. response_type: "code",
  219. scope: OAUTH_SCOPES.join(" "),
  220. code_challenge: challenge,
  221. code_challenge_method: "S256",
  222. state: crypto.randomUUID(),
  223. });
  224. callbacks.onAuth({ url: `${GITLAB_COM_URL}/oauth/authorize?${authParams.toString()}` });
  225. const callbackUrl = await callbacks.onPrompt({ message: "Paste the callback URL:" });
  226. const code = new URL(callbackUrl).searchParams.get("code");
  227. if (!code) throw new Error("No authorization code found in callback URL");
  228. const tokenResponse = await fetch(`${GITLAB_COM_URL}/oauth/token`, {
  229. method: "POST",
  230. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  231. body: new URLSearchParams({
  232. client_id: BUNDLED_CLIENT_ID,
  233. grant_type: "authorization_code",
  234. code,
  235. code_verifier: verifier,
  236. redirect_uri: REDIRECT_URI,
  237. }).toString(),
  238. });
  239. if (!tokenResponse.ok) throw new Error(`Token exchange failed: ${await tokenResponse.text()}`);
  240. const data = (await tokenResponse.json()) as {
  241. access_token: string;
  242. refresh_token: string;
  243. expires_in: number;
  244. created_at: number;
  245. };
  246. invalidateDirectAccessToken();
  247. return {
  248. refresh: data.refresh_token,
  249. access: data.access_token,
  250. expires: (data.created_at + data.expires_in) * 1000 - 5 * 60 * 1000,
  251. };
  252. }
  253. async function refreshGitLabToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
  254. const response = await fetch(`${GITLAB_COM_URL}/oauth/token`, {
  255. method: "POST",
  256. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  257. body: new URLSearchParams({
  258. client_id: BUNDLED_CLIENT_ID,
  259. grant_type: "refresh_token",
  260. refresh_token: credentials.refresh,
  261. }).toString(),
  262. });
  263. if (!response.ok) throw new Error(`Token refresh failed: ${await response.text()}`);
  264. const data = (await response.json()) as {
  265. access_token: string;
  266. refresh_token: string;
  267. expires_in: number;
  268. created_at: number;
  269. };
  270. invalidateDirectAccessToken();
  271. return {
  272. refresh: data.refresh_token,
  273. access: data.access_token,
  274. expires: (data.created_at + data.expires_in) * 1000 - 5 * 60 * 1000,
  275. };
  276. }
  277. // =============================================================================
  278. // Stream Function
  279. // =============================================================================
  280. export function streamGitLabDuo(
  281. model: Model<Api>,
  282. context: Context,
  283. options?: SimpleStreamOptions,
  284. ): AssistantMessageEventStream {
  285. const stream = createAssistantMessageEventStream();
  286. (async () => {
  287. try {
  288. const gitlabAccessToken = options?.apiKey;
  289. if (!gitlabAccessToken) throw new Error("No GitLab access token. Run /login gitlab-duo or set GITLAB_TOKEN");
  290. const cfg = MODEL_MAP.get(model.id);
  291. if (!cfg) throw new Error(`Unknown model: ${model.id}`);
  292. const directAccess = await getDirectAccessToken(gitlabAccessToken);
  293. const modelWithBaseUrl = { ...model, baseUrl: cfg.baseUrl };
  294. const headers = { ...directAccess.headers, Authorization: `Bearer ${directAccess.token}` };
  295. const streamOptions = { ...options, apiKey: "gitlab-duo", headers };
  296. const innerStream =
  297. cfg.backend === "anthropic"
  298. ? streamSimpleAnthropic(
  299. {
  300. ...(modelWithBaseUrl as Model<"anthropic-messages">),
  301. compat: {
  302. ...(modelWithBaseUrl as Model<"anthropic-messages">).compat,
  303. forceAdaptiveThinking: true,
  304. },
  305. },
  306. context,
  307. streamOptions,
  308. )
  309. : streamSimpleOpenAIResponses(modelWithBaseUrl as Model<"openai-responses">, context, streamOptions);
  310. for await (const event of innerStream) stream.push(event);
  311. stream.end();
  312. } catch (error) {
  313. stream.push({
  314. type: "error",
  315. reason: "error",
  316. error: {
  317. role: "assistant",
  318. content: [],
  319. api: model.api,
  320. provider: model.provider,
  321. model: model.id,
  322. usage: {
  323. input: 0,
  324. output: 0,
  325. cacheRead: 0,
  326. cacheWrite: 0,
  327. totalTokens: 0,
  328. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  329. },
  330. stopReason: "error",
  331. errorMessage: error instanceof Error ? error.message : String(error),
  332. timestamp: Date.now(),
  333. },
  334. });
  335. stream.end();
  336. }
  337. })();
  338. return stream;
  339. }
  340. // =============================================================================
  341. // Extension Entry Point
  342. // =============================================================================
  343. export default function (pi: ExtensionAPI) {
  344. pi.registerProvider("gitlab-duo", {
  345. baseUrl: AI_GATEWAY_URL,
  346. apiKey: "$GITLAB_TOKEN",
  347. api: "gitlab-duo-api",
  348. models: MODELS.map(({ id, name, reasoning, thinkingLevelMap, input, cost, contextWindow, maxTokens }) => ({
  349. id,
  350. name,
  351. reasoning,
  352. thinkingLevelMap,
  353. input,
  354. cost,
  355. contextWindow,
  356. maxTokens,
  357. })),
  358. oauth: {
  359. name: "GitLab Duo",
  360. login: loginGitLab,
  361. refreshToken: refreshGitLabToken,
  362. getApiKey: (cred) => cred.access,
  363. },
  364. streamSimple: streamGitLabDuo,
  365. });
  366. }