@anthonyhaussman/opencode-agy-auth 1.2.3-alpha.6 → 1.2.3-alpha.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/README.md CHANGED
@@ -8,6 +8,7 @@ An [OpenCode](https://opencode.ai/) authentication plugin that enables seamless
8
8
  - **Dynamic Model Retrieval**: Fetches available models based on user tier and current allocations.
9
9
  - **Quota Tracking**: Injects the `agy_quota` tool into OpenCode to check usage limits directly.
10
10
  - **Traffic Simulation**: Maintains background heartbeat with `agy` servers.
11
+ - **Dual OpenCode Compatibility**: Fully supports both OpenCode v1 (>= 1.18.29) and OpenCode v2 seamlessly without breaking changes.
11
12
 
12
13
  ## Installation
13
14
 
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { AgyCLIOAuthPlugin, GoogleOAuthPlugin } from "./src/plugin";
2
+ import { setupOpenCodeV2, v2PluginDefinition } from "./src/plugin/v2";
3
+ import type { DualOpenCodePlugin } from "./src/plugin/types";
2
4
  export { AgyCLIOAuthPlugin, GoogleOAuthPlugin };
3
- declare const _default: {
4
- id: string;
5
- server: typeof AgyCLIOAuthPlugin;
6
- };
7
- export default _default;
5
+ export { setupOpenCodeV2, v2PluginDefinition };
6
+ export * from "./src/plugin/types";
7
+ declare const dualPlugin: DualOpenCodePlugin;
8
+ export default dualPlugin;
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,621 @@ 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, readFileSync as readFileSync5 } 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 createV2FetchInterceptor(getAuthSnapshot) {
20815
+ return async function agyV2Fetch(input, init) {
20816
+ const isGL = isGenerativeLanguageRequest(input);
20817
+ const isInternal = toUrlString2(input).includes("cloudcode-pa.googleapis.com");
20818
+ if (!isGL && !isInternal) {
20819
+ return agyFetch(input, init);
20820
+ }
20821
+ let rawAuth = getAuthSnapshot ? await getAuthSnapshot() : void 0;
20822
+ if (!rawAuth) {
20823
+ rawAuth = loadStoredAuthFromJson();
20824
+ }
20825
+ if (!rawAuth || !isOAuthAuth(rawAuth)) {
20826
+ return agyFetch(input, init);
20827
+ }
20828
+ let authRecord = resolveCachedAuth(rawAuth);
20829
+ if (accessTokenExpired(authRecord)) {
20830
+ const refreshed = await refreshAccessToken(authRecord, { auth: { set: async () => {
20831
+ } } });
20832
+ if (refreshed) {
20833
+ authRecord = refreshed;
20834
+ }
20835
+ }
20836
+ if (!authRecord.access) {
20837
+ return agyFetch(input, init);
20838
+ }
20839
+ if (isInternal) {
20840
+ const hasAuth = getSafeHeader2(init?.headers, "Authorization") !== void 0;
20841
+ if (hasAuth) {
20842
+ return agyFetch(input, init);
20843
+ }
20844
+ const userAgent = buildAgyCliUserAgent();
20845
+ const headers = setSafeHeaders2(init?.headers, {
20846
+ Authorization: `Bearer ${authRecord.access}`,
20847
+ "User-Agent": userAgent
20848
+ });
20849
+ return agyFetch(input, {
20850
+ ...init,
20851
+ headers
20852
+ });
20853
+ }
20854
+ const requestTarget = parseGenerativeLanguageRequest(input);
20855
+ const requestUserAgentModel = requestTarget?.effectiveModel;
20856
+ let projectContext;
20857
+ try {
20858
+ projectContext = await ensureProjectContext(
20859
+ authRecord,
20860
+ { auth: { set: async () => {
20861
+ } } },
20862
+ void 0,
20863
+ requestUserAgentModel
20864
+ );
20865
+ } catch {
20866
+ projectContext = {
20867
+ effectiveProjectId: parseRefreshParts(authRecord.refresh).projectId || "antigravity",
20868
+ auth: authRecord
20869
+ };
20870
+ }
20871
+ const originalRequestedModel = parseGenerativeLanguageRequest(input)?.effectiveModel;
20872
+ let modifiedInput = input;
20873
+ if (isGL && originalRequestedModel) {
20874
+ const originalBase = originalRequestedModel.replace("google-agy/", "");
20875
+ const resolvedBase = resolveModelTier2(originalBase, init);
20876
+ if (originalBase !== resolvedBase) {
20877
+ if (typeof modifiedInput === "string") {
20878
+ modifiedInput = modifiedInput.replace(`models/${originalBase}`, `models/${resolvedBase}`);
20879
+ } else if (typeof Request !== "undefined" && modifiedInput instanceof Request) {
20880
+ const newUrl = modifiedInput.url.replace(`models/${originalBase}`, `models/${resolvedBase}`);
20881
+ modifiedInput = new Request(newUrl, modifiedInput);
20882
+ }
20883
+ }
20884
+ }
20885
+ const transformed = prepareAgyRequest(
20886
+ modifiedInput,
20887
+ init,
20888
+ authRecord.access,
20889
+ projectContext.effectiveProjectId,
20890
+ void 0
20891
+ );
20892
+ const chatLogger = createChatLogger();
20893
+ if (chatLogger) {
20894
+ chatLogger.logRequest(
20895
+ toUrlString2(transformed.request),
20896
+ transformed.init.method || "GET",
20897
+ transformed.init.headers,
20898
+ transformed.init.body
20899
+ );
20900
+ }
20901
+ const response = await fetchWithRetry(transformed.request, transformed.init);
20902
+ return transformAgyResponse(
20903
+ response,
20904
+ transformed.streaming,
20905
+ null,
20906
+ transformed.requestedModel,
20907
+ transformed.sessionId,
20908
+ chatLogger
20909
+ );
20910
+ };
20911
+ }
20912
+ async function setupOpenCodeV2(ctx) {
20913
+ ctx.catalog.transform(async (editor) => {
20914
+ if (!editor) return;
20915
+ const resolveVariants = (modelId) => {
20916
+ const mapping = TIER_MAPPING[modelId];
20917
+ if (!mapping) return void 0;
20918
+ const variants = [];
20919
+ if (mapping.minimal !== void 0) variants.push({ id: "minimal" });
20920
+ if (mapping.low !== void 0) variants.push({ id: "low" });
20921
+ if (mapping.medium !== void 0) variants.push({ id: "medium" });
20922
+ if (mapping.high !== void 0) variants.push({ id: "high" });
20923
+ return variants.length > 0 ? variants : void 0;
20924
+ };
20925
+ if (typeof editor?.provider?.update === "function") {
20926
+ editor.provider.update(AGY_PROVIDER_ID, (p) => {
20927
+ p.name = "Antigravity CLI";
20928
+ p.activation = "enabled";
20929
+ p.package = "aisdk:@ai-sdk/google";
20930
+ p.description = "Google Gemini Antigravity Code Assist OAuth provider";
20931
+ p.settings = { ...p.settings || {}, apiKey: "dummy" };
20932
+ p.integrationID = AGY_PROVIDER_ID;
20933
+ });
20934
+ if (typeof editor?.model?.update === "function") {
20935
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
20936
+ editor.model.update(AGY_PROVIDER_ID, modelId, (m) => {
20937
+ m.name = simple.name;
20938
+ m.capabilities = {
20939
+ tools: true,
20940
+ input: ["text", "image"],
20941
+ output: ["text"]
20942
+ };
20943
+ m.limit = {
20944
+ context: simple.maxTokens,
20945
+ output: simple.maxOutputTokens
20946
+ };
20947
+ m.family = "gemini";
20948
+ if (simple.cost) {
20949
+ m.cost = simple.cost;
20950
+ }
20951
+ const variants = resolveVariants(modelId);
20952
+ if (variants) {
20953
+ m.variants = variants;
20954
+ }
20955
+ });
20956
+ }
20957
+ }
20958
+ return;
20959
+ }
20960
+ const catalog = editor;
20961
+ catalog.providers = catalog.providers || {};
20962
+ catalog.providers[AGY_PROVIDER_ID] = {
20963
+ id: AGY_PROVIDER_ID,
20964
+ name: "Antigravity CLI",
20965
+ npm: "aisdk:@ai-sdk/google",
20966
+ settings: { apiKey: "dummy" },
20967
+ integrationID: AGY_PROVIDER_ID,
20968
+ models: { ...catalog.providers[AGY_PROVIDER_ID]?.models || {} },
20969
+ ...catalog.providers[AGY_PROVIDER_ID]
20970
+ };
20971
+ if (catalog.providers[AGY_PROVIDER_ID].settings) {
20972
+ catalog.providers[AGY_PROVIDER_ID].settings = {
20973
+ ...catalog.providers[AGY_PROVIDER_ID].settings,
20974
+ apiKey: "dummy"
20975
+ };
20976
+ } else {
20977
+ catalog.providers[AGY_PROVIDER_ID].settings = { apiKey: "dummy" };
20978
+ }
20979
+ catalog.providers[AGY_PROVIDER_ID].integrationID = AGY_PROVIDER_ID;
20980
+ const targetModels = catalog.providers[AGY_PROVIDER_ID].models;
20981
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
20982
+ const isClaude = modelId.startsWith("claude-");
20983
+ const isGpt = modelId.startsWith("gpt-");
20984
+ const variants = resolveVariants(modelId);
20985
+ targetModels[modelId] = {
20986
+ id: modelId,
20987
+ providerID: AGY_PROVIDER_ID,
20988
+ name: simple.name,
20989
+ description: simple.description,
20990
+ family: modelId.includes("gemini") ? "gemini" : isClaude ? "claude" : isGpt ? "gpt" : "unknown",
20991
+ reasoning: simple.reasoning,
20992
+ attachment: simple.attachment,
20993
+ tool_call: simple.toolCall,
20994
+ limit: {
20995
+ context: simple.maxTokens,
20996
+ output: simple.maxOutputTokens
20997
+ },
20998
+ cost: simple.cost || { input: 0, output: 0 },
20999
+ ...variants ? { variants } : {},
21000
+ ...targetModels[modelId] || {}
21001
+ };
21002
+ }
21003
+ });
21004
+ ctx.tool.transform(async (editor) => {
21005
+ if (!editor) return;
21006
+ const quotaTool = createAgyQuotaTool({
21007
+ client: void 0,
21008
+ getAuthResolver: () => void 0,
21009
+ getConfiguredProjectId: () => void 0,
21010
+ getUserAgentModel: () => void 0
21011
+ });
21012
+ const quotaSummaryTool = createAgyQuotaSummaryTool({
21013
+ client: void 0,
21014
+ getAuthResolver: () => void 0,
21015
+ getConfiguredProjectId: () => void 0,
21016
+ getUserAgentModel: () => void 0
21017
+ });
21018
+ if (typeof editor.add === "function") {
21019
+ editor.add({
21020
+ name: AGY_QUOTA_TOOL_NAME,
21021
+ description: quotaTool.description,
21022
+ input: {},
21023
+ execute: async (args, context) => quotaTool.execute(args, context)
21024
+ });
21025
+ editor.add({
21026
+ name: AGY_QUOTA_SUMMARY_TOOL_NAME,
21027
+ description: quotaSummaryTool.description,
21028
+ input: {},
21029
+ execute: async (args, context) => quotaSummaryTool.execute(args, context)
21030
+ });
21031
+ } else if (typeof editor.set === "function") {
21032
+ editor.set(AGY_QUOTA_TOOL_NAME, quotaTool);
21033
+ editor.set(AGY_QUOTA_SUMMARY_TOOL_NAME, quotaSummaryTool);
21034
+ } else if (editor.tools && typeof editor.tools === "object") {
21035
+ editor.tools[AGY_QUOTA_TOOL_NAME] = quotaTool;
21036
+ editor.tools[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21037
+ } else if (typeof editor === "object") {
21038
+ editor[AGY_QUOTA_TOOL_NAME] = quotaTool;
21039
+ editor[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21040
+ }
21041
+ });
21042
+ ctx.command.transform(async (editor) => {
21043
+ if (!editor) return;
21044
+ const commands = {
21045
+ [AGY_V2_QUOTA_COMMAND]: {
21046
+ description: "Show Agy Code Assist quota usage",
21047
+ template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21048
+ },
21049
+ [AGY_V2_QUOTA_SUMMARY_COMMAND]: {
21050
+ description: "Show Agy Code Assist quota summary with weekly and 5-hour limits",
21051
+ template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21052
+ }
21053
+ };
21054
+ if (typeof editor.add === "function") {
21055
+ editor.add({
21056
+ name: AGY_V2_QUOTA_COMMAND,
21057
+ description: "Display current Antigravity quota usage",
21058
+ template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21059
+ });
21060
+ editor.add({
21061
+ name: AGY_V2_QUOTA_SUMMARY_COMMAND,
21062
+ description: "Display Antigravity quota summary grouped by model family",
21063
+ template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21064
+ });
21065
+ } else if (typeof editor.set === "function") {
21066
+ editor.set(AGY_V2_QUOTA_COMMAND, commands[AGY_V2_QUOTA_COMMAND]);
21067
+ editor.set(AGY_V2_QUOTA_SUMMARY_COMMAND, commands[AGY_V2_QUOTA_SUMMARY_COMMAND]);
21068
+ } else if (editor.commands && typeof editor.commands === "object") {
21069
+ editor.commands[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21070
+ editor.commands[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21071
+ } else if (typeof editor === "object") {
21072
+ editor[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21073
+ editor[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21074
+ }
21075
+ });
21076
+ ctx.integration?.transform?.((editor) => {
21077
+ if (!editor) return;
21078
+ editor.update?.(AGY_PROVIDER_ID, (integration) => {
21079
+ integration.name = "Antigravity CLI (plugin)";
21080
+ });
21081
+ editor.method?.update?.({
21082
+ integrationID: AGY_PROVIDER_ID,
21083
+ method: {
21084
+ id: "oauth",
21085
+ type: "oauth",
21086
+ label: "Antigravity CLI (OAuth)"
21087
+ },
21088
+ authorize: async () => {
21089
+ const authorization = await authorizeAgy();
21090
+ return {
21091
+ mode: "code",
21092
+ url: authorization.url,
21093
+ instructions: "Please complete Google account authorization in your browser. After authorization, copy the full redirect URL or code and paste it below:",
21094
+ callback: async (code) => {
21095
+ const trimmed = code.trim();
21096
+ const parsed = parseOAuthCallbackInput(trimmed);
21097
+ const authCode = parsed.code || trimmed;
21098
+ if (!authCode) {
21099
+ return { type: "failed", error: "Missing authorization code in callback input" };
21100
+ }
21101
+ if (parsed.state && parsed.state !== authorization.state) {
21102
+ return { type: "failed", error: "State mismatch in callback input (possible CSRF attempt)" };
21103
+ }
21104
+ const exchangeResult = await exchangeAgyWithVerifier(authCode, authorization.verifier);
21105
+ if (exchangeResult.type !== "success") {
21106
+ return exchangeResult;
21107
+ }
21108
+ const initialRefresh = formatRefreshParts({
21109
+ refreshToken: exchangeResult.refresh
21110
+ });
21111
+ let authRecord = {
21112
+ type: "oauth",
21113
+ refresh: initialRefresh,
21114
+ access: exchangeResult.access,
21115
+ expires: exchangeResult.expires
21116
+ };
21117
+ try {
21118
+ const projectContext = await ensureProjectContext(
21119
+ authRecord,
21120
+ { auth: { set: async () => {
21121
+ } } }
21122
+ );
21123
+ authRecord = {
21124
+ ...authRecord,
21125
+ refresh: projectContext.auth.refresh
21126
+ };
21127
+ } catch {
21128
+ }
21129
+ return {
21130
+ type: "success",
21131
+ refresh: authRecord.refresh,
21132
+ access: authRecord.access,
21133
+ expires: authRecord.expires
21134
+ };
21135
+ }
21136
+ };
21137
+ }
21138
+ });
21139
+ });
21140
+ ctx.aisdk?.hook("sdk", async (event) => {
21141
+ if (!event) return;
21142
+ const isMatchingProvider = event.providerID === AGY_PROVIDER_ID || event.model?.providerID === AGY_PROVIDER_ID;
21143
+ if (!isMatchingProvider) return;
21144
+ event.options = event.options || {};
21145
+ event.options.apiKey = "dummy";
21146
+ event.options.fetch = createV2FetchInterceptor();
21147
+ });
21148
+ ctx.session.hook(
21149
+ "http.request",
21150
+ async (event) => {
21151
+ if (!event) return;
21152
+ const rawUrl = typeof event.url === "string" ? event.url : event.request?.url || "";
21153
+ const isGL = isGenerativeLanguageRequest(rawUrl);
21154
+ const isInternal = rawUrl.includes("cloudcode-pa.googleapis.com");
21155
+ if (!isGL && !isInternal) {
21156
+ return;
21157
+ }
21158
+ event.headers = event.headers || {};
21159
+ let modelName;
21160
+ if (isGL) {
21161
+ const parsed = parseGenerativeLanguageRequest(rawUrl);
21162
+ modelName = parsed?.effectiveModel;
21163
+ if (typeof event.headers.delete === "function") {
21164
+ event.headers.delete("x-goog-api-key");
21165
+ event.headers.delete("api-key");
21166
+ } else {
21167
+ for (const key of Object.keys(event.headers)) {
21168
+ const lower = key.toLowerCase();
21169
+ if (lower === "x-goog-api-key" || lower === "api-key") {
21170
+ delete event.headers[key];
21171
+ }
21172
+ }
21173
+ }
21174
+ if (event.request?.headers) {
21175
+ if (typeof event.request.headers.delete === "function") {
21176
+ event.request.headers.delete("x-goog-api-key");
21177
+ event.request.headers.delete("api-key");
21178
+ } else {
21179
+ for (const key of Object.keys(event.request.headers)) {
21180
+ const lower = key.toLowerCase();
21181
+ if (lower === "x-goog-api-key" || lower === "api-key") {
21182
+ delete event.request.headers[key];
21183
+ }
21184
+ }
21185
+ }
21186
+ }
21187
+ try {
21188
+ const parsedUrl = new URL(rawUrl);
21189
+ let urlChanged = false;
21190
+ for (const param of ["key", "x-goog-api-key", "api-key"]) {
21191
+ if (parsedUrl.searchParams.has(param)) {
21192
+ parsedUrl.searchParams.delete(param);
21193
+ urlChanged = true;
21194
+ }
21195
+ }
21196
+ if (urlChanged) {
21197
+ const cleanedUrl = parsedUrl.toString();
21198
+ if (typeof event.url === "string") {
21199
+ event.url = cleanedUrl;
21200
+ }
21201
+ if (event.request && typeof event.request === "object") {
21202
+ if (typeof event.request.url === "string") {
21203
+ event.request.url = cleanedUrl;
21204
+ }
21205
+ }
21206
+ }
21207
+ } catch {
21208
+ }
21209
+ const hasAuth = typeof event.headers?.get === "function" ? !!event.headers.get("Authorization") : event.headers && Object.keys(event.headers).some((k) => k.toLowerCase() === "authorization");
21210
+ if (!hasAuth) {
21211
+ let token;
21212
+ if (typeof event.auth?.access === "string" && event.auth.access) {
21213
+ token = event.auth.access;
21214
+ } else if (typeof event.auth?.token === "string" && event.auth.token) {
21215
+ token = event.auth.token;
21216
+ } else {
21217
+ const storedAuth = loadStoredAuthFromJson();
21218
+ if (storedAuth && isOAuthAuth(storedAuth)) {
21219
+ const resolved = resolveCachedAuth(storedAuth);
21220
+ token = resolved.access;
21221
+ }
21222
+ }
21223
+ if (token) {
21224
+ if (typeof event.headers?.set === "function") {
21225
+ event.headers.set("Authorization", `Bearer ${token}`);
21226
+ } else if (event.headers) {
21227
+ event.headers["Authorization"] = `Bearer ${token}`;
21228
+ }
21229
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21230
+ event.request.headers.set("Authorization", `Bearer ${token}`);
21231
+ }
21232
+ }
21233
+ }
21234
+ }
21235
+ const userAgent = buildAgyCliUserAgent(modelName);
21236
+ if (typeof event.headers.set === "function") {
21237
+ if (!event.headers.get("User-Agent")) {
21238
+ event.headers.set("User-Agent", userAgent);
21239
+ }
21240
+ } else {
21241
+ if (!event.headers["User-Agent"] && !event.headers["user-agent"]) {
21242
+ event.headers["User-Agent"] = userAgent;
21243
+ }
21244
+ }
21245
+ },
21246
+ { providerID: AGY_PROVIDER_ID }
21247
+ );
21248
+ ctx.session.hook(
21249
+ "http.response",
21250
+ async (event) => {
21251
+ if (!event) return;
21252
+ if (event.response?.status === 429) {
21253
+ return;
21254
+ }
21255
+ },
21256
+ { providerID: AGY_PROVIDER_ID }
21257
+ );
21258
+ ctx.session.hook(
21259
+ "retry",
21260
+ async (event) => {
21261
+ if (!event) return;
21262
+ const response = event.response;
21263
+ if (response instanceof Response) {
21264
+ if (response.status === 429 || response.status === 503) {
21265
+ const quota = await classifyQuotaResponse(response);
21266
+ if (quota?.retryDelayMs) {
21267
+ event.retryDelayMs = quota.retryDelayMs;
21268
+ } else {
21269
+ event.retryDelayMs = await resolveRetryDelayMs(response, event.attempt || 1);
21270
+ }
21271
+ }
21272
+ } else if (event.details && Array.isArray(event.details)) {
21273
+ const retryInfo = event.details.find(
21274
+ (d) => d && d["@type"] === "type.googleapis.com/google.rpc.RetryInfo"
21275
+ );
21276
+ if (retryInfo?.retryDelay) {
21277
+ const delayMs = retryInternals.parseRetryDelayValue(retryInfo.retryDelay);
21278
+ if (delayMs !== null) {
21279
+ event.retryDelayMs = delayMs;
21280
+ }
21281
+ }
21282
+ }
21283
+ },
21284
+ { providerID: AGY_PROVIDER_ID }
21285
+ );
21286
+ }
21287
+ var v2PluginDefinition = defineOpenCodeV2Plugin({
21288
+ id: AGY_PROVIDER_ID,
21289
+ setup: setupOpenCodeV2
21290
+ });
21291
+
20672
21292
  // index.ts
20673
- var index_default = {
20674
- id: "@anthonyhaussman/opencode-agy-auth",
21293
+ var dualPlugin = {
21294
+ ...v2PluginDefinition,
20675
21295
  server: AgyCLIOAuthPlugin
20676
21296
  };
21297
+ var index_default = dualPlugin;
20677
21298
  export {
20678
21299
  AgyCLIOAuthPlugin,
20679
21300
  GoogleOAuthPlugin,
20680
- index_default as default
21301
+ index_default as default,
21302
+ defineOpenCodeV2Plugin,
21303
+ setupOpenCodeV2,
21304
+ v2PluginDefinition
20681
21305
  };
20682
21306
  //# sourceMappingURL=index.js.map