@anthonyhaussman/opencode-agy-auth 1.2.13-alpha.0 → 1.2.13

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