@anthonyhaussman/opencode-agy-auth 1.2.7-alpha.3 → 1.2.7

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 CHANGED
@@ -579,12 +579,6 @@ async function resolveQuotaResetDelay(accessToken, projectId, model, userAgentMo
579
579
  return null;
580
580
  }
581
581
  }
582
- var retryInternals = {
583
- parseRetryDelayValue,
584
- parseRetryDelayFromMessage,
585
- findResetTimeForModel,
586
- resolveQuotaResetDelay
587
- };
588
582
 
589
583
  // src/sdk/retry/helpers.ts
590
584
  var DEFAULT_MAX_ATTEMPTS = 3;
@@ -1581,11 +1575,7 @@ function createOAuthAuthorizeMethod(options) {
1581
1575
  const isHeadless = !!(process.env.SSH_CONNECTION || process.env.SSH_CLIENT || process.env.SSH_TTY || process.env.OPENCODE_HEADLESS);
1582
1576
  const authorization = await authorizeAgy();
1583
1577
  if (!isHeadless) {
1584
- if (options?.openBrowser) {
1585
- options.openBrowser(authorization.url);
1586
- } else {
1587
- openBrowserUrl(authorization.url);
1588
- }
1578
+ openBrowserUrl(authorization.url);
1589
1579
  }
1590
1580
  return {
1591
1581
  url: authorization.url,
@@ -1639,23 +1629,16 @@ function parseOAuthCallbackInput(input) {
1639
1629
  }
1640
1630
  return { code: trimmed };
1641
1631
  }
1642
- function defaultOpenBrowserLauncher(command, args) {
1643
- const child = spawn(command, args, {
1644
- stdio: "ignore",
1645
- detached: true
1646
- });
1647
- child.unref?.();
1648
- }
1649
- var openBrowserLauncher = defaultOpenBrowserLauncher;
1650
1632
  function openBrowserUrl(url2) {
1651
- if ((process.env.NODE_ENV === "test" || process.env.VITEST) && openBrowserLauncher === defaultOpenBrowserLauncher) {
1652
- return;
1653
- }
1654
1633
  try {
1655
1634
  const platform2 = process.platform;
1656
1635
  const command = platform2 === "darwin" ? "open" : platform2 === "win32" ? "rundll32" : "xdg-open";
1657
1636
  const args = platform2 === "win32" ? ["url.dll,FileProtocolHandler", url2] : [url2];
1658
- openBrowserLauncher(command, args);
1637
+ const child = spawn(command, args, {
1638
+ stdio: "ignore",
1639
+ detached: true
1640
+ });
1641
+ child.unref?.();
1659
1642
  } catch {
1660
1643
  }
1661
1644
  }
@@ -15337,12 +15320,6 @@ function formatRelativeResetTime(resetTime) {
15337
15320
 
15338
15321
  // src/plugin/quota.ts
15339
15322
  var AGY_QUOTA_TOOL_NAME = "agy_quota";
15340
- var AGY_V2_QUOTA_COMMAND = "agy-quota";
15341
- var AGY_V2_QUOTA_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota usage for the current authenticated account.
15342
-
15343
- Immediately call \`${AGY_QUOTA_TOOL_NAME}\` with no arguments and return its output verbatim.
15344
- Do not call other tools.
15345
- `;
15346
15323
  function createAgyQuotaTool({
15347
15324
  client,
15348
15325
  getAuthResolver,
@@ -15582,12 +15559,6 @@ function splitModelVariant(modelId) {
15582
15559
 
15583
15560
  // src/plugin/quota-summary.ts
15584
15561
  var AGY_QUOTA_SUMMARY_TOOL_NAME = "agy_quota_summary";
15585
- var AGY_V2_QUOTA_SUMMARY_COMMAND = "agy-quota-summary";
15586
- var AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota summary (weekly and 5-hour limits by model group) for the current authenticated account.
15587
-
15588
- Immediately call \`${AGY_QUOTA_SUMMARY_TOOL_NAME}\` with no arguments and return its output verbatim.
15589
- Do not call other tools.
15590
- `;
15591
15562
  function createAgyQuotaSummaryTool({
15592
15563
  client,
15593
15564
  getAuthResolver,
@@ -20233,81 +20204,22 @@ var ChatLoggerImpl = class {
20233
20204
  }
20234
20205
  };
20235
20206
 
20236
- // src/plugin/headers.ts
20237
- function getSafeHeader(headers, key) {
20238
- if (!headers) {
20239
- return void 0;
20240
- }
20241
- const targetKey = key.toLowerCase();
20242
- if (typeof headers.get === "function") {
20243
- try {
20244
- return headers.get(targetKey) || void 0;
20245
- } catch {
20246
- }
20247
- }
20248
- if (Array.isArray(headers)) {
20249
- const found = headers.find((item) => {
20250
- if (Array.isArray(item) && typeof item[0] === "string") {
20251
- return item[0].toLowerCase() === targetKey;
20252
- }
20253
- return false;
20254
- });
20255
- return found ? String(found[1]) : void 0;
20256
- }
20257
- if (typeof headers === "object") {
20258
- const foundKey = Object.keys(headers).find((k) => k.toLowerCase() === targetKey);
20259
- return foundKey ? headers[foundKey] !== void 0 ? String(headers[foundKey]) : void 0 : void 0;
20260
- }
20261
- return void 0;
20262
- }
20263
- function setSafeHeaders(initHeaders, newHeaders) {
20264
- if (typeof globalThis.Headers !== "undefined") {
20265
- const headers = new globalThis.Headers(initHeaders ?? {});
20266
- for (const [k, v] of Object.entries(newHeaders)) {
20267
- headers.set(k, v);
20268
- }
20269
- return headers;
20270
- }
20271
- if (Array.isArray(initHeaders)) {
20272
- const nextHeaders2 = [...initHeaders];
20273
- for (const [k, v] of Object.entries(newHeaders)) {
20274
- const idx = nextHeaders2.findIndex((item) => Array.isArray(item) && typeof item[0] === "string" && item[0].toLowerCase() === k.toLowerCase());
20275
- if (idx !== -1) {
20276
- nextHeaders2[idx] = [k, v];
20277
- } else {
20278
- nextHeaders2.push([k, v]);
20279
- }
20280
- }
20281
- return nextHeaders2;
20282
- }
20283
- const nextHeaders = {};
20284
- if (initHeaders && typeof initHeaders === "object") {
20285
- for (const [k, v] of Object.entries(initHeaders)) {
20286
- nextHeaders[k] = String(v);
20287
- }
20288
- }
20289
- for (const [k, v] of Object.entries(newHeaders)) {
20290
- const existingKey = Object.keys(nextHeaders).find((key) => key.toLowerCase() === k.toLowerCase());
20291
- if (existingKey) {
20292
- nextHeaders[existingKey] = v;
20293
- } else {
20294
- nextHeaders[k] = v;
20295
- }
20296
- }
20297
- return nextHeaders;
20298
- }
20299
- function toUrlString(value) {
20300
- if (typeof value === "string") {
20301
- return value;
20302
- }
20303
- const candidate = value.url;
20304
- if (candidate) {
20305
- return candidate;
20306
- }
20307
- return value.toString();
20308
- }
20207
+ // src/plugin.ts
20208
+ var AGY_QUOTA_COMMAND = "agyquota";
20209
+ var AGY_QUOTA_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota usage for the current authenticated account.
20309
20210
 
20310
- // src/plugin/tier.ts
20211
+ Immediately call \`${AGY_QUOTA_TOOL_NAME}\` with no arguments and return its output verbatim.
20212
+ Do not call other tools.
20213
+ `;
20214
+ var AGY_QUOTA_SUMMARY_COMMAND = "agyquotasummary";
20215
+ var AGY_QUOTA_SUMMARY_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota summary (weekly and 5-hour limits by model group) for the current authenticated account.
20216
+
20217
+ Immediately call \`${AGY_QUOTA_SUMMARY_TOOL_NAME}\` with no arguments and return its output verbatim.
20218
+ Do not call other tools.
20219
+ `;
20220
+ var latestAgyAuthResolver;
20221
+ var latestAgyConfiguredProjectId;
20222
+ var latestAgyUserAgentModel;
20311
20223
  var STATIC_MODELS_SIMPLE = {
20312
20224
  "gemini-3.8-flash": {
20313
20225
  name: "Gemini 3.8 Flash",
@@ -20395,39 +20307,6 @@ var TIER_MAPPING = {
20395
20307
  high: "gemini-3.1-pro-high"
20396
20308
  }
20397
20309
  };
20398
- function resolveModelTier(baseModelId, headersOrInit) {
20399
- const parts = baseModelId.split("@");
20400
- const base = parts[0] || "";
20401
- const suffixTier = parts[1]?.toLowerCase();
20402
- const mapping = TIER_MAPPING[base];
20403
- if (!mapping) {
20404
- return baseModelId;
20405
- }
20406
- const rawHeaders = headersOrInit && typeof headersOrInit === "object" && "headers" in headersOrInit ? headersOrInit.headers : headersOrInit;
20407
- const headerTier = getSafeHeader(rawHeaders, "x-agy-tier")?.toLowerCase() || null;
20408
- const requestedTier = headerTier || suffixTier;
20409
- if (requestedTier && Object.prototype.hasOwnProperty.call(mapping, requestedTier)) {
20410
- return mapping[requestedTier] || baseModelId;
20411
- }
20412
- return mapping["medium"] ?? mapping["high"] ?? baseModelId;
20413
- }
20414
-
20415
- // src/plugin.ts
20416
- var AGY_QUOTA_COMMAND = "agyquota";
20417
- var AGY_QUOTA_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota usage for the current authenticated account.
20418
-
20419
- Immediately call \`${AGY_QUOTA_TOOL_NAME}\` with no arguments and return its output verbatim.
20420
- Do not call other tools.
20421
- `;
20422
- var AGY_QUOTA_SUMMARY_COMMAND = "agyquotasummary";
20423
- var AGY_QUOTA_SUMMARY_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota summary (weekly and 5-hour limits by model group) for the current authenticated account.
20424
-
20425
- Immediately call \`${AGY_QUOTA_SUMMARY_TOOL_NAME}\` with no arguments and return its output verbatim.
20426
- Do not call other tools.
20427
- `;
20428
- var latestAgyAuthResolver;
20429
- var latestAgyConfiguredProjectId;
20430
- var latestAgyUserAgentModel;
20431
20310
  var buildModelFromSimple = (modelId, simple) => {
20432
20311
  const isClaude = modelId.startsWith("claude-");
20433
20312
  const isGpt = modelId.startsWith("gpt-");
@@ -20521,6 +20400,83 @@ var STATIC_MODELS = {};
20521
20400
  for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
20522
20401
  STATIC_MODELS[modelId] = buildModelFromSimple(modelId, simple);
20523
20402
  }
20403
+ function getSafeHeader(headers, key) {
20404
+ if (!headers) {
20405
+ return void 0;
20406
+ }
20407
+ const targetKey = key.toLowerCase();
20408
+ if (typeof headers.get === "function") {
20409
+ try {
20410
+ return headers.get(targetKey) || void 0;
20411
+ } catch {
20412
+ }
20413
+ }
20414
+ if (Array.isArray(headers)) {
20415
+ const found = headers.find((item) => {
20416
+ if (Array.isArray(item) && typeof item[0] === "string") {
20417
+ return item[0].toLowerCase() === targetKey;
20418
+ }
20419
+ return false;
20420
+ });
20421
+ return found ? String(found[1]) : void 0;
20422
+ }
20423
+ if (typeof headers === "object") {
20424
+ const foundKey = Object.keys(headers).find((k) => k.toLowerCase() === targetKey);
20425
+ return foundKey ? headers[foundKey] !== void 0 ? String(headers[foundKey]) : void 0 : void 0;
20426
+ }
20427
+ return void 0;
20428
+ }
20429
+ function setSafeHeaders(initHeaders, newHeaders) {
20430
+ if (typeof globalThis.Headers !== "undefined") {
20431
+ const headers = new globalThis.Headers(initHeaders ?? {});
20432
+ for (const [k, v] of Object.entries(newHeaders)) {
20433
+ headers.set(k, v);
20434
+ }
20435
+ return headers;
20436
+ }
20437
+ if (Array.isArray(initHeaders)) {
20438
+ const nextHeaders2 = [...initHeaders];
20439
+ for (const [k, v] of Object.entries(newHeaders)) {
20440
+ const idx = nextHeaders2.findIndex((item) => Array.isArray(item) && typeof item[0] === "string" && item[0].toLowerCase() === k.toLowerCase());
20441
+ if (idx !== -1) {
20442
+ nextHeaders2[idx] = [k, v];
20443
+ } else {
20444
+ nextHeaders2.push([k, v]);
20445
+ }
20446
+ }
20447
+ return nextHeaders2;
20448
+ }
20449
+ const nextHeaders = {};
20450
+ if (initHeaders && typeof initHeaders === "object") {
20451
+ for (const [k, v] of Object.entries(initHeaders)) {
20452
+ nextHeaders[k] = String(v);
20453
+ }
20454
+ }
20455
+ for (const [k, v] of Object.entries(newHeaders)) {
20456
+ const existingKey = Object.keys(nextHeaders).find((key) => key.toLowerCase() === k.toLowerCase());
20457
+ if (existingKey) {
20458
+ nextHeaders[existingKey] = v;
20459
+ } else {
20460
+ nextHeaders[k] = v;
20461
+ }
20462
+ }
20463
+ return nextHeaders;
20464
+ }
20465
+ function resolveModelTier(baseModelId, init) {
20466
+ const parts = baseModelId.split("@");
20467
+ const base = parts[0] || "";
20468
+ const suffixTier = parts[1]?.toLowerCase();
20469
+ const mapping = TIER_MAPPING[base];
20470
+ if (!mapping) {
20471
+ return baseModelId;
20472
+ }
20473
+ const headerTier = getSafeHeader(init?.headers, "x-agy-tier")?.toLowerCase() || null;
20474
+ const requestedTier = headerTier || suffixTier;
20475
+ if (requestedTier && Object.prototype.hasOwnProperty.call(mapping, requestedTier)) {
20476
+ return mapping[requestedTier] || baseModelId;
20477
+ }
20478
+ return mapping["medium"] ?? mapping["high"];
20479
+ }
20524
20480
  var AgyCLIOAuthPlugin = async ({ client }) => {
20525
20481
  let latestConfig;
20526
20482
  updateStaticModelsWithPricing(STATIC_MODELS);
@@ -20848,749 +20804,25 @@ async function ensureProjectContextOrThrow(authRecord, client, configuredProject
20848
20804
  throw error45;
20849
20805
  }
20850
20806
  }
20851
-
20852
- // src/plugin/types.ts
20853
- function defineOpenCodeV2Plugin(def) {
20854
- return def;
20855
- }
20856
-
20857
- // src/plugin/v2-storage.ts
20858
- import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "fs";
20859
- import { homedir as homedir4 } from "os";
20860
- import { join as join6 } from "path";
20861
- var storedAuthOverrideForTesting = void 0;
20862
- function loadStoredAuthFromJson() {
20863
- if (storedAuthOverrideForTesting !== void 0) {
20864
- return storedAuthOverrideForTesting;
20865
- }
20866
- const authPath = join6(homedir4(), ".local", "share", "opencode", "auth.json");
20867
- try {
20868
- if (existsSync6(authPath)) {
20869
- const content = readFileSync5(authPath, "utf8");
20870
- const data = JSON.parse(content);
20871
- return data?.[AGY_PROVIDER_ID];
20872
- }
20873
- } catch {
20874
- }
20875
- return void 0;
20876
- }
20877
- function saveStoredAuthToJson(authRecord) {
20878
- if (process.env.NODE_ENV === "test" || process.env.VITEST || storedAuthOverrideForTesting !== void 0) {
20879
- return;
20880
- }
20881
- try {
20882
- const dirPath = join6(homedir4(), ".local", "share", "opencode");
20883
- if (!existsSync6(dirPath)) {
20884
- mkdirSync5(dirPath, { recursive: true });
20885
- }
20886
- const authPath = join6(dirPath, "auth.json");
20887
- let data = {};
20888
- if (existsSync6(authPath)) {
20889
- try {
20890
- data = JSON.parse(readFileSync5(authPath, "utf8")) || {};
20891
- } catch {
20892
- data = {};
20893
- }
20894
- }
20895
- data[AGY_PROVIDER_ID] = {
20896
- type: "oauth",
20897
- refresh: authRecord.refresh,
20898
- access: authRecord.access,
20899
- expires: authRecord.expires
20900
- };
20901
- writeFileSync5(authPath, JSON.stringify(data, null, 2), "utf8");
20902
- } catch {
20903
- }
20904
- }
20905
-
20906
- // src/plugin/v2-fetch.ts
20907
- function createV2FetchInterceptor(getAuthSnapshot) {
20908
- return async function agyV2Fetch(input, init) {
20909
- const isGL = isGenerativeLanguageRequest(input);
20910
- const isInternal = toUrlString(input).includes("cloudcode-pa.googleapis.com");
20911
- if (!isGL && !isInternal) {
20912
- return (globalThis.fetch || fetch)(input, init);
20913
- }
20914
- let rawAuth = getAuthSnapshot ? await getAuthSnapshot() : void 0;
20915
- if (!rawAuth) {
20916
- rawAuth = loadStoredAuthFromJson();
20917
- }
20918
- if (!rawAuth || !isOAuthAuth(rawAuth)) {
20919
- return (globalThis.fetch || fetch)(input, init);
20920
- }
20921
- let authRecord = resolveCachedAuth(rawAuth);
20922
- if (accessTokenExpired(authRecord)) {
20923
- const refreshed = await refreshAccessToken(authRecord, { auth: { set: async () => {
20924
- } } });
20925
- if (refreshed) {
20926
- authRecord = refreshed;
20927
- }
20928
- }
20929
- if (!authRecord.access) {
20930
- return (globalThis.fetch || fetch)(input, init);
20931
- }
20932
- if (isInternal) {
20933
- const hasAuth = getSafeHeader(init?.headers, "Authorization") !== void 0;
20934
- if (hasAuth) {
20935
- return (globalThis.fetch || fetch)(input, init);
20936
- }
20937
- const userAgent = buildAgyCliUserAgent();
20938
- const headers = setSafeHeaders(init?.headers, {
20939
- Authorization: `Bearer ${authRecord.access}`,
20940
- "User-Agent": userAgent
20941
- });
20942
- return (globalThis.fetch || fetch)(input, {
20943
- ...init,
20944
- headers
20945
- });
20946
- }
20947
- const requestTarget = parseGenerativeLanguageRequest(input);
20948
- const requestUserAgentModel = requestTarget?.effectiveModel;
20949
- let projectContext;
20950
- try {
20951
- projectContext = await ensureProjectContext(
20952
- authRecord,
20953
- { auth: { set: async () => {
20954
- } } },
20955
- void 0,
20956
- requestUserAgentModel
20957
- );
20958
- } catch {
20959
- projectContext = {
20960
- effectiveProjectId: parseRefreshParts(authRecord.refresh).projectId || "antigravity",
20961
- auth: authRecord
20962
- };
20963
- }
20964
- const originalRequestedModel = parseGenerativeLanguageRequest(input)?.effectiveModel;
20965
- let modifiedInput = input;
20966
- if (isGL && originalRequestedModel) {
20967
- const originalBase = originalRequestedModel.replace("google-agy/", "");
20968
- const resolvedBase = resolveModelTier(originalBase, init);
20969
- if (originalBase !== resolvedBase) {
20970
- if (typeof modifiedInput === "string") {
20971
- modifiedInput = modifiedInput.replace(`models/${originalBase}`, `models/${resolvedBase}`);
20972
- } else if (typeof Request !== "undefined" && modifiedInput instanceof Request) {
20973
- const newUrl = modifiedInput.url.replace(`models/${originalBase}`, `models/${resolvedBase}`);
20974
- modifiedInput = new Request(newUrl, modifiedInput);
20975
- }
20976
- }
20977
- }
20978
- const transformed = prepareAgyRequest(
20979
- modifiedInput,
20980
- init,
20981
- authRecord.access,
20982
- projectContext.effectiveProjectId,
20983
- void 0
20984
- );
20985
- const chatLogger = createChatLogger();
20986
- if (chatLogger) {
20987
- chatLogger.logRequest(
20988
- toUrlString(transformed.request),
20989
- transformed.init.method || "GET",
20990
- transformed.init.headers,
20991
- transformed.init.body
20992
- );
20993
- }
20994
- const response = await fetchWithRetry(transformed.request, transformed.init);
20995
- return transformAgyResponse(
20996
- response,
20997
- transformed.streaming,
20998
- null,
20999
- transformed.requestedModel,
21000
- transformed.sessionId,
21001
- chatLogger
21002
- );
21003
- };
21004
- }
21005
-
21006
- // src/plugin/v2-session.ts
21007
- function createV2HttpRequestHook(state = {}) {
21008
- return async (event) => {
21009
- if (!event) return;
21010
- const rawUrl = typeof event.url === "string" ? event.url : event.request?.url || "";
21011
- const isGL = isGenerativeLanguageRequest(rawUrl);
21012
- const isInternal = rawUrl.includes("cloudcode-pa.googleapis.com");
21013
- if (!isGL && !isInternal) {
21014
- return;
21015
- }
21016
- event.headers = event.headers || {};
21017
- let modelName;
21018
- let rawAuth = event.auth;
21019
- if (rawAuth && !rawAuth.type) {
21020
- const tokenVal = rawAuth.access || rawAuth.token;
21021
- if (tokenVal || rawAuth.refresh) {
21022
- rawAuth = { type: "oauth", access: tokenVal, ...rawAuth };
21023
- }
21024
- }
21025
- if (!rawAuth || !isOAuthAuth(rawAuth)) {
21026
- rawAuth = loadStoredAuthFromJson();
21027
- }
21028
- let authRecord = rawAuth && isOAuthAuth(rawAuth) ? resolveCachedAuth(rawAuth) : void 0;
21029
- if (authRecord && accessTokenExpired(authRecord)) {
21030
- const refreshed = await refreshAccessToken(authRecord, { auth: { set: async () => {
21031
- } } });
21032
- if (refreshed) {
21033
- authRecord = refreshed;
21034
- saveStoredAuthToJson(refreshed);
21035
- }
21036
- }
21037
- if (isGL) {
21038
- const parsed = parseGenerativeLanguageRequest(rawUrl);
21039
- modelName = parsed?.effectiveModel;
21040
- if (modelName) {
21041
- state.lastInterceptedModel = modelName;
21042
- }
21043
- if (typeof event.headers.delete === "function") {
21044
- event.headers.delete("x-goog-api-key");
21045
- event.headers.delete("api-key");
21046
- } else {
21047
- for (const key of Object.keys(event.headers)) {
21048
- const lower = key.toLowerCase();
21049
- if (lower === "x-goog-api-key" || lower === "api-key") {
21050
- delete event.headers[key];
21051
- }
21052
- }
21053
- }
21054
- if (event.request?.headers) {
21055
- if (typeof event.request.headers.delete === "function") {
21056
- event.request.headers.delete("x-goog-api-key");
21057
- event.request.headers.delete("api-key");
21058
- } else {
21059
- for (const key of Object.keys(event.request.headers)) {
21060
- const lower = key.toLowerCase();
21061
- if (lower === "x-goog-api-key" || lower === "api-key") {
21062
- delete event.request.headers[key];
21063
- }
21064
- }
21065
- }
21066
- }
21067
- let cleanUrl = rawUrl;
21068
- try {
21069
- const parsedUrl = new URL(rawUrl);
21070
- let urlChanged = false;
21071
- for (const param of ["key", "x-goog-api-key", "api-key"]) {
21072
- if (parsedUrl.searchParams.has(param)) {
21073
- parsedUrl.searchParams.delete(param);
21074
- urlChanged = true;
21075
- }
21076
- }
21077
- if (urlChanged) {
21078
- cleanUrl = parsedUrl.toString();
21079
- }
21080
- } catch {
21081
- }
21082
- if (authRecord && authRecord.access) {
21083
- let projectContext;
21084
- try {
21085
- projectContext = await ensureProjectContext(
21086
- authRecord,
21087
- { auth: { set: async () => {
21088
- } } },
21089
- void 0,
21090
- modelName
21091
- );
21092
- } catch {
21093
- projectContext = {
21094
- effectiveProjectId: parseRefreshParts(authRecord.refresh).projectId || "antigravity",
21095
- auth: authRecord
21096
- };
21097
- }
21098
- const originalRequestedModel = modelName;
21099
- let modifiedUrl = cleanUrl;
21100
- if (originalRequestedModel) {
21101
- const originalBase = originalRequestedModel.replace("google-agy/", "");
21102
- const initHeaders = event.headers instanceof Headers ? event.headers : event.request?.headers;
21103
- const resolvedBase = resolveModelTier(originalBase, { headers: initHeaders });
21104
- if (originalBase !== resolvedBase) {
21105
- modifiedUrl = modifiedUrl.replace(`models/${originalBase}`, `models/${resolvedBase}`);
21106
- }
21107
- }
21108
- let bodyPayload = event.body;
21109
- if (bodyPayload === void 0 && event.request) {
21110
- if (typeof event.request.clone === "function") {
21111
- try {
21112
- bodyPayload = await event.request.clone().text();
21113
- } catch {
21114
- }
21115
- } else if (event.request.body !== void 0) {
21116
- bodyPayload = event.request.body;
21117
- }
21118
- }
21119
- let preExistingUserAgent;
21120
- if (typeof event.headers?.get === "function") {
21121
- preExistingUserAgent = event.headers.get("user-agent") || event.headers.get("User-Agent") || void 0;
21122
- } else if (event.headers && typeof event.headers === "object") {
21123
- preExistingUserAgent = event.headers["user-agent"] || event.headers["User-Agent"] || void 0;
21124
- }
21125
- if (!preExistingUserAgent && typeof event.request?.headers?.get === "function") {
21126
- preExistingUserAgent = event.request.headers.get("user-agent") || event.request.headers.get("User-Agent") || void 0;
21127
- } else if (!preExistingUserAgent && event.request?.headers && typeof event.request.headers === "object") {
21128
- preExistingUserAgent = event.request.headers["user-agent"] || event.request.headers["User-Agent"] || void 0;
21129
- }
21130
- const method = event.method || event.request?.method || "POST";
21131
- const requestHeaders = event.headers || event.request?.headers;
21132
- const transformed = prepareAgyRequest(
21133
- modifiedUrl,
21134
- {
21135
- method,
21136
- headers: requestHeaders,
21137
- body: bodyPayload
21138
- },
21139
- authRecord.access,
21140
- projectContext.effectiveProjectId
21141
- );
21142
- const targetUrl = toUrlString(transformed.request);
21143
- if (typeof event.url === "string") {
21144
- event.url = targetUrl;
21145
- }
21146
- if (event.request && typeof event.request === "object") {
21147
- if (typeof Request !== "undefined" && event.request instanceof Request) {
21148
- event.request = new Request(targetUrl, {
21149
- method: transformed.init.method,
21150
- headers: transformed.init.headers,
21151
- body: transformed.init.body
21152
- });
21153
- } else if (typeof event.request.url === "string") {
21154
- try {
21155
- event.request.url = targetUrl;
21156
- } catch {
21157
- }
21158
- }
21159
- }
21160
- const headerEntries = transformed.init.headers instanceof Headers ? Array.from(transformed.init.headers.entries()) : Object.entries(transformed.init.headers || {});
21161
- for (const [k, v] of headerEntries) {
21162
- const lowerK = k.toLowerCase();
21163
- if (lowerK === "user-agent") {
21164
- if (preExistingUserAgent) {
21165
- continue;
21166
- }
21167
- if (typeof event.headers?.set === "function") {
21168
- event.headers.set("User-Agent", v);
21169
- } else if (event.headers) {
21170
- event.headers["User-Agent"] = v;
21171
- }
21172
- if (event.request?.headers && typeof event.request.headers.set === "function") {
21173
- event.request.headers.set("User-Agent", v);
21174
- } else if (event.request?.headers && typeof event.request.headers === "object") {
21175
- event.request.headers["User-Agent"] = v;
21176
- }
21177
- continue;
21178
- }
21179
- if (typeof event.headers?.set === "function") {
21180
- event.headers.set(k, v);
21181
- } else if (event.headers) {
21182
- event.headers[k] = v;
21183
- }
21184
- if (event.request?.headers && typeof event.request.headers.set === "function") {
21185
- event.request.headers.set(k, v);
21186
- } else if (event.request?.headers && typeof event.request.headers === "object") {
21187
- event.request.headers[k] = v;
21188
- }
21189
- }
21190
- if (transformed.init.body !== void 0) {
21191
- event.body = transformed.init.body;
21192
- if (event.request && typeof event.request === "object" && !(event.request instanceof Request)) {
21193
- event.request.body = transformed.init.body;
21194
- }
21195
- }
21196
- } else {
21197
- if (typeof event.url === "string") {
21198
- event.url = cleanUrl;
21199
- }
21200
- if (event.request && typeof event.request === "object") {
21201
- if (typeof event.request.url === "string") {
21202
- event.request.url = cleanUrl;
21203
- }
21204
- }
21205
- }
21206
- }
21207
- if (authRecord && authRecord.access) {
21208
- if (typeof event.headers?.set === "function") {
21209
- event.headers.set("Authorization", `Bearer ${authRecord.access}`);
21210
- } else if (event.headers) {
21211
- event.headers["Authorization"] = `Bearer ${authRecord.access}`;
21212
- }
21213
- if (event.request?.headers && typeof event.request.headers.set === "function") {
21214
- event.request.headers.set("Authorization", `Bearer ${authRecord.access}`);
21215
- } else if (event.request?.headers && typeof event.request.headers === "object") {
21216
- event.request.headers["Authorization"] = `Bearer ${authRecord.access}`;
21217
- }
21218
- }
21219
- const userAgent = buildAgyCliUserAgent(modelName);
21220
- if (typeof event.headers?.set === "function") {
21221
- if (!event.headers.get("User-Agent") && !event.headers.get("user-agent")) {
21222
- event.headers.set("User-Agent", userAgent);
21223
- }
21224
- } else if (event.headers) {
21225
- if (!event.headers["User-Agent"] && !event.headers["user-agent"]) {
21226
- event.headers["User-Agent"] = userAgent;
21227
- }
21228
- }
21229
- if (event.request?.headers && typeof event.request.headers.set === "function") {
21230
- if (!event.request.headers.get("User-Agent") && !event.request.headers.get("user-agent")) {
21231
- event.request.headers.set("User-Agent", userAgent);
21232
- }
21233
- } else if (event.request?.headers && typeof event.request.headers === "object") {
21234
- if (!event.request.headers["User-Agent"] && !event.request.headers["user-agent"]) {
21235
- event.request.headers["User-Agent"] = userAgent;
21236
- }
21237
- }
21238
- };
21239
- }
21240
- function createV2HttpResponseHook(state = {}) {
21241
- return async (event) => {
21242
- if (!event || !event.response) return;
21243
- const rawUrl = typeof event.url === "string" ? event.url : event.request?.url || "";
21244
- const isInternal = rawUrl.includes("cloudcode-pa.googleapis.com");
21245
- if (isInternal && event.response instanceof Response) {
21246
- const isStreaming = rawUrl.includes(":streamGenerateCode") || event.response.headers.get("content-type")?.includes("text/event-stream");
21247
- const parsedModel = parseGenerativeLanguageRequest(rawUrl)?.effectiveModel || state.lastInterceptedModel;
21248
- const transformed = await transformAgyResponse(
21249
- event.response,
21250
- !!isStreaming,
21251
- null,
21252
- parsedModel,
21253
- void 0,
21254
- void 0
21255
- );
21256
- event.response = transformed;
21257
- }
21258
- };
21259
- }
21260
- function createV2RetryHook() {
21261
- return async (event) => {
21262
- if (!event) return;
21263
- const response = event.response;
21264
- if (response instanceof Response) {
21265
- if (response.status === 429 || response.status === 503) {
21266
- const quota = await classifyQuotaResponse(response);
21267
- if (quota?.retryDelayMs) {
21268
- event.retryDelayMs = quota.retryDelayMs;
21269
- } else {
21270
- event.retryDelayMs = await resolveRetryDelayMs(response, event.attempt || 1);
21271
- }
21272
- }
21273
- } else if (event.details && Array.isArray(event.details)) {
21274
- const retryInfo = event.details.find(
21275
- (d) => d && d["@type"] === "type.googleapis.com/google.rpc.RetryInfo"
21276
- );
21277
- if (retryInfo?.retryDelay) {
21278
- const delayMs = retryInternals.parseRetryDelayValue(retryInfo.retryDelay);
21279
- if (delayMs !== null) {
21280
- event.retryDelayMs = delayMs;
21281
- }
21282
- }
21283
- }
21284
- };
21285
- }
21286
- function registerV2SessionHooks(ctx) {
21287
- const state = {};
21288
- ctx.session.hook("http.request", createV2HttpRequestHook(state), { providerID: AGY_PROVIDER_ID });
21289
- ctx.session.hook("http.response", createV2HttpResponseHook(state), { providerID: AGY_PROVIDER_ID });
21290
- ctx.session.hook("retry", createV2RetryHook(), { providerID: AGY_PROVIDER_ID });
21291
- }
21292
-
21293
- // src/plugin/v2.ts
21294
- async function setupOpenCodeV2(ctx) {
21295
- const resolveVariants = (modelId) => {
21296
- const mapping = TIER_MAPPING[modelId];
21297
- if (!mapping) return void 0;
21298
- const variants = [];
21299
- if (mapping.minimal !== void 0) variants.push({ id: "minimal" });
21300
- if (mapping.low !== void 0) variants.push({ id: "low" });
21301
- if (mapping.medium !== void 0) variants.push({ id: "medium" });
21302
- if (mapping.high !== void 0) variants.push({ id: "high" });
21303
- return variants.length > 0 ? variants : void 0;
21304
- };
21305
- const updateProviderRecord = (p) => {
21306
- p.name = "Antigravity CLI";
21307
- p.activation = "enabled";
21308
- p.package = "aisdk:@ai-sdk/google";
21309
- p.description = "Google Gemini Antigravity Code Assist OAuth provider";
21310
- p.settings = { ...p.settings || {}, apiKey: "dummy" };
21311
- p.integrationID = AGY_PROVIDER_ID;
21312
- };
21313
- const buildModelRecord = (modelId, simple, existingModel) => {
21314
- const isClaude = modelId.startsWith("claude-");
21315
- const isGpt = modelId.startsWith("gpt-");
21316
- const variants = resolveVariants(modelId);
21317
- return {
21318
- id: modelId,
21319
- providerID: AGY_PROVIDER_ID,
21320
- name: simple.name,
21321
- description: simple.description,
21322
- family: modelId.includes("gemini") ? "gemini" : isClaude ? "claude" : isGpt ? "gpt" : "unknown",
21323
- reasoning: simple.reasoning,
21324
- attachment: simple.attachment,
21325
- tool_call: simple.toolCall,
21326
- limit: {
21327
- context: simple.maxTokens,
21328
- output: simple.maxOutputTokens
21329
- },
21330
- cost: simple.cost || { input: 0, output: 0 },
21331
- ...variants ? { variants } : {},
21332
- ...existingModel || {}
21333
- };
21334
- };
21335
- const updateModelRecord = (m, modelId, simple) => {
21336
- m.name = simple.name;
21337
- m.capabilities = {
21338
- tools: true,
21339
- input: ["text", "image"],
21340
- output: ["text"]
21341
- };
21342
- m.limit = {
21343
- context: simple.maxTokens,
21344
- output: simple.maxOutputTokens
21345
- };
21346
- m.family = "gemini";
21347
- if (simple.cost) {
21348
- m.cost = simple.cost;
21349
- }
21350
- const variants = resolveVariants(modelId);
21351
- if (variants) {
21352
- m.variants = variants;
21353
- }
21354
- };
21355
- if (ctx.provider?.transform) {
21356
- ctx.provider.transform(async (editor) => {
21357
- if (!editor) return;
21358
- if (typeof editor.update === "function") {
21359
- editor.update(AGY_PROVIDER_ID, updateProviderRecord);
21360
- } else if (typeof editor.set === "function") {
21361
- const p = { id: AGY_PROVIDER_ID };
21362
- updateProviderRecord(p);
21363
- editor.set(AGY_PROVIDER_ID, p);
21364
- } else if (typeof editor === "object") {
21365
- const p = editor[AGY_PROVIDER_ID] || { id: AGY_PROVIDER_ID };
21366
- updateProviderRecord(p);
21367
- editor[AGY_PROVIDER_ID] = p;
21368
- }
21369
- });
21370
- }
21371
- if (ctx.model?.transform) {
21372
- ctx.model.transform(async (editor) => {
21373
- if (!editor) return;
21374
- if (typeof editor.update === "function") {
21375
- for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21376
- editor.update(AGY_PROVIDER_ID, modelId, (m) => updateModelRecord(m, modelId, simple));
21377
- }
21378
- } else if (typeof editor.set === "function") {
21379
- for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21380
- const m = buildModelRecord(modelId, simple);
21381
- editor.set(`${AGY_PROVIDER_ID}:${modelId}`, m);
21382
- }
21383
- } else if (typeof editor === "object") {
21384
- for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21385
- const key = `${AGY_PROVIDER_ID}:${modelId}`;
21386
- editor[key] = buildModelRecord(modelId, simple, editor[key]);
21387
- }
21388
- }
21389
- });
20807
+ function toUrlString(value) {
20808
+ if (typeof value === "string") {
20809
+ return value;
21390
20810
  }
21391
- if (ctx.catalog?.transform) {
21392
- ctx.catalog.transform(async (editor) => {
21393
- if (!editor) return;
21394
- if (typeof editor?.provider?.update === "function") {
21395
- editor.provider.update(AGY_PROVIDER_ID, updateProviderRecord);
21396
- if (typeof editor?.model?.update === "function") {
21397
- for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21398
- editor.model.update(AGY_PROVIDER_ID, modelId, (m) => updateModelRecord(m, modelId, simple));
21399
- }
21400
- }
21401
- return;
21402
- }
21403
- const catalog = editor;
21404
- catalog.providers = catalog.providers || {};
21405
- catalog.providers[AGY_PROVIDER_ID] = {
21406
- id: AGY_PROVIDER_ID,
21407
- name: "Antigravity CLI",
21408
- npm: "aisdk:@ai-sdk/google",
21409
- settings: { apiKey: "dummy" },
21410
- integrationID: AGY_PROVIDER_ID,
21411
- models: { ...catalog.providers[AGY_PROVIDER_ID]?.models || {} },
21412
- ...catalog.providers[AGY_PROVIDER_ID]
21413
- };
21414
- if (catalog.providers[AGY_PROVIDER_ID].settings) {
21415
- catalog.providers[AGY_PROVIDER_ID].settings = {
21416
- ...catalog.providers[AGY_PROVIDER_ID].settings,
21417
- apiKey: "dummy"
21418
- };
21419
- } else {
21420
- catalog.providers[AGY_PROVIDER_ID].settings = { apiKey: "dummy" };
21421
- }
21422
- catalog.providers[AGY_PROVIDER_ID].integrationID = AGY_PROVIDER_ID;
21423
- const targetModels = catalog.providers[AGY_PROVIDER_ID].models;
21424
- for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21425
- targetModels[modelId] = buildModelRecord(modelId, simple, targetModels[modelId]);
21426
- }
21427
- });
20811
+ const candidate = value.url;
20812
+ if (candidate) {
20813
+ return candidate;
21428
20814
  }
21429
- ctx.tool.transform(async (editor) => {
21430
- if (!editor) return;
21431
- const quotaTool = createAgyQuotaTool({
21432
- client: void 0,
21433
- getAuthResolver: () => void 0,
21434
- getConfiguredProjectId: () => void 0,
21435
- getUserAgentModel: () => void 0
21436
- });
21437
- const quotaSummaryTool = createAgyQuotaSummaryTool({
21438
- client: void 0,
21439
- getAuthResolver: () => void 0,
21440
- getConfiguredProjectId: () => void 0,
21441
- getUserAgentModel: () => void 0
21442
- });
21443
- if (typeof editor.add === "function") {
21444
- editor.add({
21445
- name: AGY_QUOTA_TOOL_NAME,
21446
- description: quotaTool.description,
21447
- input: {},
21448
- execute: async (args, context) => quotaTool.execute(args, context)
21449
- });
21450
- editor.add({
21451
- name: AGY_QUOTA_SUMMARY_TOOL_NAME,
21452
- description: quotaSummaryTool.description,
21453
- input: {},
21454
- execute: async (args, context) => quotaSummaryTool.execute(args, context)
21455
- });
21456
- } else if (typeof editor.set === "function") {
21457
- editor.set(AGY_QUOTA_TOOL_NAME, quotaTool);
21458
- editor.set(AGY_QUOTA_SUMMARY_TOOL_NAME, quotaSummaryTool);
21459
- } else if (editor.tools && typeof editor.tools === "object") {
21460
- editor.tools[AGY_QUOTA_TOOL_NAME] = quotaTool;
21461
- editor.tools[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21462
- } else if (typeof editor === "object") {
21463
- editor[AGY_QUOTA_TOOL_NAME] = quotaTool;
21464
- editor[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21465
- }
21466
- });
21467
- ctx.command.transform(async (editor) => {
21468
- if (!editor) return;
21469
- const commands = {
21470
- [AGY_V2_QUOTA_COMMAND]: {
21471
- description: "Show Agy Code Assist quota usage",
21472
- template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21473
- },
21474
- [AGY_V2_QUOTA_SUMMARY_COMMAND]: {
21475
- description: "Show Agy Code Assist quota summary with weekly and 5-hour limits",
21476
- template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21477
- }
21478
- };
21479
- if (typeof editor.add === "function") {
21480
- editor.add({
21481
- name: AGY_V2_QUOTA_COMMAND,
21482
- description: "Display current Antigravity quota usage",
21483
- template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21484
- });
21485
- editor.add({
21486
- name: AGY_V2_QUOTA_SUMMARY_COMMAND,
21487
- description: "Display Antigravity quota summary grouped by model family",
21488
- template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21489
- });
21490
- } else if (typeof editor.set === "function") {
21491
- editor.set(AGY_V2_QUOTA_COMMAND, commands[AGY_V2_QUOTA_COMMAND]);
21492
- editor.set(AGY_V2_QUOTA_SUMMARY_COMMAND, commands[AGY_V2_QUOTA_SUMMARY_COMMAND]);
21493
- } else if (editor.commands && typeof editor.commands === "object") {
21494
- editor.commands[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21495
- editor.commands[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21496
- } else if (typeof editor === "object") {
21497
- editor[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21498
- editor[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21499
- }
21500
- });
21501
- ctx.integration?.transform?.((editor) => {
21502
- if (!editor) return;
21503
- editor.update?.(AGY_PROVIDER_ID, (integration) => {
21504
- integration.name = "Antigravity CLI (plugin)";
21505
- });
21506
- editor.method?.update?.({
21507
- integrationID: AGY_PROVIDER_ID,
21508
- method: {
21509
- id: "oauth",
21510
- type: "oauth",
21511
- label: "Antigravity CLI (OAuth)"
21512
- },
21513
- authorize: async () => {
21514
- const authorization = await authorizeAgy();
21515
- return {
21516
- mode: "code",
21517
- url: authorization.url,
21518
- instructions: "Please complete Google account authorization in your browser. After authorization, copy the full redirect URL or code and paste it below:",
21519
- callback: async (code) => {
21520
- const trimmed = code.trim();
21521
- const parsed = parseOAuthCallbackInput(trimmed);
21522
- const authCode = parsed.code || trimmed;
21523
- if (!authCode) {
21524
- return { type: "failed", error: "Missing authorization code in callback input" };
21525
- }
21526
- if (parsed.state && parsed.state !== authorization.state) {
21527
- return { type: "failed", error: "State mismatch in callback input (possible CSRF attempt)" };
21528
- }
21529
- const exchangeResult = await exchangeAgyWithVerifier(authCode, authorization.verifier);
21530
- if (exchangeResult.type !== "success") {
21531
- return exchangeResult;
21532
- }
21533
- const initialRefresh = formatRefreshParts({
21534
- refreshToken: exchangeResult.refresh
21535
- });
21536
- let authRecord = {
21537
- type: "oauth",
21538
- refresh: initialRefresh,
21539
- access: exchangeResult.access,
21540
- expires: exchangeResult.expires
21541
- };
21542
- try {
21543
- const projectContext = await ensureProjectContext(
21544
- authRecord,
21545
- { auth: { set: async () => {
21546
- } } }
21547
- );
21548
- authRecord = {
21549
- ...authRecord,
21550
- refresh: projectContext.auth.refresh
21551
- };
21552
- } catch {
21553
- }
21554
- saveStoredAuthToJson(authRecord);
21555
- return {
21556
- type: "oauth",
21557
- methodID: "oauth",
21558
- refresh: authRecord.refresh,
21559
- access: authRecord.access,
21560
- expires: authRecord.expires
21561
- };
21562
- }
21563
- };
21564
- }
21565
- });
21566
- });
21567
- ctx.aisdk?.hook("sdk", async (event) => {
21568
- if (!event) return;
21569
- const isMatchingProvider = event.providerID === AGY_PROVIDER_ID || event.model?.providerID === AGY_PROVIDER_ID;
21570
- if (!isMatchingProvider) return;
21571
- event.options = event.options || {};
21572
- event.options.apiKey = "dummy";
21573
- event.options.fetch = createV2FetchInterceptor();
21574
- });
21575
- registerV2SessionHooks(ctx);
20815
+ return value.toString();
21576
20816
  }
21577
- var v2PluginDefinition = defineOpenCodeV2Plugin({
21578
- id: AGY_PROVIDER_ID,
21579
- setup: setupOpenCodeV2
21580
- });
21581
20817
 
21582
20818
  // index.ts
21583
- var dualPlugin = {
21584
- ...v2PluginDefinition,
20819
+ var index_default = {
20820
+ id: "@anthonyhaussman/opencode-agy-auth",
21585
20821
  server: AgyCLIOAuthPlugin
21586
20822
  };
21587
- var index_default = dualPlugin;
21588
20823
  export {
21589
20824
  AgyCLIOAuthPlugin,
21590
20825
  GoogleOAuthPlugin,
21591
- index_default as default,
21592
- defineOpenCodeV2Plugin,
21593
- setupOpenCodeV2,
21594
- v2PluginDefinition
20826
+ index_default as default
21595
20827
  };
21596
20828
  //# sourceMappingURL=index.js.map