@anthonyhaussman/opencode-agy-auth 1.2.3-alpha.6 → 1.2.3-alpha.8

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
  }
@@ -20669,14 +20686,795 @@ function toUrlString(value) {
20669
20686
  return value.toString();
20670
20687
  }
20671
20688
 
20689
+ // src/plugin/types.ts
20690
+ function defineOpenCodeV2Plugin(def) {
20691
+ return def;
20692
+ }
20693
+
20694
+ // src/plugin/v2.ts
20695
+ import { homedir as homedir4 } from "os";
20696
+ import { join as join6 } from "path";
20697
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "fs";
20698
+ import "http";
20699
+ var AGY_V2_QUOTA_COMMAND = "agy-quota";
20700
+ var AGY_V2_QUOTA_SUMMARY_COMMAND = "agy-quota-summary";
20701
+ var AGY_V2_QUOTA_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota usage for the current authenticated account.
20702
+
20703
+ Immediately call \`${AGY_QUOTA_TOOL_NAME}\` with no arguments and return its output verbatim.
20704
+ Do not call other tools.
20705
+ `;
20706
+ 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.
20707
+
20708
+ Immediately call \`${AGY_QUOTA_SUMMARY_TOOL_NAME}\` with no arguments and return its output verbatim.
20709
+ Do not call other tools.
20710
+ `;
20711
+ function getSafeHeader2(headers, key) {
20712
+ if (!headers) {
20713
+ return void 0;
20714
+ }
20715
+ const targetKey = key.toLowerCase();
20716
+ if (typeof headers.get === "function") {
20717
+ try {
20718
+ return headers.get(targetKey) || void 0;
20719
+ } catch {
20720
+ }
20721
+ }
20722
+ if (Array.isArray(headers)) {
20723
+ const found = headers.find((item) => {
20724
+ if (Array.isArray(item) && typeof item[0] === "string") {
20725
+ return item[0].toLowerCase() === targetKey;
20726
+ }
20727
+ return false;
20728
+ });
20729
+ return found ? String(found[1]) : void 0;
20730
+ }
20731
+ if (typeof headers === "object") {
20732
+ const foundKey = Object.keys(headers).find((k) => k.toLowerCase() === targetKey);
20733
+ return foundKey ? headers[foundKey] !== void 0 ? String(headers[foundKey]) : void 0 : void 0;
20734
+ }
20735
+ return void 0;
20736
+ }
20737
+ function setSafeHeaders2(initHeaders, newHeaders) {
20738
+ if (typeof globalThis.Headers !== "undefined") {
20739
+ const headers = new globalThis.Headers(initHeaders ?? {});
20740
+ for (const [k, v] of Object.entries(newHeaders)) {
20741
+ headers.set(k, v);
20742
+ }
20743
+ return headers;
20744
+ }
20745
+ if (Array.isArray(initHeaders)) {
20746
+ const nextHeaders2 = [...initHeaders];
20747
+ for (const [k, v] of Object.entries(newHeaders)) {
20748
+ const idx = nextHeaders2.findIndex((item) => Array.isArray(item) && typeof item[0] === "string" && item[0].toLowerCase() === k.toLowerCase());
20749
+ if (idx !== -1) {
20750
+ nextHeaders2[idx] = [k, v];
20751
+ } else {
20752
+ nextHeaders2.push([k, v]);
20753
+ }
20754
+ }
20755
+ return nextHeaders2;
20756
+ }
20757
+ const nextHeaders = {};
20758
+ if (initHeaders && typeof initHeaders === "object") {
20759
+ for (const [k, v] of Object.entries(initHeaders)) {
20760
+ nextHeaders[k] = String(v);
20761
+ }
20762
+ }
20763
+ for (const [k, v] of Object.entries(newHeaders)) {
20764
+ const existingKey = Object.keys(nextHeaders).find((key) => key.toLowerCase() === k.toLowerCase());
20765
+ if (existingKey) {
20766
+ nextHeaders[existingKey] = v;
20767
+ } else {
20768
+ nextHeaders[k] = v;
20769
+ }
20770
+ }
20771
+ return nextHeaders;
20772
+ }
20773
+ function toUrlString2(value) {
20774
+ if (typeof value === "string") {
20775
+ return value;
20776
+ }
20777
+ const candidate = value.url;
20778
+ if (candidate) {
20779
+ return candidate;
20780
+ }
20781
+ return value.toString();
20782
+ }
20783
+ function resolveModelTier2(baseModelId, init) {
20784
+ const parts = baseModelId.split("@");
20785
+ const base = parts[0] || "";
20786
+ const suffixTier = parts[1]?.toLowerCase();
20787
+ const mapping = TIER_MAPPING[base];
20788
+ if (!mapping) {
20789
+ return baseModelId;
20790
+ }
20791
+ const headerTier = getSafeHeader2(init?.headers, "x-agy-tier")?.toLowerCase() || null;
20792
+ const requestedTier = headerTier || suffixTier;
20793
+ if (requestedTier && Object.prototype.hasOwnProperty.call(mapping, requestedTier)) {
20794
+ return mapping[requestedTier] || baseModelId;
20795
+ }
20796
+ return mapping["medium"] ?? mapping["high"];
20797
+ }
20798
+ var storedAuthOverrideForTesting = void 0;
20799
+ function loadStoredAuthFromJson() {
20800
+ if (storedAuthOverrideForTesting !== void 0) {
20801
+ return storedAuthOverrideForTesting;
20802
+ }
20803
+ const authPath = join6(homedir4(), ".local", "share", "opencode", "auth.json");
20804
+ try {
20805
+ if (existsSync6(authPath)) {
20806
+ const content = readFileSync5(authPath, "utf8");
20807
+ const data = JSON.parse(content);
20808
+ return data?.[AGY_PROVIDER_ID];
20809
+ }
20810
+ } catch {
20811
+ }
20812
+ return void 0;
20813
+ }
20814
+ function saveStoredAuthToJson(authRecord) {
20815
+ if (process.env.NODE_ENV === "test" || process.env.VITEST || storedAuthOverrideForTesting !== void 0) {
20816
+ return;
20817
+ }
20818
+ try {
20819
+ const dirPath = join6(homedir4(), ".local", "share", "opencode");
20820
+ if (!existsSync6(dirPath)) {
20821
+ mkdirSync5(dirPath, { recursive: true });
20822
+ }
20823
+ const authPath = join6(dirPath, "auth.json");
20824
+ let data = {};
20825
+ if (existsSync6(authPath)) {
20826
+ try {
20827
+ data = JSON.parse(readFileSync5(authPath, "utf8")) || {};
20828
+ } catch {
20829
+ data = {};
20830
+ }
20831
+ }
20832
+ data[AGY_PROVIDER_ID] = {
20833
+ type: "oauth",
20834
+ refresh: authRecord.refresh,
20835
+ access: authRecord.access,
20836
+ expires: authRecord.expires
20837
+ };
20838
+ writeFileSync5(authPath, JSON.stringify(data, null, 2), "utf8");
20839
+ } catch {
20840
+ }
20841
+ }
20842
+ function createV2FetchInterceptor(getAuthSnapshot) {
20843
+ return async function agyV2Fetch(input, init) {
20844
+ const isGL = isGenerativeLanguageRequest(input);
20845
+ const isInternal = toUrlString2(input).includes("cloudcode-pa.googleapis.com");
20846
+ if (!isGL && !isInternal) {
20847
+ return agyFetch(input, init);
20848
+ }
20849
+ let rawAuth = getAuthSnapshot ? await getAuthSnapshot() : void 0;
20850
+ if (!rawAuth) {
20851
+ rawAuth = loadStoredAuthFromJson();
20852
+ }
20853
+ if (!rawAuth || !isOAuthAuth(rawAuth)) {
20854
+ return agyFetch(input, init);
20855
+ }
20856
+ let authRecord = resolveCachedAuth(rawAuth);
20857
+ if (accessTokenExpired(authRecord)) {
20858
+ const refreshed = await refreshAccessToken(authRecord, { auth: { set: async () => {
20859
+ } } });
20860
+ if (refreshed) {
20861
+ authRecord = refreshed;
20862
+ }
20863
+ }
20864
+ if (!authRecord.access) {
20865
+ return agyFetch(input, init);
20866
+ }
20867
+ if (isInternal) {
20868
+ const hasAuth = getSafeHeader2(init?.headers, "Authorization") !== void 0;
20869
+ if (hasAuth) {
20870
+ return agyFetch(input, init);
20871
+ }
20872
+ const userAgent = buildAgyCliUserAgent();
20873
+ const headers = setSafeHeaders2(init?.headers, {
20874
+ Authorization: `Bearer ${authRecord.access}`,
20875
+ "User-Agent": userAgent
20876
+ });
20877
+ return agyFetch(input, {
20878
+ ...init,
20879
+ headers
20880
+ });
20881
+ }
20882
+ const requestTarget = parseGenerativeLanguageRequest(input);
20883
+ const requestUserAgentModel = requestTarget?.effectiveModel;
20884
+ let projectContext;
20885
+ try {
20886
+ projectContext = await ensureProjectContext(
20887
+ authRecord,
20888
+ { auth: { set: async () => {
20889
+ } } },
20890
+ void 0,
20891
+ requestUserAgentModel
20892
+ );
20893
+ } catch {
20894
+ projectContext = {
20895
+ effectiveProjectId: parseRefreshParts(authRecord.refresh).projectId || "antigravity",
20896
+ auth: authRecord
20897
+ };
20898
+ }
20899
+ const originalRequestedModel = parseGenerativeLanguageRequest(input)?.effectiveModel;
20900
+ let modifiedInput = input;
20901
+ if (isGL && originalRequestedModel) {
20902
+ const originalBase = originalRequestedModel.replace("google-agy/", "");
20903
+ const resolvedBase = resolveModelTier2(originalBase, init);
20904
+ if (originalBase !== resolvedBase) {
20905
+ if (typeof modifiedInput === "string") {
20906
+ modifiedInput = modifiedInput.replace(`models/${originalBase}`, `models/${resolvedBase}`);
20907
+ } else if (typeof Request !== "undefined" && modifiedInput instanceof Request) {
20908
+ const newUrl = modifiedInput.url.replace(`models/${originalBase}`, `models/${resolvedBase}`);
20909
+ modifiedInput = new Request(newUrl, modifiedInput);
20910
+ }
20911
+ }
20912
+ }
20913
+ const transformed = prepareAgyRequest(
20914
+ modifiedInput,
20915
+ init,
20916
+ authRecord.access,
20917
+ projectContext.effectiveProjectId,
20918
+ void 0
20919
+ );
20920
+ const chatLogger = createChatLogger();
20921
+ if (chatLogger) {
20922
+ chatLogger.logRequest(
20923
+ toUrlString2(transformed.request),
20924
+ transformed.init.method || "GET",
20925
+ transformed.init.headers,
20926
+ transformed.init.body
20927
+ );
20928
+ }
20929
+ const response = await fetchWithRetry(transformed.request, transformed.init);
20930
+ return transformAgyResponse(
20931
+ response,
20932
+ transformed.streaming,
20933
+ null,
20934
+ transformed.requestedModel,
20935
+ transformed.sessionId,
20936
+ chatLogger
20937
+ );
20938
+ };
20939
+ }
20940
+ async function setupOpenCodeV2(ctx) {
20941
+ ctx.catalog.transform(async (editor) => {
20942
+ if (!editor) return;
20943
+ const resolveVariants = (modelId) => {
20944
+ const mapping = TIER_MAPPING[modelId];
20945
+ if (!mapping) return void 0;
20946
+ const variants = [];
20947
+ if (mapping.minimal !== void 0) variants.push({ id: "minimal" });
20948
+ if (mapping.low !== void 0) variants.push({ id: "low" });
20949
+ if (mapping.medium !== void 0) variants.push({ id: "medium" });
20950
+ if (mapping.high !== void 0) variants.push({ id: "high" });
20951
+ return variants.length > 0 ? variants : void 0;
20952
+ };
20953
+ if (typeof editor?.provider?.update === "function") {
20954
+ editor.provider.update(AGY_PROVIDER_ID, (p) => {
20955
+ p.name = "Antigravity CLI";
20956
+ p.activation = "enabled";
20957
+ p.package = "aisdk:@ai-sdk/google";
20958
+ p.description = "Google Gemini Antigravity Code Assist OAuth provider";
20959
+ p.settings = { ...p.settings || {}, apiKey: "dummy" };
20960
+ p.integrationID = AGY_PROVIDER_ID;
20961
+ });
20962
+ if (typeof editor?.model?.update === "function") {
20963
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
20964
+ editor.model.update(AGY_PROVIDER_ID, modelId, (m) => {
20965
+ m.name = simple.name;
20966
+ m.capabilities = {
20967
+ tools: true,
20968
+ input: ["text", "image"],
20969
+ output: ["text"]
20970
+ };
20971
+ m.limit = {
20972
+ context: simple.maxTokens,
20973
+ output: simple.maxOutputTokens
20974
+ };
20975
+ m.family = "gemini";
20976
+ if (simple.cost) {
20977
+ m.cost = simple.cost;
20978
+ }
20979
+ const variants = resolveVariants(modelId);
20980
+ if (variants) {
20981
+ m.variants = variants;
20982
+ }
20983
+ });
20984
+ }
20985
+ }
20986
+ return;
20987
+ }
20988
+ const catalog = editor;
20989
+ catalog.providers = catalog.providers || {};
20990
+ catalog.providers[AGY_PROVIDER_ID] = {
20991
+ id: AGY_PROVIDER_ID,
20992
+ name: "Antigravity CLI",
20993
+ npm: "aisdk:@ai-sdk/google",
20994
+ settings: { apiKey: "dummy" },
20995
+ integrationID: AGY_PROVIDER_ID,
20996
+ models: { ...catalog.providers[AGY_PROVIDER_ID]?.models || {} },
20997
+ ...catalog.providers[AGY_PROVIDER_ID]
20998
+ };
20999
+ if (catalog.providers[AGY_PROVIDER_ID].settings) {
21000
+ catalog.providers[AGY_PROVIDER_ID].settings = {
21001
+ ...catalog.providers[AGY_PROVIDER_ID].settings,
21002
+ apiKey: "dummy"
21003
+ };
21004
+ } else {
21005
+ catalog.providers[AGY_PROVIDER_ID].settings = { apiKey: "dummy" };
21006
+ }
21007
+ catalog.providers[AGY_PROVIDER_ID].integrationID = AGY_PROVIDER_ID;
21008
+ const targetModels = catalog.providers[AGY_PROVIDER_ID].models;
21009
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21010
+ const isClaude = modelId.startsWith("claude-");
21011
+ const isGpt = modelId.startsWith("gpt-");
21012
+ const variants = resolveVariants(modelId);
21013
+ targetModels[modelId] = {
21014
+ id: modelId,
21015
+ providerID: AGY_PROVIDER_ID,
21016
+ name: simple.name,
21017
+ description: simple.description,
21018
+ family: modelId.includes("gemini") ? "gemini" : isClaude ? "claude" : isGpt ? "gpt" : "unknown",
21019
+ reasoning: simple.reasoning,
21020
+ attachment: simple.attachment,
21021
+ tool_call: simple.toolCall,
21022
+ limit: {
21023
+ context: simple.maxTokens,
21024
+ output: simple.maxOutputTokens
21025
+ },
21026
+ cost: simple.cost || { input: 0, output: 0 },
21027
+ ...variants ? { variants } : {},
21028
+ ...targetModels[modelId] || {}
21029
+ };
21030
+ }
21031
+ });
21032
+ ctx.tool.transform(async (editor) => {
21033
+ if (!editor) return;
21034
+ const quotaTool = createAgyQuotaTool({
21035
+ client: void 0,
21036
+ getAuthResolver: () => void 0,
21037
+ getConfiguredProjectId: () => void 0,
21038
+ getUserAgentModel: () => void 0
21039
+ });
21040
+ const quotaSummaryTool = createAgyQuotaSummaryTool({
21041
+ client: void 0,
21042
+ getAuthResolver: () => void 0,
21043
+ getConfiguredProjectId: () => void 0,
21044
+ getUserAgentModel: () => void 0
21045
+ });
21046
+ if (typeof editor.add === "function") {
21047
+ editor.add({
21048
+ name: AGY_QUOTA_TOOL_NAME,
21049
+ description: quotaTool.description,
21050
+ input: {},
21051
+ execute: async (args, context) => quotaTool.execute(args, context)
21052
+ });
21053
+ editor.add({
21054
+ name: AGY_QUOTA_SUMMARY_TOOL_NAME,
21055
+ description: quotaSummaryTool.description,
21056
+ input: {},
21057
+ execute: async (args, context) => quotaSummaryTool.execute(args, context)
21058
+ });
21059
+ } else if (typeof editor.set === "function") {
21060
+ editor.set(AGY_QUOTA_TOOL_NAME, quotaTool);
21061
+ editor.set(AGY_QUOTA_SUMMARY_TOOL_NAME, quotaSummaryTool);
21062
+ } else if (editor.tools && typeof editor.tools === "object") {
21063
+ editor.tools[AGY_QUOTA_TOOL_NAME] = quotaTool;
21064
+ editor.tools[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21065
+ } else if (typeof editor === "object") {
21066
+ editor[AGY_QUOTA_TOOL_NAME] = quotaTool;
21067
+ editor[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21068
+ }
21069
+ });
21070
+ ctx.command.transform(async (editor) => {
21071
+ if (!editor) return;
21072
+ const commands = {
21073
+ [AGY_V2_QUOTA_COMMAND]: {
21074
+ description: "Show Agy Code Assist quota usage",
21075
+ template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21076
+ },
21077
+ [AGY_V2_QUOTA_SUMMARY_COMMAND]: {
21078
+ description: "Show Agy Code Assist quota summary with weekly and 5-hour limits",
21079
+ template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21080
+ }
21081
+ };
21082
+ if (typeof editor.add === "function") {
21083
+ editor.add({
21084
+ name: AGY_V2_QUOTA_COMMAND,
21085
+ description: "Display current Antigravity quota usage",
21086
+ template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21087
+ });
21088
+ editor.add({
21089
+ name: AGY_V2_QUOTA_SUMMARY_COMMAND,
21090
+ description: "Display Antigravity quota summary grouped by model family",
21091
+ template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21092
+ });
21093
+ } else if (typeof editor.set === "function") {
21094
+ editor.set(AGY_V2_QUOTA_COMMAND, commands[AGY_V2_QUOTA_COMMAND]);
21095
+ editor.set(AGY_V2_QUOTA_SUMMARY_COMMAND, commands[AGY_V2_QUOTA_SUMMARY_COMMAND]);
21096
+ } else if (editor.commands && typeof editor.commands === "object") {
21097
+ editor.commands[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21098
+ editor.commands[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21099
+ } else if (typeof editor === "object") {
21100
+ editor[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21101
+ editor[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21102
+ }
21103
+ });
21104
+ ctx.integration?.transform?.((editor) => {
21105
+ if (!editor) return;
21106
+ editor.update?.(AGY_PROVIDER_ID, (integration) => {
21107
+ integration.name = "Antigravity CLI (plugin)";
21108
+ });
21109
+ editor.method?.update?.({
21110
+ integrationID: AGY_PROVIDER_ID,
21111
+ method: {
21112
+ id: "oauth",
21113
+ type: "oauth",
21114
+ label: "Antigravity CLI (OAuth)"
21115
+ },
21116
+ authorize: async () => {
21117
+ const authorization = await authorizeAgy();
21118
+ return {
21119
+ mode: "code",
21120
+ url: authorization.url,
21121
+ instructions: "Please complete Google account authorization in your browser. After authorization, copy the full redirect URL or code and paste it below:",
21122
+ callback: async (code) => {
21123
+ const trimmed = code.trim();
21124
+ const parsed = parseOAuthCallbackInput(trimmed);
21125
+ const authCode = parsed.code || trimmed;
21126
+ if (!authCode) {
21127
+ return { type: "failed", error: "Missing authorization code in callback input" };
21128
+ }
21129
+ if (parsed.state && parsed.state !== authorization.state) {
21130
+ return { type: "failed", error: "State mismatch in callback input (possible CSRF attempt)" };
21131
+ }
21132
+ const exchangeResult = await exchangeAgyWithVerifier(authCode, authorization.verifier);
21133
+ if (exchangeResult.type !== "success") {
21134
+ return exchangeResult;
21135
+ }
21136
+ const initialRefresh = formatRefreshParts({
21137
+ refreshToken: exchangeResult.refresh
21138
+ });
21139
+ let authRecord = {
21140
+ type: "oauth",
21141
+ refresh: initialRefresh,
21142
+ access: exchangeResult.access,
21143
+ expires: exchangeResult.expires
21144
+ };
21145
+ try {
21146
+ const projectContext = await ensureProjectContext(
21147
+ authRecord,
21148
+ { auth: { set: async () => {
21149
+ } } }
21150
+ );
21151
+ authRecord = {
21152
+ ...authRecord,
21153
+ refresh: projectContext.auth.refresh
21154
+ };
21155
+ } catch {
21156
+ }
21157
+ saveStoredAuthToJson(authRecord);
21158
+ return {
21159
+ type: "oauth",
21160
+ methodID: "oauth",
21161
+ refresh: authRecord.refresh,
21162
+ access: authRecord.access,
21163
+ expires: authRecord.expires
21164
+ };
21165
+ }
21166
+ };
21167
+ }
21168
+ });
21169
+ });
21170
+ ctx.aisdk?.hook("sdk", async (event) => {
21171
+ if (!event) return;
21172
+ const isMatchingProvider = event.providerID === AGY_PROVIDER_ID || event.model?.providerID === AGY_PROVIDER_ID;
21173
+ if (!isMatchingProvider) return;
21174
+ event.options = event.options || {};
21175
+ event.options.apiKey = "dummy";
21176
+ event.options.fetch = createV2FetchInterceptor();
21177
+ });
21178
+ ctx.session.hook(
21179
+ "http.request",
21180
+ async (event) => {
21181
+ if (!event) return;
21182
+ const rawUrl = typeof event.url === "string" ? event.url : event.request?.url || "";
21183
+ const isGL = isGenerativeLanguageRequest(rawUrl);
21184
+ const isInternal = rawUrl.includes("cloudcode-pa.googleapis.com");
21185
+ if (!isGL && !isInternal) {
21186
+ return;
21187
+ }
21188
+ event.headers = event.headers || {};
21189
+ let modelName;
21190
+ let rawAuth = event.auth;
21191
+ if (rawAuth && !rawAuth.type) {
21192
+ const tokenVal = rawAuth.access || rawAuth.token;
21193
+ if (tokenVal || rawAuth.refresh) {
21194
+ rawAuth = { type: "oauth", access: tokenVal, ...rawAuth };
21195
+ }
21196
+ }
21197
+ if (!rawAuth || !isOAuthAuth(rawAuth)) {
21198
+ rawAuth = loadStoredAuthFromJson();
21199
+ }
21200
+ let authRecord = rawAuth && isOAuthAuth(rawAuth) ? resolveCachedAuth(rawAuth) : void 0;
21201
+ if (authRecord && accessTokenExpired(authRecord)) {
21202
+ const refreshed = await refreshAccessToken(authRecord, { auth: { set: async () => {
21203
+ } } });
21204
+ if (refreshed) {
21205
+ authRecord = refreshed;
21206
+ saveStoredAuthToJson(refreshed);
21207
+ }
21208
+ }
21209
+ if (isGL) {
21210
+ const parsed = parseGenerativeLanguageRequest(rawUrl);
21211
+ modelName = parsed?.effectiveModel;
21212
+ if (typeof event.headers.delete === "function") {
21213
+ event.headers.delete("x-goog-api-key");
21214
+ event.headers.delete("api-key");
21215
+ } else {
21216
+ for (const key of Object.keys(event.headers)) {
21217
+ const lower = key.toLowerCase();
21218
+ if (lower === "x-goog-api-key" || lower === "api-key") {
21219
+ delete event.headers[key];
21220
+ }
21221
+ }
21222
+ }
21223
+ if (event.request?.headers) {
21224
+ if (typeof event.request.headers.delete === "function") {
21225
+ event.request.headers.delete("x-goog-api-key");
21226
+ event.request.headers.delete("api-key");
21227
+ } else {
21228
+ for (const key of Object.keys(event.request.headers)) {
21229
+ const lower = key.toLowerCase();
21230
+ if (lower === "x-goog-api-key" || lower === "api-key") {
21231
+ delete event.request.headers[key];
21232
+ }
21233
+ }
21234
+ }
21235
+ }
21236
+ let cleanUrl = rawUrl;
21237
+ try {
21238
+ const parsedUrl = new URL(rawUrl);
21239
+ let urlChanged = false;
21240
+ for (const param of ["key", "x-goog-api-key", "api-key"]) {
21241
+ if (parsedUrl.searchParams.has(param)) {
21242
+ parsedUrl.searchParams.delete(param);
21243
+ urlChanged = true;
21244
+ }
21245
+ }
21246
+ if (urlChanged) {
21247
+ cleanUrl = parsedUrl.toString();
21248
+ }
21249
+ } catch {
21250
+ }
21251
+ if (authRecord && authRecord.access) {
21252
+ let projectContext;
21253
+ try {
21254
+ projectContext = await ensureProjectContext(
21255
+ authRecord,
21256
+ { auth: { set: async () => {
21257
+ } } },
21258
+ void 0,
21259
+ modelName
21260
+ );
21261
+ } catch {
21262
+ projectContext = {
21263
+ effectiveProjectId: parseRefreshParts(authRecord.refresh).projectId || "antigravity",
21264
+ auth: authRecord
21265
+ };
21266
+ }
21267
+ const originalRequestedModel = modelName;
21268
+ let modifiedUrl = cleanUrl;
21269
+ if (originalRequestedModel) {
21270
+ const originalBase = originalRequestedModel.replace("google-agy/", "");
21271
+ const initHeaders = event.headers instanceof Headers ? event.headers : event.request?.headers;
21272
+ const resolvedBase = resolveModelTier2(originalBase, { headers: initHeaders });
21273
+ if (originalBase !== resolvedBase) {
21274
+ modifiedUrl = modifiedUrl.replace(`models/${originalBase}`, `models/${resolvedBase}`);
21275
+ }
21276
+ }
21277
+ let bodyPayload = event.body;
21278
+ if (bodyPayload === void 0 && event.request) {
21279
+ if (typeof event.request.clone === "function") {
21280
+ try {
21281
+ bodyPayload = await event.request.clone().text();
21282
+ } catch {
21283
+ }
21284
+ } else if (event.request.body !== void 0) {
21285
+ bodyPayload = event.request.body;
21286
+ }
21287
+ }
21288
+ let preExistingUserAgent;
21289
+ if (typeof event.headers?.get === "function") {
21290
+ preExistingUserAgent = event.headers.get("user-agent") || event.headers.get("User-Agent") || void 0;
21291
+ } else if (event.headers && typeof event.headers === "object") {
21292
+ preExistingUserAgent = event.headers["user-agent"] || event.headers["User-Agent"] || void 0;
21293
+ }
21294
+ if (!preExistingUserAgent && typeof event.request?.headers?.get === "function") {
21295
+ preExistingUserAgent = event.request.headers.get("user-agent") || event.request.headers.get("User-Agent") || void 0;
21296
+ } else if (!preExistingUserAgent && event.request?.headers && typeof event.request.headers === "object") {
21297
+ preExistingUserAgent = event.request.headers["user-agent"] || event.request.headers["User-Agent"] || void 0;
21298
+ }
21299
+ const method = event.method || event.request?.method || "POST";
21300
+ const requestHeaders = event.headers || event.request?.headers;
21301
+ const transformed = prepareAgyRequest(
21302
+ modifiedUrl,
21303
+ {
21304
+ method,
21305
+ headers: requestHeaders,
21306
+ body: bodyPayload
21307
+ },
21308
+ authRecord.access,
21309
+ projectContext.effectiveProjectId
21310
+ );
21311
+ const targetUrl = toUrlString2(transformed.request);
21312
+ if (typeof event.url === "string") {
21313
+ event.url = targetUrl;
21314
+ }
21315
+ if (event.request && typeof event.request === "object") {
21316
+ if (typeof Request !== "undefined" && event.request instanceof Request) {
21317
+ event.request = new Request(targetUrl, {
21318
+ method: transformed.init.method,
21319
+ headers: transformed.init.headers,
21320
+ body: transformed.init.body
21321
+ });
21322
+ } else if (typeof event.request.url === "string") {
21323
+ try {
21324
+ event.request.url = targetUrl;
21325
+ } catch {
21326
+ }
21327
+ }
21328
+ }
21329
+ const headerEntries = transformed.init.headers instanceof Headers ? Array.from(transformed.init.headers.entries()) : Object.entries(transformed.init.headers || {});
21330
+ for (const [k, v] of headerEntries) {
21331
+ const lowerK = k.toLowerCase();
21332
+ if (lowerK === "user-agent") {
21333
+ if (preExistingUserAgent) {
21334
+ continue;
21335
+ }
21336
+ if (typeof event.headers?.set === "function") {
21337
+ event.headers.set("User-Agent", v);
21338
+ } else if (event.headers) {
21339
+ event.headers["User-Agent"] = v;
21340
+ }
21341
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21342
+ event.request.headers.set("User-Agent", v);
21343
+ } else if (event.request?.headers && typeof event.request.headers === "object") {
21344
+ event.request.headers["User-Agent"] = v;
21345
+ }
21346
+ continue;
21347
+ }
21348
+ if (typeof event.headers?.set === "function") {
21349
+ event.headers.set(k, v);
21350
+ } else if (event.headers) {
21351
+ event.headers[k] = v;
21352
+ }
21353
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21354
+ event.request.headers.set(k, v);
21355
+ } else if (event.request?.headers && typeof event.request.headers === "object") {
21356
+ event.request.headers[k] = v;
21357
+ }
21358
+ }
21359
+ if (transformed.init.body !== void 0) {
21360
+ event.body = transformed.init.body;
21361
+ if (event.request && typeof event.request === "object" && !(event.request instanceof Request)) {
21362
+ event.request.body = transformed.init.body;
21363
+ }
21364
+ }
21365
+ } else {
21366
+ if (typeof event.url === "string") {
21367
+ event.url = cleanUrl;
21368
+ }
21369
+ if (event.request && typeof event.request === "object") {
21370
+ if (typeof event.request.url === "string") {
21371
+ event.request.url = cleanUrl;
21372
+ }
21373
+ }
21374
+ }
21375
+ }
21376
+ if (authRecord && authRecord.access) {
21377
+ if (typeof event.headers?.set === "function") {
21378
+ event.headers.set("Authorization", `Bearer ${authRecord.access}`);
21379
+ } else if (event.headers) {
21380
+ event.headers["Authorization"] = `Bearer ${authRecord.access}`;
21381
+ }
21382
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21383
+ event.request.headers.set("Authorization", `Bearer ${authRecord.access}`);
21384
+ } else if (event.request?.headers && typeof event.request.headers === "object") {
21385
+ event.request.headers["Authorization"] = `Bearer ${authRecord.access}`;
21386
+ }
21387
+ }
21388
+ const userAgent = buildAgyCliUserAgent(modelName);
21389
+ if (typeof event.headers?.set === "function") {
21390
+ if (!event.headers.get("User-Agent") && !event.headers.get("user-agent")) {
21391
+ event.headers.set("User-Agent", userAgent);
21392
+ }
21393
+ } else if (event.headers) {
21394
+ if (!event.headers["User-Agent"] && !event.headers["user-agent"]) {
21395
+ event.headers["User-Agent"] = userAgent;
21396
+ }
21397
+ }
21398
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21399
+ if (!event.request.headers.get("User-Agent") && !event.request.headers.get("user-agent")) {
21400
+ event.request.headers.set("User-Agent", userAgent);
21401
+ }
21402
+ } else if (event.request?.headers && typeof event.request.headers === "object") {
21403
+ if (!event.request.headers["User-Agent"] && !event.request.headers["user-agent"]) {
21404
+ event.request.headers["User-Agent"] = userAgent;
21405
+ }
21406
+ }
21407
+ },
21408
+ { providerID: AGY_PROVIDER_ID }
21409
+ );
21410
+ ctx.session.hook(
21411
+ "http.response",
21412
+ async (event) => {
21413
+ if (!event || !event.response) return;
21414
+ const rawUrl = typeof event.url === "string" ? event.url : event.request?.url || "";
21415
+ const isInternal = rawUrl.includes("cloudcode-pa.googleapis.com");
21416
+ if (isInternal && event.response instanceof Response) {
21417
+ const isStreaming = rawUrl.includes(":streamGenerateCode") || event.response.headers.get("content-type")?.includes("text/event-stream");
21418
+ const parsedModel = parseGenerativeLanguageRequest(rawUrl)?.effectiveModel;
21419
+ const transformed = transformAgyResponse(
21420
+ event.response,
21421
+ !!isStreaming,
21422
+ null,
21423
+ parsedModel,
21424
+ void 0,
21425
+ void 0
21426
+ );
21427
+ event.response = transformed;
21428
+ }
21429
+ },
21430
+ { providerID: AGY_PROVIDER_ID }
21431
+ );
21432
+ ctx.session.hook(
21433
+ "retry",
21434
+ async (event) => {
21435
+ if (!event) return;
21436
+ const response = event.response;
21437
+ if (response instanceof Response) {
21438
+ if (response.status === 429 || response.status === 503) {
21439
+ const quota = await classifyQuotaResponse(response);
21440
+ if (quota?.retryDelayMs) {
21441
+ event.retryDelayMs = quota.retryDelayMs;
21442
+ } else {
21443
+ event.retryDelayMs = await resolveRetryDelayMs(response, event.attempt || 1);
21444
+ }
21445
+ }
21446
+ } else if (event.details && Array.isArray(event.details)) {
21447
+ const retryInfo = event.details.find(
21448
+ (d) => d && d["@type"] === "type.googleapis.com/google.rpc.RetryInfo"
21449
+ );
21450
+ if (retryInfo?.retryDelay) {
21451
+ const delayMs = retryInternals.parseRetryDelayValue(retryInfo.retryDelay);
21452
+ if (delayMs !== null) {
21453
+ event.retryDelayMs = delayMs;
21454
+ }
21455
+ }
21456
+ }
21457
+ },
21458
+ { providerID: AGY_PROVIDER_ID }
21459
+ );
21460
+ }
21461
+ var v2PluginDefinition = defineOpenCodeV2Plugin({
21462
+ id: AGY_PROVIDER_ID,
21463
+ setup: setupOpenCodeV2
21464
+ });
21465
+
20672
21466
  // index.ts
20673
- var index_default = {
20674
- id: "@anthonyhaussman/opencode-agy-auth",
21467
+ var dualPlugin = {
21468
+ ...v2PluginDefinition,
20675
21469
  server: AgyCLIOAuthPlugin
20676
21470
  };
21471
+ var index_default = dualPlugin;
20677
21472
  export {
20678
21473
  AgyCLIOAuthPlugin,
20679
21474
  GoogleOAuthPlugin,
20680
- index_default as default
21475
+ index_default as default,
21476
+ defineOpenCodeV2Plugin,
21477
+ setupOpenCodeV2,
21478
+ v2PluginDefinition
20681
21479
  };
20682
21480
  //# sourceMappingURL=index.js.map