@anthonyhaussman/opencode-agy-auth 1.2.7-alpha.2 → 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
  }
@@ -20832,842 +20815,14 @@ function toUrlString(value) {
20832
20815
  return value.toString();
20833
20816
  }
20834
20817
 
20835
- // src/plugin/types.ts
20836
- function defineOpenCodeV2Plugin(def) {
20837
- return def;
20838
- }
20839
-
20840
- // src/plugin/v2.ts
20841
- import { homedir as homedir4 } from "os";
20842
- import { join as join6 } from "path";
20843
- import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "fs";
20844
- import "http";
20845
- var AGY_V2_QUOTA_COMMAND = "agy-quota";
20846
- var AGY_V2_QUOTA_SUMMARY_COMMAND = "agy-quota-summary";
20847
- var AGY_V2_QUOTA_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota usage for the current authenticated account.
20848
-
20849
- Immediately call \`${AGY_QUOTA_TOOL_NAME}\` with no arguments and return its output verbatim.
20850
- Do not call other tools.
20851
- `;
20852
- 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.
20853
-
20854
- Immediately call \`${AGY_QUOTA_SUMMARY_TOOL_NAME}\` with no arguments and return its output verbatim.
20855
- Do not call other tools.
20856
- `;
20857
- function getSafeHeader2(headers, key) {
20858
- if (!headers) {
20859
- return void 0;
20860
- }
20861
- const targetKey = key.toLowerCase();
20862
- if (typeof headers.get === "function") {
20863
- try {
20864
- return headers.get(targetKey) || void 0;
20865
- } catch {
20866
- }
20867
- }
20868
- if (Array.isArray(headers)) {
20869
- const found = headers.find((item) => {
20870
- if (Array.isArray(item) && typeof item[0] === "string") {
20871
- return item[0].toLowerCase() === targetKey;
20872
- }
20873
- return false;
20874
- });
20875
- return found ? String(found[1]) : void 0;
20876
- }
20877
- if (typeof headers === "object") {
20878
- const foundKey = Object.keys(headers).find((k) => k.toLowerCase() === targetKey);
20879
- return foundKey ? headers[foundKey] !== void 0 ? String(headers[foundKey]) : void 0 : void 0;
20880
- }
20881
- return void 0;
20882
- }
20883
- function setSafeHeaders2(initHeaders, newHeaders) {
20884
- if (typeof globalThis.Headers !== "undefined") {
20885
- const headers = new globalThis.Headers(initHeaders ?? {});
20886
- for (const [k, v] of Object.entries(newHeaders)) {
20887
- headers.set(k, v);
20888
- }
20889
- return headers;
20890
- }
20891
- if (Array.isArray(initHeaders)) {
20892
- const nextHeaders2 = [...initHeaders];
20893
- for (const [k, v] of Object.entries(newHeaders)) {
20894
- const idx = nextHeaders2.findIndex((item) => Array.isArray(item) && typeof item[0] === "string" && item[0].toLowerCase() === k.toLowerCase());
20895
- if (idx !== -1) {
20896
- nextHeaders2[idx] = [k, v];
20897
- } else {
20898
- nextHeaders2.push([k, v]);
20899
- }
20900
- }
20901
- return nextHeaders2;
20902
- }
20903
- const nextHeaders = {};
20904
- if (initHeaders && typeof initHeaders === "object") {
20905
- for (const [k, v] of Object.entries(initHeaders)) {
20906
- nextHeaders[k] = String(v);
20907
- }
20908
- }
20909
- for (const [k, v] of Object.entries(newHeaders)) {
20910
- const existingKey = Object.keys(nextHeaders).find((key) => key.toLowerCase() === k.toLowerCase());
20911
- if (existingKey) {
20912
- nextHeaders[existingKey] = v;
20913
- } else {
20914
- nextHeaders[k] = v;
20915
- }
20916
- }
20917
- return nextHeaders;
20918
- }
20919
- function toUrlString2(value) {
20920
- if (typeof value === "string") {
20921
- return value;
20922
- }
20923
- const candidate = value.url;
20924
- if (candidate) {
20925
- return candidate;
20926
- }
20927
- return value.toString();
20928
- }
20929
- function resolveModelTier2(baseModelId, init) {
20930
- const parts = baseModelId.split("@");
20931
- const base = parts[0] || "";
20932
- const suffixTier = parts[1]?.toLowerCase();
20933
- const mapping = TIER_MAPPING[base];
20934
- if (!mapping) {
20935
- return baseModelId;
20936
- }
20937
- const headerTier = getSafeHeader2(init?.headers, "x-agy-tier")?.toLowerCase() || null;
20938
- const requestedTier = headerTier || suffixTier;
20939
- if (requestedTier && Object.prototype.hasOwnProperty.call(mapping, requestedTier)) {
20940
- return mapping[requestedTier] || baseModelId;
20941
- }
20942
- return mapping["medium"] ?? mapping["high"];
20943
- }
20944
- var storedAuthOverrideForTesting = void 0;
20945
- function loadStoredAuthFromJson() {
20946
- if (storedAuthOverrideForTesting !== void 0) {
20947
- return storedAuthOverrideForTesting;
20948
- }
20949
- const authPath = join6(homedir4(), ".local", "share", "opencode", "auth.json");
20950
- try {
20951
- if (existsSync6(authPath)) {
20952
- const content = readFileSync5(authPath, "utf8");
20953
- const data = JSON.parse(content);
20954
- return data?.[AGY_PROVIDER_ID];
20955
- }
20956
- } catch {
20957
- }
20958
- return void 0;
20959
- }
20960
- function saveStoredAuthToJson(authRecord) {
20961
- if (process.env.NODE_ENV === "test" || process.env.VITEST || storedAuthOverrideForTesting !== void 0) {
20962
- return;
20963
- }
20964
- try {
20965
- const dirPath = join6(homedir4(), ".local", "share", "opencode");
20966
- if (!existsSync6(dirPath)) {
20967
- mkdirSync5(dirPath, { recursive: true });
20968
- }
20969
- const authPath = join6(dirPath, "auth.json");
20970
- let data = {};
20971
- if (existsSync6(authPath)) {
20972
- try {
20973
- data = JSON.parse(readFileSync5(authPath, "utf8")) || {};
20974
- } catch {
20975
- data = {};
20976
- }
20977
- }
20978
- data[AGY_PROVIDER_ID] = {
20979
- type: "oauth",
20980
- refresh: authRecord.refresh,
20981
- access: authRecord.access,
20982
- expires: authRecord.expires
20983
- };
20984
- writeFileSync5(authPath, JSON.stringify(data, null, 2), "utf8");
20985
- } catch {
20986
- }
20987
- }
20988
- function createV2FetchInterceptor(getAuthSnapshot) {
20989
- return async function agyV2Fetch(input, init) {
20990
- const isGL = isGenerativeLanguageRequest(input);
20991
- const isInternal = toUrlString2(input).includes("cloudcode-pa.googleapis.com");
20992
- if (!isGL && !isInternal) {
20993
- return agyFetch(input, init);
20994
- }
20995
- let rawAuth = getAuthSnapshot ? await getAuthSnapshot() : void 0;
20996
- if (!rawAuth) {
20997
- rawAuth = loadStoredAuthFromJson();
20998
- }
20999
- if (!rawAuth || !isOAuthAuth(rawAuth)) {
21000
- return agyFetch(input, init);
21001
- }
21002
- let authRecord = resolveCachedAuth(rawAuth);
21003
- if (accessTokenExpired(authRecord)) {
21004
- const refreshed = await refreshAccessToken(authRecord, { auth: { set: async () => {
21005
- } } });
21006
- if (refreshed) {
21007
- authRecord = refreshed;
21008
- }
21009
- }
21010
- if (!authRecord.access) {
21011
- return agyFetch(input, init);
21012
- }
21013
- if (isInternal) {
21014
- const hasAuth = getSafeHeader2(init?.headers, "Authorization") !== void 0;
21015
- if (hasAuth) {
21016
- return agyFetch(input, init);
21017
- }
21018
- const userAgent = buildAgyCliUserAgent();
21019
- const headers = setSafeHeaders2(init?.headers, {
21020
- Authorization: `Bearer ${authRecord.access}`,
21021
- "User-Agent": userAgent
21022
- });
21023
- return agyFetch(input, {
21024
- ...init,
21025
- headers
21026
- });
21027
- }
21028
- const requestTarget = parseGenerativeLanguageRequest(input);
21029
- const requestUserAgentModel = requestTarget?.effectiveModel;
21030
- let projectContext;
21031
- try {
21032
- projectContext = await ensureProjectContext(
21033
- authRecord,
21034
- { auth: { set: async () => {
21035
- } } },
21036
- void 0,
21037
- requestUserAgentModel
21038
- );
21039
- } catch {
21040
- projectContext = {
21041
- effectiveProjectId: parseRefreshParts(authRecord.refresh).projectId || "antigravity",
21042
- auth: authRecord
21043
- };
21044
- }
21045
- const originalRequestedModel = parseGenerativeLanguageRequest(input)?.effectiveModel;
21046
- let modifiedInput = input;
21047
- if (isGL && originalRequestedModel) {
21048
- const originalBase = originalRequestedModel.replace("google-agy/", "");
21049
- const resolvedBase = resolveModelTier2(originalBase, init);
21050
- if (originalBase !== resolvedBase) {
21051
- if (typeof modifiedInput === "string") {
21052
- modifiedInput = modifiedInput.replace(`models/${originalBase}`, `models/${resolvedBase}`);
21053
- } else if (typeof Request !== "undefined" && modifiedInput instanceof Request) {
21054
- const newUrl = modifiedInput.url.replace(`models/${originalBase}`, `models/${resolvedBase}`);
21055
- modifiedInput = new Request(newUrl, modifiedInput);
21056
- }
21057
- }
21058
- }
21059
- const transformed = prepareAgyRequest(
21060
- modifiedInput,
21061
- init,
21062
- authRecord.access,
21063
- projectContext.effectiveProjectId,
21064
- void 0
21065
- );
21066
- const chatLogger = createChatLogger();
21067
- if (chatLogger) {
21068
- chatLogger.logRequest(
21069
- toUrlString2(transformed.request),
21070
- transformed.init.method || "GET",
21071
- transformed.init.headers,
21072
- transformed.init.body
21073
- );
21074
- }
21075
- const response = await fetchWithRetry(transformed.request, transformed.init);
21076
- return transformAgyResponse(
21077
- response,
21078
- transformed.streaming,
21079
- null,
21080
- transformed.requestedModel,
21081
- transformed.sessionId,
21082
- chatLogger
21083
- );
21084
- };
21085
- }
21086
- async function setupOpenCodeV2(ctx) {
21087
- const resolveVariants = (modelId) => {
21088
- const mapping = TIER_MAPPING[modelId];
21089
- if (!mapping) return void 0;
21090
- const variants = [];
21091
- if (mapping.minimal !== void 0) variants.push({ id: "minimal" });
21092
- if (mapping.low !== void 0) variants.push({ id: "low" });
21093
- if (mapping.medium !== void 0) variants.push({ id: "medium" });
21094
- if (mapping.high !== void 0) variants.push({ id: "high" });
21095
- return variants.length > 0 ? variants : void 0;
21096
- };
21097
- const updateProviderRecord = (p) => {
21098
- p.name = "Antigravity CLI";
21099
- p.activation = "enabled";
21100
- p.package = "aisdk:@ai-sdk/google";
21101
- p.description = "Google Gemini Antigravity Code Assist OAuth provider";
21102
- p.settings = { ...p.settings || {}, apiKey: "dummy" };
21103
- p.integrationID = AGY_PROVIDER_ID;
21104
- };
21105
- const buildModelRecord = (modelId, simple, existingModel) => {
21106
- const isClaude = modelId.startsWith("claude-");
21107
- const isGpt = modelId.startsWith("gpt-");
21108
- const variants = resolveVariants(modelId);
21109
- return {
21110
- id: modelId,
21111
- providerID: AGY_PROVIDER_ID,
21112
- name: simple.name,
21113
- description: simple.description,
21114
- family: modelId.includes("gemini") ? "gemini" : isClaude ? "claude" : isGpt ? "gpt" : "unknown",
21115
- reasoning: simple.reasoning,
21116
- attachment: simple.attachment,
21117
- tool_call: simple.toolCall,
21118
- limit: {
21119
- context: simple.maxTokens,
21120
- output: simple.maxOutputTokens
21121
- },
21122
- cost: simple.cost || { input: 0, output: 0 },
21123
- ...variants ? { variants } : {},
21124
- ...existingModel || {}
21125
- };
21126
- };
21127
- const updateModelRecord = (m, modelId, simple) => {
21128
- m.name = simple.name;
21129
- m.capabilities = {
21130
- tools: true,
21131
- input: ["text", "image"],
21132
- output: ["text"]
21133
- };
21134
- m.limit = {
21135
- context: simple.maxTokens,
21136
- output: simple.maxOutputTokens
21137
- };
21138
- m.family = "gemini";
21139
- if (simple.cost) {
21140
- m.cost = simple.cost;
21141
- }
21142
- const variants = resolveVariants(modelId);
21143
- if (variants) {
21144
- m.variants = variants;
21145
- }
21146
- };
21147
- if (ctx.provider?.transform) {
21148
- ctx.provider.transform(async (editor) => {
21149
- if (!editor) return;
21150
- if (typeof editor.update === "function") {
21151
- editor.update(AGY_PROVIDER_ID, updateProviderRecord);
21152
- } else if (typeof editor.set === "function") {
21153
- const p = { id: AGY_PROVIDER_ID };
21154
- updateProviderRecord(p);
21155
- editor.set(AGY_PROVIDER_ID, p);
21156
- } else if (typeof editor === "object") {
21157
- const p = editor[AGY_PROVIDER_ID] || { id: AGY_PROVIDER_ID };
21158
- updateProviderRecord(p);
21159
- editor[AGY_PROVIDER_ID] = p;
21160
- }
21161
- });
21162
- }
21163
- if (ctx.model?.transform) {
21164
- ctx.model.transform(async (editor) => {
21165
- if (!editor) return;
21166
- if (typeof editor.update === "function") {
21167
- for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21168
- editor.update(AGY_PROVIDER_ID, modelId, (m) => updateModelRecord(m, modelId, simple));
21169
- }
21170
- } else if (typeof editor.set === "function") {
21171
- for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21172
- const m = buildModelRecord(modelId, simple);
21173
- editor.set(`${AGY_PROVIDER_ID}:${modelId}`, m);
21174
- }
21175
- } else if (typeof editor === "object") {
21176
- for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21177
- const key = `${AGY_PROVIDER_ID}:${modelId}`;
21178
- editor[key] = buildModelRecord(modelId, simple, editor[key]);
21179
- }
21180
- }
21181
- });
21182
- }
21183
- if (ctx.catalog?.transform) {
21184
- ctx.catalog.transform(async (editor) => {
21185
- if (!editor) return;
21186
- if (typeof editor?.provider?.update === "function") {
21187
- editor.provider.update(AGY_PROVIDER_ID, updateProviderRecord);
21188
- if (typeof editor?.model?.update === "function") {
21189
- for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21190
- editor.model.update(AGY_PROVIDER_ID, modelId, (m) => updateModelRecord(m, modelId, simple));
21191
- }
21192
- }
21193
- return;
21194
- }
21195
- const catalog = editor;
21196
- catalog.providers = catalog.providers || {};
21197
- catalog.providers[AGY_PROVIDER_ID] = {
21198
- id: AGY_PROVIDER_ID,
21199
- name: "Antigravity CLI",
21200
- npm: "aisdk:@ai-sdk/google",
21201
- settings: { apiKey: "dummy" },
21202
- integrationID: AGY_PROVIDER_ID,
21203
- models: { ...catalog.providers[AGY_PROVIDER_ID]?.models || {} },
21204
- ...catalog.providers[AGY_PROVIDER_ID]
21205
- };
21206
- if (catalog.providers[AGY_PROVIDER_ID].settings) {
21207
- catalog.providers[AGY_PROVIDER_ID].settings = {
21208
- ...catalog.providers[AGY_PROVIDER_ID].settings,
21209
- apiKey: "dummy"
21210
- };
21211
- } else {
21212
- catalog.providers[AGY_PROVIDER_ID].settings = { apiKey: "dummy" };
21213
- }
21214
- catalog.providers[AGY_PROVIDER_ID].integrationID = AGY_PROVIDER_ID;
21215
- const targetModels = catalog.providers[AGY_PROVIDER_ID].models;
21216
- for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21217
- targetModels[modelId] = buildModelRecord(modelId, simple, targetModels[modelId]);
21218
- }
21219
- });
21220
- }
21221
- ctx.tool.transform(async (editor) => {
21222
- if (!editor) return;
21223
- const quotaTool = createAgyQuotaTool({
21224
- client: void 0,
21225
- getAuthResolver: () => void 0,
21226
- getConfiguredProjectId: () => void 0,
21227
- getUserAgentModel: () => void 0
21228
- });
21229
- const quotaSummaryTool = createAgyQuotaSummaryTool({
21230
- client: void 0,
21231
- getAuthResolver: () => void 0,
21232
- getConfiguredProjectId: () => void 0,
21233
- getUserAgentModel: () => void 0
21234
- });
21235
- if (typeof editor.add === "function") {
21236
- editor.add({
21237
- name: AGY_QUOTA_TOOL_NAME,
21238
- description: quotaTool.description,
21239
- input: {},
21240
- execute: async (args, context) => quotaTool.execute(args, context)
21241
- });
21242
- editor.add({
21243
- name: AGY_QUOTA_SUMMARY_TOOL_NAME,
21244
- description: quotaSummaryTool.description,
21245
- input: {},
21246
- execute: async (args, context) => quotaSummaryTool.execute(args, context)
21247
- });
21248
- } else if (typeof editor.set === "function") {
21249
- editor.set(AGY_QUOTA_TOOL_NAME, quotaTool);
21250
- editor.set(AGY_QUOTA_SUMMARY_TOOL_NAME, quotaSummaryTool);
21251
- } else if (editor.tools && typeof editor.tools === "object") {
21252
- editor.tools[AGY_QUOTA_TOOL_NAME] = quotaTool;
21253
- editor.tools[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21254
- } else if (typeof editor === "object") {
21255
- editor[AGY_QUOTA_TOOL_NAME] = quotaTool;
21256
- editor[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21257
- }
21258
- });
21259
- ctx.command.transform(async (editor) => {
21260
- if (!editor) return;
21261
- const commands = {
21262
- [AGY_V2_QUOTA_COMMAND]: {
21263
- description: "Show Agy Code Assist quota usage",
21264
- template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21265
- },
21266
- [AGY_V2_QUOTA_SUMMARY_COMMAND]: {
21267
- description: "Show Agy Code Assist quota summary with weekly and 5-hour limits",
21268
- template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21269
- }
21270
- };
21271
- if (typeof editor.add === "function") {
21272
- editor.add({
21273
- name: AGY_V2_QUOTA_COMMAND,
21274
- description: "Display current Antigravity quota usage",
21275
- template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21276
- });
21277
- editor.add({
21278
- name: AGY_V2_QUOTA_SUMMARY_COMMAND,
21279
- description: "Display Antigravity quota summary grouped by model family",
21280
- template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21281
- });
21282
- } else if (typeof editor.set === "function") {
21283
- editor.set(AGY_V2_QUOTA_COMMAND, commands[AGY_V2_QUOTA_COMMAND]);
21284
- editor.set(AGY_V2_QUOTA_SUMMARY_COMMAND, commands[AGY_V2_QUOTA_SUMMARY_COMMAND]);
21285
- } else if (editor.commands && typeof editor.commands === "object") {
21286
- editor.commands[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21287
- editor.commands[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21288
- } else if (typeof editor === "object") {
21289
- editor[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21290
- editor[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21291
- }
21292
- });
21293
- ctx.integration?.transform?.((editor) => {
21294
- if (!editor) return;
21295
- editor.update?.(AGY_PROVIDER_ID, (integration) => {
21296
- integration.name = "Antigravity CLI (plugin)";
21297
- });
21298
- editor.method?.update?.({
21299
- integrationID: AGY_PROVIDER_ID,
21300
- method: {
21301
- id: "oauth",
21302
- type: "oauth",
21303
- label: "Antigravity CLI (OAuth)"
21304
- },
21305
- authorize: async () => {
21306
- const authorization = await authorizeAgy();
21307
- return {
21308
- mode: "code",
21309
- url: authorization.url,
21310
- instructions: "Please complete Google account authorization in your browser. After authorization, copy the full redirect URL or code and paste it below:",
21311
- callback: async (code) => {
21312
- const trimmed = code.trim();
21313
- const parsed = parseOAuthCallbackInput(trimmed);
21314
- const authCode = parsed.code || trimmed;
21315
- if (!authCode) {
21316
- return { type: "failed", error: "Missing authorization code in callback input" };
21317
- }
21318
- if (parsed.state && parsed.state !== authorization.state) {
21319
- return { type: "failed", error: "State mismatch in callback input (possible CSRF attempt)" };
21320
- }
21321
- const exchangeResult = await exchangeAgyWithVerifier(authCode, authorization.verifier);
21322
- if (exchangeResult.type !== "success") {
21323
- return exchangeResult;
21324
- }
21325
- const initialRefresh = formatRefreshParts({
21326
- refreshToken: exchangeResult.refresh
21327
- });
21328
- let authRecord = {
21329
- type: "oauth",
21330
- refresh: initialRefresh,
21331
- access: exchangeResult.access,
21332
- expires: exchangeResult.expires
21333
- };
21334
- try {
21335
- const projectContext = await ensureProjectContext(
21336
- authRecord,
21337
- { auth: { set: async () => {
21338
- } } }
21339
- );
21340
- authRecord = {
21341
- ...authRecord,
21342
- refresh: projectContext.auth.refresh
21343
- };
21344
- } catch {
21345
- }
21346
- saveStoredAuthToJson(authRecord);
21347
- return {
21348
- type: "oauth",
21349
- methodID: "oauth",
21350
- refresh: authRecord.refresh,
21351
- access: authRecord.access,
21352
- expires: authRecord.expires
21353
- };
21354
- }
21355
- };
21356
- }
21357
- });
21358
- });
21359
- ctx.aisdk?.hook("sdk", async (event) => {
21360
- if (!event) return;
21361
- const isMatchingProvider = event.providerID === AGY_PROVIDER_ID || event.model?.providerID === AGY_PROVIDER_ID;
21362
- if (!isMatchingProvider) return;
21363
- event.options = event.options || {};
21364
- event.options.apiKey = "dummy";
21365
- event.options.fetch = createV2FetchInterceptor();
21366
- });
21367
- let lastInterceptedModel;
21368
- ctx.session.hook(
21369
- "http.request",
21370
- async (event) => {
21371
- if (!event) return;
21372
- const rawUrl = typeof event.url === "string" ? event.url : event.request?.url || "";
21373
- const isGL = isGenerativeLanguageRequest(rawUrl);
21374
- const isInternal = rawUrl.includes("cloudcode-pa.googleapis.com");
21375
- if (!isGL && !isInternal) {
21376
- return;
21377
- }
21378
- event.headers = event.headers || {};
21379
- let modelName;
21380
- let rawAuth = event.auth;
21381
- if (rawAuth && !rawAuth.type) {
21382
- const tokenVal = rawAuth.access || rawAuth.token;
21383
- if (tokenVal || rawAuth.refresh) {
21384
- rawAuth = { type: "oauth", access: tokenVal, ...rawAuth };
21385
- }
21386
- }
21387
- if (!rawAuth || !isOAuthAuth(rawAuth)) {
21388
- rawAuth = loadStoredAuthFromJson();
21389
- }
21390
- let authRecord = rawAuth && isOAuthAuth(rawAuth) ? resolveCachedAuth(rawAuth) : void 0;
21391
- if (authRecord && accessTokenExpired(authRecord)) {
21392
- const refreshed = await refreshAccessToken(authRecord, { auth: { set: async () => {
21393
- } } });
21394
- if (refreshed) {
21395
- authRecord = refreshed;
21396
- saveStoredAuthToJson(refreshed);
21397
- }
21398
- }
21399
- if (isGL) {
21400
- const parsed = parseGenerativeLanguageRequest(rawUrl);
21401
- modelName = parsed?.effectiveModel;
21402
- if (modelName) {
21403
- lastInterceptedModel = modelName;
21404
- }
21405
- if (typeof event.headers.delete === "function") {
21406
- event.headers.delete("x-goog-api-key");
21407
- event.headers.delete("api-key");
21408
- } else {
21409
- for (const key of Object.keys(event.headers)) {
21410
- const lower = key.toLowerCase();
21411
- if (lower === "x-goog-api-key" || lower === "api-key") {
21412
- delete event.headers[key];
21413
- }
21414
- }
21415
- }
21416
- if (event.request?.headers) {
21417
- if (typeof event.request.headers.delete === "function") {
21418
- event.request.headers.delete("x-goog-api-key");
21419
- event.request.headers.delete("api-key");
21420
- } else {
21421
- for (const key of Object.keys(event.request.headers)) {
21422
- const lower = key.toLowerCase();
21423
- if (lower === "x-goog-api-key" || lower === "api-key") {
21424
- delete event.request.headers[key];
21425
- }
21426
- }
21427
- }
21428
- }
21429
- let cleanUrl = rawUrl;
21430
- try {
21431
- const parsedUrl = new URL(rawUrl);
21432
- let urlChanged = false;
21433
- for (const param of ["key", "x-goog-api-key", "api-key"]) {
21434
- if (parsedUrl.searchParams.has(param)) {
21435
- parsedUrl.searchParams.delete(param);
21436
- urlChanged = true;
21437
- }
21438
- }
21439
- if (urlChanged) {
21440
- cleanUrl = parsedUrl.toString();
21441
- }
21442
- } catch {
21443
- }
21444
- if (authRecord && authRecord.access) {
21445
- let projectContext;
21446
- try {
21447
- projectContext = await ensureProjectContext(
21448
- authRecord,
21449
- { auth: { set: async () => {
21450
- } } },
21451
- void 0,
21452
- modelName
21453
- );
21454
- } catch {
21455
- projectContext = {
21456
- effectiveProjectId: parseRefreshParts(authRecord.refresh).projectId || "antigravity",
21457
- auth: authRecord
21458
- };
21459
- }
21460
- const originalRequestedModel = modelName;
21461
- let modifiedUrl = cleanUrl;
21462
- if (originalRequestedModel) {
21463
- const originalBase = originalRequestedModel.replace("google-agy/", "");
21464
- const initHeaders = event.headers instanceof Headers ? event.headers : event.request?.headers;
21465
- const resolvedBase = resolveModelTier2(originalBase, { headers: initHeaders });
21466
- if (originalBase !== resolvedBase) {
21467
- modifiedUrl = modifiedUrl.replace(`models/${originalBase}`, `models/${resolvedBase}`);
21468
- }
21469
- }
21470
- let bodyPayload = event.body;
21471
- if (bodyPayload === void 0 && event.request) {
21472
- if (typeof event.request.clone === "function") {
21473
- try {
21474
- bodyPayload = await event.request.clone().text();
21475
- } catch {
21476
- }
21477
- } else if (event.request.body !== void 0) {
21478
- bodyPayload = event.request.body;
21479
- }
21480
- }
21481
- let preExistingUserAgent;
21482
- if (typeof event.headers?.get === "function") {
21483
- preExistingUserAgent = event.headers.get("user-agent") || event.headers.get("User-Agent") || void 0;
21484
- } else if (event.headers && typeof event.headers === "object") {
21485
- preExistingUserAgent = event.headers["user-agent"] || event.headers["User-Agent"] || void 0;
21486
- }
21487
- if (!preExistingUserAgent && typeof event.request?.headers?.get === "function") {
21488
- preExistingUserAgent = event.request.headers.get("user-agent") || event.request.headers.get("User-Agent") || void 0;
21489
- } else if (!preExistingUserAgent && event.request?.headers && typeof event.request.headers === "object") {
21490
- preExistingUserAgent = event.request.headers["user-agent"] || event.request.headers["User-Agent"] || void 0;
21491
- }
21492
- const method = event.method || event.request?.method || "POST";
21493
- const requestHeaders = event.headers || event.request?.headers;
21494
- const transformed = prepareAgyRequest(
21495
- modifiedUrl,
21496
- {
21497
- method,
21498
- headers: requestHeaders,
21499
- body: bodyPayload
21500
- },
21501
- authRecord.access,
21502
- projectContext.effectiveProjectId
21503
- );
21504
- const targetUrl = toUrlString2(transformed.request);
21505
- if (typeof event.url === "string") {
21506
- event.url = targetUrl;
21507
- }
21508
- if (event.request && typeof event.request === "object") {
21509
- if (typeof Request !== "undefined" && event.request instanceof Request) {
21510
- event.request = new Request(targetUrl, {
21511
- method: transformed.init.method,
21512
- headers: transformed.init.headers,
21513
- body: transformed.init.body
21514
- });
21515
- } else if (typeof event.request.url === "string") {
21516
- try {
21517
- event.request.url = targetUrl;
21518
- } catch {
21519
- }
21520
- }
21521
- }
21522
- const headerEntries = transformed.init.headers instanceof Headers ? Array.from(transformed.init.headers.entries()) : Object.entries(transformed.init.headers || {});
21523
- for (const [k, v] of headerEntries) {
21524
- const lowerK = k.toLowerCase();
21525
- if (lowerK === "user-agent") {
21526
- if (preExistingUserAgent) {
21527
- continue;
21528
- }
21529
- if (typeof event.headers?.set === "function") {
21530
- event.headers.set("User-Agent", v);
21531
- } else if (event.headers) {
21532
- event.headers["User-Agent"] = v;
21533
- }
21534
- if (event.request?.headers && typeof event.request.headers.set === "function") {
21535
- event.request.headers.set("User-Agent", v);
21536
- } else if (event.request?.headers && typeof event.request.headers === "object") {
21537
- event.request.headers["User-Agent"] = v;
21538
- }
21539
- continue;
21540
- }
21541
- if (typeof event.headers?.set === "function") {
21542
- event.headers.set(k, v);
21543
- } else if (event.headers) {
21544
- event.headers[k] = v;
21545
- }
21546
- if (event.request?.headers && typeof event.request.headers.set === "function") {
21547
- event.request.headers.set(k, v);
21548
- } else if (event.request?.headers && typeof event.request.headers === "object") {
21549
- event.request.headers[k] = v;
21550
- }
21551
- }
21552
- if (transformed.init.body !== void 0) {
21553
- event.body = transformed.init.body;
21554
- if (event.request && typeof event.request === "object" && !(event.request instanceof Request)) {
21555
- event.request.body = transformed.init.body;
21556
- }
21557
- }
21558
- } else {
21559
- if (typeof event.url === "string") {
21560
- event.url = cleanUrl;
21561
- }
21562
- if (event.request && typeof event.request === "object") {
21563
- if (typeof event.request.url === "string") {
21564
- event.request.url = cleanUrl;
21565
- }
21566
- }
21567
- }
21568
- }
21569
- if (authRecord && authRecord.access) {
21570
- if (typeof event.headers?.set === "function") {
21571
- event.headers.set("Authorization", `Bearer ${authRecord.access}`);
21572
- } else if (event.headers) {
21573
- event.headers["Authorization"] = `Bearer ${authRecord.access}`;
21574
- }
21575
- if (event.request?.headers && typeof event.request.headers.set === "function") {
21576
- event.request.headers.set("Authorization", `Bearer ${authRecord.access}`);
21577
- } else if (event.request?.headers && typeof event.request.headers === "object") {
21578
- event.request.headers["Authorization"] = `Bearer ${authRecord.access}`;
21579
- }
21580
- }
21581
- const userAgent = buildAgyCliUserAgent(modelName);
21582
- if (typeof event.headers?.set === "function") {
21583
- if (!event.headers.get("User-Agent") && !event.headers.get("user-agent")) {
21584
- event.headers.set("User-Agent", userAgent);
21585
- }
21586
- } else if (event.headers) {
21587
- if (!event.headers["User-Agent"] && !event.headers["user-agent"]) {
21588
- event.headers["User-Agent"] = userAgent;
21589
- }
21590
- }
21591
- if (event.request?.headers && typeof event.request.headers.set === "function") {
21592
- if (!event.request.headers.get("User-Agent") && !event.request.headers.get("user-agent")) {
21593
- event.request.headers.set("User-Agent", userAgent);
21594
- }
21595
- } else if (event.request?.headers && typeof event.request.headers === "object") {
21596
- if (!event.request.headers["User-Agent"] && !event.request.headers["user-agent"]) {
21597
- event.request.headers["User-Agent"] = userAgent;
21598
- }
21599
- }
21600
- },
21601
- { providerID: AGY_PROVIDER_ID }
21602
- );
21603
- ctx.session.hook(
21604
- "http.response",
21605
- async (event) => {
21606
- if (!event || !event.response) return;
21607
- const rawUrl = typeof event.url === "string" ? event.url : event.request?.url || "";
21608
- const isInternal = rawUrl.includes("cloudcode-pa.googleapis.com");
21609
- if (isInternal && event.response instanceof Response) {
21610
- const isStreaming = rawUrl.includes(":streamGenerateCode") || event.response.headers.get("content-type")?.includes("text/event-stream");
21611
- const parsedModel = parseGenerativeLanguageRequest(rawUrl)?.effectiveModel || lastInterceptedModel;
21612
- const transformed = await transformAgyResponse(
21613
- event.response,
21614
- !!isStreaming,
21615
- null,
21616
- parsedModel,
21617
- void 0,
21618
- void 0
21619
- );
21620
- event.response = transformed;
21621
- }
21622
- },
21623
- { providerID: AGY_PROVIDER_ID }
21624
- );
21625
- ctx.session.hook(
21626
- "retry",
21627
- async (event) => {
21628
- if (!event) return;
21629
- const response = event.response;
21630
- if (response instanceof Response) {
21631
- if (response.status === 429 || response.status === 503) {
21632
- const quota = await classifyQuotaResponse(response);
21633
- if (quota?.retryDelayMs) {
21634
- event.retryDelayMs = quota.retryDelayMs;
21635
- } else {
21636
- event.retryDelayMs = await resolveRetryDelayMs(response, event.attempt || 1);
21637
- }
21638
- }
21639
- } else if (event.details && Array.isArray(event.details)) {
21640
- const retryInfo = event.details.find(
21641
- (d) => d && d["@type"] === "type.googleapis.com/google.rpc.RetryInfo"
21642
- );
21643
- if (retryInfo?.retryDelay) {
21644
- const delayMs = retryInternals.parseRetryDelayValue(retryInfo.retryDelay);
21645
- if (delayMs !== null) {
21646
- event.retryDelayMs = delayMs;
21647
- }
21648
- }
21649
- }
21650
- },
21651
- { providerID: AGY_PROVIDER_ID }
21652
- );
21653
- }
21654
- var v2PluginDefinition = defineOpenCodeV2Plugin({
21655
- id: AGY_PROVIDER_ID,
21656
- setup: setupOpenCodeV2
21657
- });
21658
-
21659
20818
  // index.ts
21660
- var dualPlugin = {
21661
- ...v2PluginDefinition,
20819
+ var index_default = {
20820
+ id: "@anthonyhaussman/opencode-agy-auth",
21662
20821
  server: AgyCLIOAuthPlugin
21663
20822
  };
21664
- var index_default = dualPlugin;
21665
20823
  export {
21666
20824
  AgyCLIOAuthPlugin,
21667
20825
  GoogleOAuthPlugin,
21668
- index_default as default,
21669
- defineOpenCodeV2Plugin,
21670
- setupOpenCodeV2,
21671
- v2PluginDefinition
20826
+ index_default as default
21672
20827
  };
21673
20828
  //# sourceMappingURL=index.js.map