@anthonyhaussman/opencode-agy-auth 1.2.16-alpha.0 → 1.2.16-alpha.1

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,6 +579,12 @@ 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
+ };
582
588
 
583
589
  // src/sdk/retry/helpers.ts
584
590
  var DEFAULT_MAX_ATTEMPTS = 3;
@@ -1575,7 +1581,11 @@ function createOAuthAuthorizeMethod(options) {
1575
1581
  const isHeadless = !!(process.env.SSH_CONNECTION || process.env.SSH_CLIENT || process.env.SSH_TTY || process.env.OPENCODE_HEADLESS);
1576
1582
  const authorization = await authorizeAgy();
1577
1583
  if (!isHeadless) {
1578
- openBrowserUrl(authorization.url);
1584
+ if (options?.openBrowser) {
1585
+ options.openBrowser(authorization.url);
1586
+ } else {
1587
+ openBrowserUrl(authorization.url);
1588
+ }
1579
1589
  }
1580
1590
  return {
1581
1591
  url: authorization.url,
@@ -1629,16 +1639,23 @@ function parseOAuthCallbackInput(input) {
1629
1639
  }
1630
1640
  return { code: trimmed };
1631
1641
  }
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;
1632
1650
  function openBrowserUrl(url2) {
1651
+ if ((process.env.NODE_ENV === "test" || process.env.VITEST) && openBrowserLauncher === defaultOpenBrowserLauncher) {
1652
+ return;
1653
+ }
1633
1654
  try {
1634
1655
  const platform2 = process.platform;
1635
1656
  const command = platform2 === "darwin" ? "open" : platform2 === "win32" ? "rundll32" : "xdg-open";
1636
1657
  const args = platform2 === "win32" ? ["url.dll,FileProtocolHandler", url2] : [url2];
1637
- const child = spawn(command, args, {
1638
- stdio: "ignore",
1639
- detached: true
1640
- });
1641
- child.unref?.();
1658
+ openBrowserLauncher(command, args);
1642
1659
  } catch {
1643
1660
  }
1644
1661
  }
@@ -15320,6 +15337,12 @@ function formatRelativeResetTime(resetTime) {
15320
15337
 
15321
15338
  // src/plugin/quota.ts
15322
15339
  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
+ `;
15323
15346
  function createAgyQuotaTool({
15324
15347
  client,
15325
15348
  getAuthResolver,
@@ -15559,6 +15582,12 @@ function splitModelVariant(modelId) {
15559
15582
 
15560
15583
  // src/plugin/quota-summary.ts
15561
15584
  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
+ `;
15562
15591
  function createAgyQuotaSummaryTool({
15563
15592
  client,
15564
15593
  getAuthResolver,
@@ -19928,9 +19957,14 @@ function normalizeToolSchemaTypes(tools, toolMapper) {
19928
19957
  fn.name = toolMapper ? toolMapper.toGemini(fn.name) : sanitizeToolName(fn.name);
19929
19958
  }
19930
19959
  if (fn) {
19960
+ if (!fn.parameters) {
19961
+ fn.parameters = fn.parameters_json_schema ?? fn.parametersJsonSchema;
19962
+ }
19931
19963
  if (!fn.parameters) {
19932
19964
  fn.parameters = { type: "OBJECT", properties: {} };
19933
19965
  }
19966
+ delete fn.parameters_json_schema;
19967
+ delete fn.parametersJsonSchema;
19934
19968
  sanitizeSchema(fn.parameters);
19935
19969
  }
19936
19970
  }
@@ -20355,22 +20389,81 @@ var ChatLoggerImpl = class {
20355
20389
  }
20356
20390
  };
20357
20391
 
20358
- // src/plugin.ts
20359
- var AGY_QUOTA_COMMAND = "agyquota";
20360
- var AGY_QUOTA_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota usage for the current authenticated account.
20361
-
20362
- Immediately call \`${AGY_QUOTA_TOOL_NAME}\` with no arguments and return its output verbatim.
20363
- Do not call other tools.
20364
- `;
20365
- var AGY_QUOTA_SUMMARY_COMMAND = "agyquotasummary";
20366
- 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.
20392
+ // src/plugin/headers.ts
20393
+ function getSafeHeader(headers, key) {
20394
+ if (!headers) {
20395
+ return void 0;
20396
+ }
20397
+ const targetKey = key.toLowerCase();
20398
+ if (typeof headers.get === "function") {
20399
+ try {
20400
+ return headers.get(targetKey) || void 0;
20401
+ } catch {
20402
+ }
20403
+ }
20404
+ if (Array.isArray(headers)) {
20405
+ const found = headers.find((item) => {
20406
+ if (Array.isArray(item) && typeof item[0] === "string") {
20407
+ return item[0].toLowerCase() === targetKey;
20408
+ }
20409
+ return false;
20410
+ });
20411
+ return found ? String(found[1]) : void 0;
20412
+ }
20413
+ if (typeof headers === "object") {
20414
+ const foundKey = Object.keys(headers).find((k) => k.toLowerCase() === targetKey);
20415
+ return foundKey ? headers[foundKey] !== void 0 ? String(headers[foundKey]) : void 0 : void 0;
20416
+ }
20417
+ return void 0;
20418
+ }
20419
+ function setSafeHeaders(initHeaders, newHeaders) {
20420
+ if (typeof globalThis.Headers !== "undefined") {
20421
+ const headers = new globalThis.Headers(initHeaders ?? {});
20422
+ for (const [k, v] of Object.entries(newHeaders)) {
20423
+ headers.set(k, v);
20424
+ }
20425
+ return headers;
20426
+ }
20427
+ if (Array.isArray(initHeaders)) {
20428
+ const nextHeaders2 = [...initHeaders];
20429
+ for (const [k, v] of Object.entries(newHeaders)) {
20430
+ const idx = nextHeaders2.findIndex((item) => Array.isArray(item) && typeof item[0] === "string" && item[0].toLowerCase() === k.toLowerCase());
20431
+ if (idx !== -1) {
20432
+ nextHeaders2[idx] = [k, v];
20433
+ } else {
20434
+ nextHeaders2.push([k, v]);
20435
+ }
20436
+ }
20437
+ return nextHeaders2;
20438
+ }
20439
+ const nextHeaders = {};
20440
+ if (initHeaders && typeof initHeaders === "object") {
20441
+ for (const [k, v] of Object.entries(initHeaders)) {
20442
+ nextHeaders[k] = String(v);
20443
+ }
20444
+ }
20445
+ for (const [k, v] of Object.entries(newHeaders)) {
20446
+ const existingKey = Object.keys(nextHeaders).find((key) => key.toLowerCase() === k.toLowerCase());
20447
+ if (existingKey) {
20448
+ nextHeaders[existingKey] = v;
20449
+ } else {
20450
+ nextHeaders[k] = v;
20451
+ }
20452
+ }
20453
+ return nextHeaders;
20454
+ }
20455
+ function toUrlString(value) {
20456
+ if (typeof value === "string") {
20457
+ return value;
20458
+ }
20459
+ const candidate = value.url;
20460
+ if (candidate) {
20461
+ return candidate;
20462
+ }
20463
+ return value.toString();
20464
+ }
20367
20465
 
20368
- Immediately call \`${AGY_QUOTA_SUMMARY_TOOL_NAME}\` with no arguments and return its output verbatim.
20369
- Do not call other tools.
20370
- `;
20371
- var latestAgyAuthResolver;
20372
- var latestAgyConfiguredProjectId;
20373
- var latestAgyUserAgentModel;
20466
+ // src/plugin/tier.ts
20374
20467
  var STATIC_MODELS_SIMPLE = {
20375
20468
  "gemini-3.8-flash": {
20376
20469
  name: "Gemini 3.8 Flash",
@@ -20468,6 +20561,39 @@ var TIER_MAPPING = {
20468
20561
  high: "claude-sonnet-5-5-high"
20469
20562
  }
20470
20563
  };
20564
+ function resolveModelTier(baseModelId, headersOrInit) {
20565
+ const parts = baseModelId.split("@");
20566
+ const base = parts[0] || "";
20567
+ const suffixTier = parts[1]?.toLowerCase();
20568
+ const mapping = TIER_MAPPING[base];
20569
+ if (!mapping) {
20570
+ return baseModelId;
20571
+ }
20572
+ const rawHeaders = headersOrInit && typeof headersOrInit === "object" && "headers" in headersOrInit ? headersOrInit.headers : headersOrInit;
20573
+ const headerTier = getSafeHeader(rawHeaders, "x-agy-tier")?.toLowerCase() || null;
20574
+ const requestedTier = headerTier || suffixTier;
20575
+ if (requestedTier && Object.prototype.hasOwnProperty.call(mapping, requestedTier)) {
20576
+ return mapping[requestedTier] || baseModelId;
20577
+ }
20578
+ return mapping["medium"] ?? mapping["high"] ?? baseModelId;
20579
+ }
20580
+
20581
+ // src/plugin.ts
20582
+ var AGY_QUOTA_COMMAND = "agyquota";
20583
+ var AGY_QUOTA_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota usage for the current authenticated account.
20584
+
20585
+ Immediately call \`${AGY_QUOTA_TOOL_NAME}\` with no arguments and return its output verbatim.
20586
+ Do not call other tools.
20587
+ `;
20588
+ var AGY_QUOTA_SUMMARY_COMMAND = "agyquotasummary";
20589
+ 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.
20590
+
20591
+ Immediately call \`${AGY_QUOTA_SUMMARY_TOOL_NAME}\` with no arguments and return its output verbatim.
20592
+ Do not call other tools.
20593
+ `;
20594
+ var latestAgyAuthResolver;
20595
+ var latestAgyConfiguredProjectId;
20596
+ var latestAgyUserAgentModel;
20471
20597
  var buildModelFromSimple = (modelId, simple) => {
20472
20598
  const isClaude = modelId.startsWith("claude-");
20473
20599
  const isGpt = modelId.startsWith("gpt-");
@@ -20561,83 +20687,6 @@ var STATIC_MODELS = {};
20561
20687
  for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
20562
20688
  STATIC_MODELS[modelId] = buildModelFromSimple(modelId, simple);
20563
20689
  }
20564
- function getSafeHeader(headers, key) {
20565
- if (!headers) {
20566
- return void 0;
20567
- }
20568
- const targetKey = key.toLowerCase();
20569
- if (typeof headers.get === "function") {
20570
- try {
20571
- return headers.get(targetKey) || void 0;
20572
- } catch {
20573
- }
20574
- }
20575
- if (Array.isArray(headers)) {
20576
- const found = headers.find((item) => {
20577
- if (Array.isArray(item) && typeof item[0] === "string") {
20578
- return item[0].toLowerCase() === targetKey;
20579
- }
20580
- return false;
20581
- });
20582
- return found ? String(found[1]) : void 0;
20583
- }
20584
- if (typeof headers === "object") {
20585
- const foundKey = Object.keys(headers).find((k) => k.toLowerCase() === targetKey);
20586
- return foundKey ? headers[foundKey] !== void 0 ? String(headers[foundKey]) : void 0 : void 0;
20587
- }
20588
- return void 0;
20589
- }
20590
- function setSafeHeaders(initHeaders, newHeaders) {
20591
- if (typeof globalThis.Headers !== "undefined") {
20592
- const headers = new globalThis.Headers(initHeaders ?? {});
20593
- for (const [k, v] of Object.entries(newHeaders)) {
20594
- headers.set(k, v);
20595
- }
20596
- return headers;
20597
- }
20598
- if (Array.isArray(initHeaders)) {
20599
- const nextHeaders2 = [...initHeaders];
20600
- for (const [k, v] of Object.entries(newHeaders)) {
20601
- const idx = nextHeaders2.findIndex((item) => Array.isArray(item) && typeof item[0] === "string" && item[0].toLowerCase() === k.toLowerCase());
20602
- if (idx !== -1) {
20603
- nextHeaders2[idx] = [k, v];
20604
- } else {
20605
- nextHeaders2.push([k, v]);
20606
- }
20607
- }
20608
- return nextHeaders2;
20609
- }
20610
- const nextHeaders = {};
20611
- if (initHeaders && typeof initHeaders === "object") {
20612
- for (const [k, v] of Object.entries(initHeaders)) {
20613
- nextHeaders[k] = String(v);
20614
- }
20615
- }
20616
- for (const [k, v] of Object.entries(newHeaders)) {
20617
- const existingKey = Object.keys(nextHeaders).find((key) => key.toLowerCase() === k.toLowerCase());
20618
- if (existingKey) {
20619
- nextHeaders[existingKey] = v;
20620
- } else {
20621
- nextHeaders[k] = v;
20622
- }
20623
- }
20624
- return nextHeaders;
20625
- }
20626
- function resolveModelTier(baseModelId, init) {
20627
- const parts = baseModelId.split("@");
20628
- const base = parts[0] || "";
20629
- const suffixTier = parts[1]?.toLowerCase();
20630
- const mapping = TIER_MAPPING[base];
20631
- if (!mapping) {
20632
- return baseModelId;
20633
- }
20634
- const headerTier = getSafeHeader(init?.headers, "x-agy-tier")?.toLowerCase() || null;
20635
- const requestedTier = headerTier || suffixTier;
20636
- if (requestedTier && Object.prototype.hasOwnProperty.call(mapping, requestedTier)) {
20637
- return mapping[requestedTier] || baseModelId;
20638
- }
20639
- return mapping["medium"] ?? mapping["high"];
20640
- }
20641
20690
  var AgyCLIOAuthPlugin = async ({ client }) => {
20642
20691
  let latestConfig;
20643
20692
  updateStaticModelsWithPricing(STATIC_MODELS);
@@ -20965,25 +21014,782 @@ async function ensureProjectContextOrThrow(authRecord, client, configuredProject
20965
21014
  throw error45;
20966
21015
  }
20967
21016
  }
20968
- function toUrlString(value) {
20969
- if (typeof value === "string") {
20970
- return value;
21017
+
21018
+ // src/plugin/types.ts
21019
+ function defineOpenCodeV2Plugin(def) {
21020
+ return def;
21021
+ }
21022
+
21023
+ // src/plugin/v2-storage.ts
21024
+ import { closeSync, existsSync as existsSync6, mkdirSync as mkdirSync5, openSync, readFileSync as readFileSync5, renameSync as renameSync4, unlinkSync as unlinkSync4, writeFileSync as writeFileSync5 } from "fs";
21025
+ import { randomUUID as randomUUID4 } from "crypto";
21026
+ import { homedir as homedir4 } from "os";
21027
+ import { join as join6 } from "path";
21028
+ var storedAuthOverrideForTesting = void 0;
21029
+ function loadStoredAuthFromJson() {
21030
+ if (storedAuthOverrideForTesting !== void 0) {
21031
+ return storedAuthOverrideForTesting;
21032
+ }
21033
+ const authPath = join6(homedir4(), ".local", "share", "opencode", "auth.json");
21034
+ try {
21035
+ if (existsSync6(authPath)) {
21036
+ const content = readFileSync5(authPath, "utf8");
21037
+ const data = JSON.parse(content);
21038
+ return data?.[AGY_PROVIDER_ID];
21039
+ }
21040
+ } catch {
20971
21041
  }
20972
- const candidate = value.url;
20973
- if (candidate) {
20974
- return candidate;
21042
+ return void 0;
21043
+ }
21044
+ function saveStoredAuthToJson(authRecord) {
21045
+ if (process.env.NODE_ENV === "test" || process.env.VITEST || storedAuthOverrideForTesting !== void 0) {
21046
+ return;
20975
21047
  }
20976
- return value.toString();
21048
+ const dirPath = join6(homedir4(), ".local", "share", "opencode");
21049
+ if (!existsSync6(dirPath)) {
21050
+ mkdirSync5(dirPath, { recursive: true });
21051
+ }
21052
+ const authPath = join6(dirPath, "auth.json");
21053
+ const data = existsSync6(authPath) ? JSON.parse(readFileSync5(authPath, "utf8")) : {};
21054
+ data[AGY_PROVIDER_ID] = {
21055
+ type: "oauth",
21056
+ refresh: authRecord.refresh,
21057
+ access: authRecord.access,
21058
+ expires: authRecord.expires
21059
+ };
21060
+ const tempPath = `${authPath}.${process.pid}.${randomUUID4()}.tmp`;
21061
+ let tempFileDescriptor;
21062
+ let ownsTempFile = false;
21063
+ try {
21064
+ tempFileDescriptor = openSync(tempPath, "wx", 384);
21065
+ ownsTempFile = true;
21066
+ writeFileSync5(tempFileDescriptor, JSON.stringify(data, null, 2), {
21067
+ encoding: "utf8"
21068
+ });
21069
+ closeSync(tempFileDescriptor);
21070
+ tempFileDescriptor = void 0;
21071
+ renameSync4(tempPath, authPath);
21072
+ } catch (error45) {
21073
+ if (tempFileDescriptor !== void 0) {
21074
+ try {
21075
+ closeSync(tempFileDescriptor);
21076
+ } catch {
21077
+ }
21078
+ }
21079
+ if (ownsTempFile) {
21080
+ try {
21081
+ unlinkSync4(tempPath);
21082
+ } catch {
21083
+ }
21084
+ }
21085
+ throw error45;
21086
+ }
21087
+ }
21088
+
21089
+ // src/plugin/v2-fetch.ts
21090
+ function createV2FetchInterceptor(getAuthSnapshot) {
21091
+ return async function agyV2Fetch(input, init) {
21092
+ const isGL = isGenerativeLanguageRequest(input);
21093
+ const isInternal = toUrlString(input).includes("cloudcode-pa.googleapis.com");
21094
+ if (!isGL && !isInternal) {
21095
+ return (globalThis.fetch || fetch)(input, init);
21096
+ }
21097
+ let rawAuth = getAuthSnapshot ? await getAuthSnapshot() : void 0;
21098
+ if (!rawAuth) {
21099
+ rawAuth = loadStoredAuthFromJson();
21100
+ }
21101
+ if (!rawAuth || !isOAuthAuth(rawAuth)) {
21102
+ return (globalThis.fetch || fetch)(input, init);
21103
+ }
21104
+ let authRecord = resolveCachedAuth(rawAuth);
21105
+ if (accessTokenExpired(authRecord)) {
21106
+ const refreshed = await refreshAccessToken(authRecord, { auth: { set: async () => {
21107
+ } } });
21108
+ if (refreshed) {
21109
+ authRecord = refreshed;
21110
+ }
21111
+ }
21112
+ if (!authRecord.access) {
21113
+ return (globalThis.fetch || fetch)(input, init);
21114
+ }
21115
+ if (isInternal) {
21116
+ const hasAuth = getSafeHeader(init?.headers, "Authorization") !== void 0;
21117
+ if (hasAuth) {
21118
+ return (globalThis.fetch || fetch)(input, init);
21119
+ }
21120
+ const userAgent = buildAgyCliUserAgent();
21121
+ const headers = setSafeHeaders(init?.headers, {
21122
+ Authorization: `Bearer ${authRecord.access}`,
21123
+ "User-Agent": userAgent
21124
+ });
21125
+ return (globalThis.fetch || fetch)(input, {
21126
+ ...init,
21127
+ headers
21128
+ });
21129
+ }
21130
+ const requestTarget = parseGenerativeLanguageRequest(input);
21131
+ const requestUserAgentModel = requestTarget?.effectiveModel;
21132
+ let projectContext;
21133
+ try {
21134
+ projectContext = await ensureProjectContext(
21135
+ authRecord,
21136
+ { auth: { set: async () => {
21137
+ } } },
21138
+ void 0,
21139
+ requestUserAgentModel
21140
+ );
21141
+ } catch {
21142
+ projectContext = {
21143
+ effectiveProjectId: parseRefreshParts(authRecord.refresh).projectId || "antigravity",
21144
+ auth: authRecord
21145
+ };
21146
+ }
21147
+ const originalRequestedModel = parseGenerativeLanguageRequest(input)?.effectiveModel;
21148
+ let modifiedInput = input;
21149
+ if (isGL && originalRequestedModel) {
21150
+ const originalBase = originalRequestedModel.replace("google-agy/", "");
21151
+ const resolvedBase = resolveModelTier(originalBase, init);
21152
+ if (originalBase !== resolvedBase) {
21153
+ if (typeof modifiedInput === "string") {
21154
+ modifiedInput = modifiedInput.replace(`models/${originalBase}`, `models/${resolvedBase}`);
21155
+ } else if (typeof Request !== "undefined" && modifiedInput instanceof Request) {
21156
+ const newUrl = modifiedInput.url.replace(`models/${originalBase}`, `models/${resolvedBase}`);
21157
+ modifiedInput = new Request(newUrl, modifiedInput);
21158
+ }
21159
+ }
21160
+ }
21161
+ const transformed = prepareAgyRequest(
21162
+ modifiedInput,
21163
+ init,
21164
+ authRecord.access,
21165
+ projectContext.effectiveProjectId,
21166
+ void 0
21167
+ );
21168
+ const chatLogger = createChatLogger();
21169
+ if (chatLogger) {
21170
+ chatLogger.logRequest(
21171
+ toUrlString(transformed.request),
21172
+ transformed.init.method || "GET",
21173
+ transformed.init.headers,
21174
+ transformed.init.body
21175
+ );
21176
+ }
21177
+ const response = await fetchWithRetry(transformed.request, transformed.init);
21178
+ return transformAgyResponse(
21179
+ response,
21180
+ transformed.streaming,
21181
+ null,
21182
+ transformed.requestedModel,
21183
+ transformed.sessionId,
21184
+ chatLogger
21185
+ );
21186
+ };
20977
21187
  }
20978
21188
 
21189
+ // src/plugin/v2-session.ts
21190
+ function createV2HttpRequestHook(state = {}) {
21191
+ return async (event) => {
21192
+ if (!event) return;
21193
+ const rawUrl = typeof event.url === "string" ? event.url : event.request?.url || "";
21194
+ const isGL = isGenerativeLanguageRequest(rawUrl);
21195
+ const isInternal = rawUrl.includes("cloudcode-pa.googleapis.com");
21196
+ if (!isGL && !isInternal) {
21197
+ return;
21198
+ }
21199
+ event.headers = event.headers || {};
21200
+ let modelName;
21201
+ let rawAuth = event.auth;
21202
+ if (rawAuth && !rawAuth.type) {
21203
+ const tokenVal = rawAuth.access || rawAuth.token;
21204
+ if (tokenVal || rawAuth.refresh) {
21205
+ rawAuth = { type: "oauth", access: tokenVal, ...rawAuth };
21206
+ }
21207
+ }
21208
+ if (!rawAuth || !isOAuthAuth(rawAuth)) {
21209
+ rawAuth = loadStoredAuthFromJson();
21210
+ }
21211
+ let authRecord = rawAuth && isOAuthAuth(rawAuth) ? resolveCachedAuth(rawAuth) : void 0;
21212
+ if (authRecord && accessTokenExpired(authRecord)) {
21213
+ const refreshed = await refreshAccessToken(authRecord, { auth: { set: async () => {
21214
+ } } });
21215
+ if (refreshed) {
21216
+ authRecord = refreshed;
21217
+ try {
21218
+ saveStoredAuthToJson(refreshed);
21219
+ } catch {
21220
+ console.warn("[Agy Auth] Refreshed credentials could not be persisted; the current request will continue.");
21221
+ }
21222
+ }
21223
+ }
21224
+ if (isGL) {
21225
+ const parsed = parseGenerativeLanguageRequest(rawUrl);
21226
+ modelName = parsed?.effectiveModel;
21227
+ if (modelName) {
21228
+ state.lastInterceptedModel = modelName;
21229
+ }
21230
+ if (typeof event.headers.delete === "function") {
21231
+ event.headers.delete("x-goog-api-key");
21232
+ event.headers.delete("api-key");
21233
+ } else {
21234
+ for (const key of Object.keys(event.headers)) {
21235
+ const lower = key.toLowerCase();
21236
+ if (lower === "x-goog-api-key" || lower === "api-key") {
21237
+ delete event.headers[key];
21238
+ }
21239
+ }
21240
+ }
21241
+ if (event.request?.headers) {
21242
+ if (typeof event.request.headers.delete === "function") {
21243
+ event.request.headers.delete("x-goog-api-key");
21244
+ event.request.headers.delete("api-key");
21245
+ } else {
21246
+ for (const key of Object.keys(event.request.headers)) {
21247
+ const lower = key.toLowerCase();
21248
+ if (lower === "x-goog-api-key" || lower === "api-key") {
21249
+ delete event.request.headers[key];
21250
+ }
21251
+ }
21252
+ }
21253
+ }
21254
+ let cleanUrl = rawUrl;
21255
+ try {
21256
+ const parsedUrl = new URL(rawUrl);
21257
+ let urlChanged = false;
21258
+ for (const param of ["key", "x-goog-api-key", "api-key"]) {
21259
+ if (parsedUrl.searchParams.has(param)) {
21260
+ parsedUrl.searchParams.delete(param);
21261
+ urlChanged = true;
21262
+ }
21263
+ }
21264
+ if (urlChanged) {
21265
+ cleanUrl = parsedUrl.toString();
21266
+ }
21267
+ } catch {
21268
+ }
21269
+ if (authRecord && authRecord.access) {
21270
+ let projectContext;
21271
+ try {
21272
+ projectContext = await ensureProjectContext(
21273
+ authRecord,
21274
+ { auth: { set: async () => {
21275
+ } } },
21276
+ void 0,
21277
+ modelName
21278
+ );
21279
+ } catch {
21280
+ projectContext = {
21281
+ effectiveProjectId: parseRefreshParts(authRecord.refresh).projectId || "antigravity",
21282
+ auth: authRecord
21283
+ };
21284
+ }
21285
+ const originalRequestedModel = modelName;
21286
+ let modifiedUrl = cleanUrl;
21287
+ if (originalRequestedModel) {
21288
+ const originalBase = originalRequestedModel.replace("google-agy/", "");
21289
+ const initHeaders = event.headers instanceof Headers ? event.headers : event.request?.headers;
21290
+ const resolvedBase = resolveModelTier(originalBase, { headers: initHeaders });
21291
+ if (originalBase !== resolvedBase) {
21292
+ modifiedUrl = modifiedUrl.replace(`models/${originalBase}`, `models/${resolvedBase}`);
21293
+ }
21294
+ }
21295
+ let bodyPayload = event.body;
21296
+ if (bodyPayload === void 0 && event.request) {
21297
+ if (typeof event.request.clone === "function") {
21298
+ try {
21299
+ bodyPayload = await event.request.clone().text();
21300
+ } catch {
21301
+ }
21302
+ } else if (event.request.body !== void 0) {
21303
+ bodyPayload = event.request.body;
21304
+ }
21305
+ }
21306
+ let preExistingUserAgent;
21307
+ if (typeof event.headers?.get === "function") {
21308
+ preExistingUserAgent = event.headers.get("user-agent") || event.headers.get("User-Agent") || void 0;
21309
+ } else if (event.headers && typeof event.headers === "object") {
21310
+ preExistingUserAgent = event.headers["user-agent"] || event.headers["User-Agent"] || void 0;
21311
+ }
21312
+ if (!preExistingUserAgent && typeof event.request?.headers?.get === "function") {
21313
+ preExistingUserAgent = event.request.headers.get("user-agent") || event.request.headers.get("User-Agent") || void 0;
21314
+ } else if (!preExistingUserAgent && event.request?.headers && typeof event.request.headers === "object") {
21315
+ preExistingUserAgent = event.request.headers["user-agent"] || event.request.headers["User-Agent"] || void 0;
21316
+ }
21317
+ const method = event.method || event.request?.method || "POST";
21318
+ const requestHeaders = event.headers || event.request?.headers;
21319
+ const transformed = prepareAgyRequest(
21320
+ modifiedUrl,
21321
+ {
21322
+ method,
21323
+ headers: requestHeaders,
21324
+ body: bodyPayload
21325
+ },
21326
+ authRecord.access,
21327
+ projectContext.effectiveProjectId
21328
+ );
21329
+ const targetUrl = toUrlString(transformed.request);
21330
+ if (typeof event.url === "string") {
21331
+ event.url = targetUrl;
21332
+ }
21333
+ if (event.request && typeof event.request === "object") {
21334
+ if (typeof Request !== "undefined" && event.request instanceof Request) {
21335
+ event.request = new Request(targetUrl, {
21336
+ method: transformed.init.method,
21337
+ headers: transformed.init.headers,
21338
+ body: transformed.init.body
21339
+ });
21340
+ } else if (typeof event.request.url === "string") {
21341
+ try {
21342
+ event.request.url = targetUrl;
21343
+ } catch {
21344
+ }
21345
+ }
21346
+ }
21347
+ const headerEntries = transformed.init.headers instanceof Headers ? Array.from(transformed.init.headers.entries()) : Object.entries(transformed.init.headers || {});
21348
+ for (const [k, v] of headerEntries) {
21349
+ const lowerK = k.toLowerCase();
21350
+ if (lowerK === "user-agent") {
21351
+ if (preExistingUserAgent) {
21352
+ continue;
21353
+ }
21354
+ if (typeof event.headers?.set === "function") {
21355
+ event.headers.set("User-Agent", v);
21356
+ } else if (event.headers) {
21357
+ event.headers["User-Agent"] = v;
21358
+ }
21359
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21360
+ event.request.headers.set("User-Agent", v);
21361
+ } else if (event.request?.headers && typeof event.request.headers === "object") {
21362
+ event.request.headers["User-Agent"] = v;
21363
+ }
21364
+ continue;
21365
+ }
21366
+ if (typeof event.headers?.set === "function") {
21367
+ event.headers.set(k, v);
21368
+ } else if (event.headers) {
21369
+ event.headers[k] = v;
21370
+ }
21371
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21372
+ event.request.headers.set(k, v);
21373
+ } else if (event.request?.headers && typeof event.request.headers === "object") {
21374
+ event.request.headers[k] = v;
21375
+ }
21376
+ }
21377
+ if (transformed.init.body !== void 0) {
21378
+ event.body = transformed.init.body;
21379
+ if (event.request && typeof event.request === "object" && !(event.request instanceof Request)) {
21380
+ event.request.body = transformed.init.body;
21381
+ }
21382
+ }
21383
+ } else {
21384
+ if (typeof event.url === "string") {
21385
+ event.url = cleanUrl;
21386
+ }
21387
+ if (event.request && typeof event.request === "object") {
21388
+ if (typeof Request !== "undefined" && event.request instanceof Request) {
21389
+ event.request = new Request(cleanUrl, event.request);
21390
+ } else if (typeof event.request.url === "string") {
21391
+ try {
21392
+ event.request.url = cleanUrl;
21393
+ } catch {
21394
+ }
21395
+ }
21396
+ }
21397
+ }
21398
+ }
21399
+ if (authRecord && authRecord.access) {
21400
+ if (typeof event.headers?.set === "function") {
21401
+ event.headers.set("Authorization", `Bearer ${authRecord.access}`);
21402
+ } else if (event.headers) {
21403
+ event.headers["Authorization"] = `Bearer ${authRecord.access}`;
21404
+ }
21405
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21406
+ event.request.headers.set("Authorization", `Bearer ${authRecord.access}`);
21407
+ } else if (event.request?.headers && typeof event.request.headers === "object") {
21408
+ event.request.headers["Authorization"] = `Bearer ${authRecord.access}`;
21409
+ }
21410
+ }
21411
+ const userAgent = buildAgyCliUserAgent(modelName);
21412
+ if (typeof event.headers?.set === "function") {
21413
+ if (!event.headers.get("User-Agent") && !event.headers.get("user-agent")) {
21414
+ event.headers.set("User-Agent", userAgent);
21415
+ }
21416
+ } else if (event.headers) {
21417
+ if (!event.headers["User-Agent"] && !event.headers["user-agent"]) {
21418
+ event.headers["User-Agent"] = userAgent;
21419
+ }
21420
+ }
21421
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21422
+ if (!event.request.headers.get("User-Agent") && !event.request.headers.get("user-agent")) {
21423
+ event.request.headers.set("User-Agent", userAgent);
21424
+ }
21425
+ } else if (event.request?.headers && typeof event.request.headers === "object") {
21426
+ if (!event.request.headers["User-Agent"] && !event.request.headers["user-agent"]) {
21427
+ event.request.headers["User-Agent"] = userAgent;
21428
+ }
21429
+ }
21430
+ };
21431
+ }
21432
+ function createV2HttpResponseHook(state = {}) {
21433
+ return async (event) => {
21434
+ if (!event || !event.response) return;
21435
+ const rawUrl = typeof event.url === "string" ? event.url : event.request?.url || "";
21436
+ const isInternal = rawUrl.includes("cloudcode-pa.googleapis.com");
21437
+ if (isInternal && event.response instanceof Response) {
21438
+ const isStreaming = rawUrl.includes(":streamGenerateCode") || event.response.headers.get("content-type")?.includes("text/event-stream");
21439
+ const parsedModel = parseGenerativeLanguageRequest(rawUrl)?.effectiveModel || state.lastInterceptedModel;
21440
+ const transformed = await transformAgyResponse(
21441
+ event.response,
21442
+ !!isStreaming,
21443
+ null,
21444
+ parsedModel,
21445
+ void 0,
21446
+ void 0
21447
+ );
21448
+ event.response = transformed;
21449
+ }
21450
+ };
21451
+ }
21452
+ function createV2RetryHook() {
21453
+ return async (event) => {
21454
+ if (!event) return;
21455
+ const response = event.response;
21456
+ if (response instanceof Response) {
21457
+ if (response.status === 429 || response.status === 503) {
21458
+ const quota = await classifyQuotaResponse(response);
21459
+ if (quota?.retryDelayMs) {
21460
+ event.retryDelayMs = quota.retryDelayMs;
21461
+ } else {
21462
+ event.retryDelayMs = await resolveRetryDelayMs(response, event.attempt || 1);
21463
+ }
21464
+ }
21465
+ } else if (event.details && Array.isArray(event.details)) {
21466
+ const retryInfo = event.details.find(
21467
+ (d) => d && d["@type"] === "type.googleapis.com/google.rpc.RetryInfo"
21468
+ );
21469
+ if (retryInfo?.retryDelay) {
21470
+ const delayMs = retryInternals.parseRetryDelayValue(retryInfo.retryDelay);
21471
+ if (delayMs !== null) {
21472
+ event.retryDelayMs = delayMs;
21473
+ }
21474
+ }
21475
+ }
21476
+ };
21477
+ }
21478
+ function registerV2SessionHooks(ctx) {
21479
+ const state = {};
21480
+ ctx.session.hook("http.request", createV2HttpRequestHook(state), { providerID: AGY_PROVIDER_ID });
21481
+ ctx.session.hook("http.response", createV2HttpResponseHook(state), { providerID: AGY_PROVIDER_ID });
21482
+ ctx.session.hook("retry", createV2RetryHook(), { providerID: AGY_PROVIDER_ID });
21483
+ }
21484
+
21485
+ // src/plugin/v2.ts
21486
+ async function setupOpenCodeV2(ctx) {
21487
+ const resolveVariants = (modelId) => {
21488
+ const mapping = TIER_MAPPING[modelId];
21489
+ if (!mapping) return void 0;
21490
+ const variants = [];
21491
+ if (mapping.minimal !== void 0) variants.push({ id: "minimal" });
21492
+ if (mapping.low !== void 0) variants.push({ id: "low" });
21493
+ if (mapping.medium !== void 0) variants.push({ id: "medium" });
21494
+ if (mapping.high !== void 0) variants.push({ id: "high" });
21495
+ return variants.length > 0 ? variants : void 0;
21496
+ };
21497
+ const updateProviderRecord = (p) => {
21498
+ p.name = "Antigravity CLI";
21499
+ p.activation = "enabled";
21500
+ p.package = "aisdk:@ai-sdk/google";
21501
+ p.description = "Google Gemini Antigravity Code Assist OAuth provider";
21502
+ p.settings = { ...p.settings || {}, apiKey: "dummy" };
21503
+ p.integrationID = AGY_PROVIDER_ID;
21504
+ };
21505
+ const buildModelRecord = (modelId, simple, existingModel) => {
21506
+ const isClaude = modelId.startsWith("claude-");
21507
+ const isGpt = modelId.startsWith("gpt-");
21508
+ const variants = resolveVariants(modelId);
21509
+ return {
21510
+ id: modelId,
21511
+ providerID: AGY_PROVIDER_ID,
21512
+ name: simple.name,
21513
+ description: simple.description,
21514
+ family: modelId.includes("gemini") ? "gemini" : isClaude ? "claude" : isGpt ? "gpt" : "unknown",
21515
+ reasoning: simple.reasoning,
21516
+ attachment: simple.attachment,
21517
+ tool_call: simple.toolCall,
21518
+ limit: {
21519
+ context: simple.maxTokens,
21520
+ output: simple.maxOutputTokens
21521
+ },
21522
+ cost: simple.cost || { input: 0, output: 0 },
21523
+ ...variants ? { variants } : {},
21524
+ ...existingModel || {}
21525
+ };
21526
+ };
21527
+ const updateModelRecord = (m, modelId, simple) => {
21528
+ m.name = simple.name;
21529
+ m.capabilities = {
21530
+ tools: true,
21531
+ input: ["text", "image"],
21532
+ output: ["text"]
21533
+ };
21534
+ m.limit = {
21535
+ context: simple.maxTokens,
21536
+ output: simple.maxOutputTokens
21537
+ };
21538
+ m.family = "gemini";
21539
+ if (simple.cost) {
21540
+ m.cost = simple.cost;
21541
+ }
21542
+ const variants = resolveVariants(modelId);
21543
+ if (variants) {
21544
+ m.variants = variants;
21545
+ }
21546
+ };
21547
+ if (ctx.provider?.transform) {
21548
+ ctx.provider.transform(async (editor) => {
21549
+ if (!editor) return;
21550
+ if (typeof editor.update === "function") {
21551
+ editor.update(AGY_PROVIDER_ID, updateProviderRecord);
21552
+ } else if (typeof editor.set === "function") {
21553
+ const p = { id: AGY_PROVIDER_ID };
21554
+ updateProviderRecord(p);
21555
+ editor.set(AGY_PROVIDER_ID, p);
21556
+ } else if (typeof editor === "object") {
21557
+ const p = editor[AGY_PROVIDER_ID] || { id: AGY_PROVIDER_ID };
21558
+ updateProviderRecord(p);
21559
+ editor[AGY_PROVIDER_ID] = p;
21560
+ }
21561
+ });
21562
+ }
21563
+ if (ctx.model?.transform) {
21564
+ ctx.model.transform(async (editor) => {
21565
+ if (!editor) return;
21566
+ if (typeof editor.update === "function") {
21567
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21568
+ editor.update(AGY_PROVIDER_ID, modelId, (m) => updateModelRecord(m, modelId, simple));
21569
+ }
21570
+ } else if (typeof editor.set === "function") {
21571
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21572
+ const m = buildModelRecord(modelId, simple);
21573
+ editor.set(`${AGY_PROVIDER_ID}:${modelId}`, m);
21574
+ }
21575
+ } else if (typeof editor === "object") {
21576
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21577
+ const key = `${AGY_PROVIDER_ID}:${modelId}`;
21578
+ editor[key] = buildModelRecord(modelId, simple, editor[key]);
21579
+ }
21580
+ }
21581
+ });
21582
+ }
21583
+ if (ctx.catalog?.transform) {
21584
+ ctx.catalog.transform(async (editor) => {
21585
+ if (!editor) return;
21586
+ if (typeof editor?.provider?.update === "function") {
21587
+ editor.provider.update(AGY_PROVIDER_ID, updateProviderRecord);
21588
+ if (typeof editor?.model?.update === "function") {
21589
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21590
+ editor.model.update(AGY_PROVIDER_ID, modelId, (m) => updateModelRecord(m, modelId, simple));
21591
+ }
21592
+ }
21593
+ return;
21594
+ }
21595
+ const catalog = editor;
21596
+ catalog.providers = catalog.providers || {};
21597
+ catalog.providers[AGY_PROVIDER_ID] = {
21598
+ id: AGY_PROVIDER_ID,
21599
+ name: "Antigravity CLI",
21600
+ npm: "aisdk:@ai-sdk/google",
21601
+ settings: { apiKey: "dummy" },
21602
+ integrationID: AGY_PROVIDER_ID,
21603
+ models: { ...catalog.providers[AGY_PROVIDER_ID]?.models || {} },
21604
+ ...catalog.providers[AGY_PROVIDER_ID]
21605
+ };
21606
+ if (catalog.providers[AGY_PROVIDER_ID].settings) {
21607
+ catalog.providers[AGY_PROVIDER_ID].settings = {
21608
+ ...catalog.providers[AGY_PROVIDER_ID].settings,
21609
+ apiKey: "dummy"
21610
+ };
21611
+ } else {
21612
+ catalog.providers[AGY_PROVIDER_ID].settings = { apiKey: "dummy" };
21613
+ }
21614
+ catalog.providers[AGY_PROVIDER_ID].integrationID = AGY_PROVIDER_ID;
21615
+ const targetModels = catalog.providers[AGY_PROVIDER_ID].models;
21616
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21617
+ targetModels[modelId] = buildModelRecord(modelId, simple, targetModels[modelId]);
21618
+ }
21619
+ });
21620
+ }
21621
+ ctx.tool.transform(async (editor) => {
21622
+ if (!editor) return;
21623
+ const quotaTool = createAgyQuotaTool({
21624
+ client: void 0,
21625
+ getAuthResolver: () => void 0,
21626
+ getConfiguredProjectId: () => void 0,
21627
+ getUserAgentModel: () => void 0
21628
+ });
21629
+ const quotaSummaryTool = createAgyQuotaSummaryTool({
21630
+ client: void 0,
21631
+ getAuthResolver: () => void 0,
21632
+ getConfiguredProjectId: () => void 0,
21633
+ getUserAgentModel: () => void 0
21634
+ });
21635
+ if (typeof editor.add === "function") {
21636
+ editor.add({
21637
+ name: AGY_QUOTA_TOOL_NAME,
21638
+ description: quotaTool.description,
21639
+ input: {},
21640
+ execute: async (args, context) => quotaTool.execute(args, context)
21641
+ });
21642
+ editor.add({
21643
+ name: AGY_QUOTA_SUMMARY_TOOL_NAME,
21644
+ description: quotaSummaryTool.description,
21645
+ input: {},
21646
+ execute: async (args, context) => quotaSummaryTool.execute(args, context)
21647
+ });
21648
+ } else if (typeof editor.set === "function") {
21649
+ editor.set(AGY_QUOTA_TOOL_NAME, quotaTool);
21650
+ editor.set(AGY_QUOTA_SUMMARY_TOOL_NAME, quotaSummaryTool);
21651
+ } else if (editor.tools && typeof editor.tools === "object") {
21652
+ editor.tools[AGY_QUOTA_TOOL_NAME] = quotaTool;
21653
+ editor.tools[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21654
+ } else if (typeof editor === "object") {
21655
+ editor[AGY_QUOTA_TOOL_NAME] = quotaTool;
21656
+ editor[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21657
+ }
21658
+ });
21659
+ ctx.command.transform(async (editor) => {
21660
+ if (!editor) return;
21661
+ const commands = {
21662
+ [AGY_V2_QUOTA_COMMAND]: {
21663
+ description: "Show Agy Code Assist quota usage",
21664
+ template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21665
+ },
21666
+ [AGY_V2_QUOTA_SUMMARY_COMMAND]: {
21667
+ description: "Show Agy Code Assist quota summary with weekly and 5-hour limits",
21668
+ template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21669
+ }
21670
+ };
21671
+ if (typeof editor.add === "function") {
21672
+ editor.add({
21673
+ name: AGY_V2_QUOTA_COMMAND,
21674
+ description: "Display current Antigravity quota usage",
21675
+ template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21676
+ });
21677
+ editor.add({
21678
+ name: AGY_V2_QUOTA_SUMMARY_COMMAND,
21679
+ description: "Display Antigravity quota summary grouped by model family",
21680
+ template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21681
+ });
21682
+ } else if (typeof editor.set === "function") {
21683
+ editor.set(AGY_V2_QUOTA_COMMAND, commands[AGY_V2_QUOTA_COMMAND]);
21684
+ editor.set(AGY_V2_QUOTA_SUMMARY_COMMAND, commands[AGY_V2_QUOTA_SUMMARY_COMMAND]);
21685
+ } else if (editor.commands && typeof editor.commands === "object") {
21686
+ editor.commands[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21687
+ editor.commands[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21688
+ } else if (typeof editor === "object") {
21689
+ editor[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21690
+ editor[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21691
+ }
21692
+ });
21693
+ ctx.integration?.transform?.((editor) => {
21694
+ if (!editor) return;
21695
+ editor.update?.(AGY_PROVIDER_ID, (integration) => {
21696
+ integration.name = "Antigravity CLI (plugin)";
21697
+ });
21698
+ editor.method?.update?.({
21699
+ integrationID: AGY_PROVIDER_ID,
21700
+ method: {
21701
+ id: "oauth",
21702
+ type: "oauth",
21703
+ label: "Antigravity CLI (OAuth)"
21704
+ },
21705
+ authorize: async () => {
21706
+ const authorization = await authorizeAgy();
21707
+ return {
21708
+ mode: "code",
21709
+ url: authorization.url,
21710
+ instructions: "Please complete Google account authorization in your browser. After authorization, copy the full redirect URL or code and paste it below:",
21711
+ callback: async (code) => {
21712
+ const trimmed = code.trim();
21713
+ const parsed = parseOAuthCallbackInput(trimmed);
21714
+ const authCode = parsed.code || trimmed;
21715
+ if (!authCode) {
21716
+ return { type: "failed", error: "Missing authorization code in callback input" };
21717
+ }
21718
+ if (parsed.state && parsed.state !== authorization.state) {
21719
+ return { type: "failed", error: "State mismatch in callback input (possible CSRF attempt)" };
21720
+ }
21721
+ const exchangeResult = await exchangeAgyWithVerifier(authCode, authorization.verifier);
21722
+ if (exchangeResult.type !== "success") {
21723
+ return exchangeResult;
21724
+ }
21725
+ const initialRefresh = formatRefreshParts({
21726
+ refreshToken: exchangeResult.refresh
21727
+ });
21728
+ let authRecord = {
21729
+ type: "oauth",
21730
+ refresh: initialRefresh,
21731
+ access: exchangeResult.access,
21732
+ expires: exchangeResult.expires
21733
+ };
21734
+ try {
21735
+ const projectContext = await ensureProjectContext(
21736
+ authRecord,
21737
+ { auth: { set: async () => {
21738
+ } } }
21739
+ );
21740
+ authRecord = {
21741
+ ...authRecord,
21742
+ refresh: projectContext.auth.refresh
21743
+ };
21744
+ } catch {
21745
+ }
21746
+ try {
21747
+ saveStoredAuthToJson(authRecord);
21748
+ } catch {
21749
+ return {
21750
+ type: "failed",
21751
+ error: "Google authentication succeeded but AGY credentials could not be stored. Check filesystem access and retry."
21752
+ };
21753
+ }
21754
+ return {
21755
+ type: "oauth",
21756
+ methodID: "oauth",
21757
+ refresh: authRecord.refresh,
21758
+ access: authRecord.access,
21759
+ expires: authRecord.expires
21760
+ };
21761
+ }
21762
+ };
21763
+ }
21764
+ });
21765
+ });
21766
+ ctx.aisdk?.hook("sdk", async (event) => {
21767
+ if (!event) return;
21768
+ const isMatchingProvider = event.providerID === AGY_PROVIDER_ID || event.model?.providerID === AGY_PROVIDER_ID;
21769
+ if (!isMatchingProvider) return;
21770
+ event.options = event.options || {};
21771
+ event.options.apiKey = "dummy";
21772
+ event.options.fetch = createV2FetchInterceptor();
21773
+ });
21774
+ registerV2SessionHooks(ctx);
21775
+ }
21776
+ var v2PluginDefinition = defineOpenCodeV2Plugin({
21777
+ id: AGY_PROVIDER_ID,
21778
+ setup: setupOpenCodeV2
21779
+ });
21780
+
20979
21781
  // index.ts
20980
- var index_default = {
20981
- id: "@anthonyhaussman/opencode-agy-auth",
21782
+ var dualPlugin = {
21783
+ ...v2PluginDefinition,
20982
21784
  server: AgyCLIOAuthPlugin
20983
21785
  };
21786
+ var index_default = dualPlugin;
20984
21787
  export {
20985
21788
  AgyCLIOAuthPlugin,
20986
21789
  GoogleOAuthPlugin,
20987
- index_default as default
21790
+ index_default as default,
21791
+ defineOpenCodeV2Plugin,
21792
+ setupOpenCodeV2,
21793
+ v2PluginDefinition
20988
21794
  };
20989
21795
  //# sourceMappingURL=index.js.map