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

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
  }
@@ -19612,6 +19595,23 @@ function normalizeToolSchemaTypes(tools, toolMapper) {
19612
19595
  obj.type = t.toUpperCase();
19613
19596
  }
19614
19597
  }
19598
+ if (Array.isArray(obj.enum)) {
19599
+ const sanitizedEnum = Array.from(
19600
+ new Set(
19601
+ obj.enum.filter((v) => v !== null && v !== void 0).map((v) => String(v))
19602
+ )
19603
+ );
19604
+ if (sanitizedEnum.length > 0) {
19605
+ obj.enum = sanitizedEnum;
19606
+ if (obj.type === "BOOLEAN") {
19607
+ obj.type = "STRING";
19608
+ }
19609
+ } else {
19610
+ delete obj.enum;
19611
+ }
19612
+ } else if ("enum" in obj) {
19613
+ delete obj.enum;
19614
+ }
19615
19615
  if (obj.properties && typeof obj.properties === "object") {
19616
19616
  Object.values(obj.properties).forEach(sanitizeSchema);
19617
19617
  }
@@ -20669,621 +20669,14 @@ function toUrlString(value) {
20669
20669
  return value.toString();
20670
20670
  }
20671
20671
 
20672
- // src/plugin/types.ts
20673
- function defineOpenCodeV2Plugin(def) {
20674
- return def;
20675
- }
20676
-
20677
- // src/plugin/v2.ts
20678
- import { homedir as homedir4 } from "os";
20679
- import { join as join6 } from "path";
20680
- import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
20681
- import "http";
20682
- var AGY_V2_QUOTA_COMMAND = "agy-quota";
20683
- var AGY_V2_QUOTA_SUMMARY_COMMAND = "agy-quota-summary";
20684
- var AGY_V2_QUOTA_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota usage for the current authenticated account.
20685
-
20686
- Immediately call \`${AGY_QUOTA_TOOL_NAME}\` with no arguments and return its output verbatim.
20687
- Do not call other tools.
20688
- `;
20689
- 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.
20690
-
20691
- Immediately call \`${AGY_QUOTA_SUMMARY_TOOL_NAME}\` with no arguments and return its output verbatim.
20692
- Do not call other tools.
20693
- `;
20694
- function getSafeHeader2(headers, key) {
20695
- if (!headers) {
20696
- return void 0;
20697
- }
20698
- const targetKey = key.toLowerCase();
20699
- if (typeof headers.get === "function") {
20700
- try {
20701
- return headers.get(targetKey) || void 0;
20702
- } catch {
20703
- }
20704
- }
20705
- if (Array.isArray(headers)) {
20706
- const found = headers.find((item) => {
20707
- if (Array.isArray(item) && typeof item[0] === "string") {
20708
- return item[0].toLowerCase() === targetKey;
20709
- }
20710
- return false;
20711
- });
20712
- return found ? String(found[1]) : void 0;
20713
- }
20714
- if (typeof headers === "object") {
20715
- const foundKey = Object.keys(headers).find((k) => k.toLowerCase() === targetKey);
20716
- return foundKey ? headers[foundKey] !== void 0 ? String(headers[foundKey]) : void 0 : void 0;
20717
- }
20718
- return void 0;
20719
- }
20720
- function setSafeHeaders2(initHeaders, newHeaders) {
20721
- if (typeof globalThis.Headers !== "undefined") {
20722
- const headers = new globalThis.Headers(initHeaders ?? {});
20723
- for (const [k, v] of Object.entries(newHeaders)) {
20724
- headers.set(k, v);
20725
- }
20726
- return headers;
20727
- }
20728
- if (Array.isArray(initHeaders)) {
20729
- const nextHeaders2 = [...initHeaders];
20730
- for (const [k, v] of Object.entries(newHeaders)) {
20731
- const idx = nextHeaders2.findIndex((item) => Array.isArray(item) && typeof item[0] === "string" && item[0].toLowerCase() === k.toLowerCase());
20732
- if (idx !== -1) {
20733
- nextHeaders2[idx] = [k, v];
20734
- } else {
20735
- nextHeaders2.push([k, v]);
20736
- }
20737
- }
20738
- return nextHeaders2;
20739
- }
20740
- const nextHeaders = {};
20741
- if (initHeaders && typeof initHeaders === "object") {
20742
- for (const [k, v] of Object.entries(initHeaders)) {
20743
- nextHeaders[k] = String(v);
20744
- }
20745
- }
20746
- for (const [k, v] of Object.entries(newHeaders)) {
20747
- const existingKey = Object.keys(nextHeaders).find((key) => key.toLowerCase() === k.toLowerCase());
20748
- if (existingKey) {
20749
- nextHeaders[existingKey] = v;
20750
- } else {
20751
- nextHeaders[k] = v;
20752
- }
20753
- }
20754
- return nextHeaders;
20755
- }
20756
- function toUrlString2(value) {
20757
- if (typeof value === "string") {
20758
- return value;
20759
- }
20760
- const candidate = value.url;
20761
- if (candidate) {
20762
- return candidate;
20763
- }
20764
- return value.toString();
20765
- }
20766
- function resolveModelTier2(baseModelId, init) {
20767
- const parts = baseModelId.split("@");
20768
- const base = parts[0] || "";
20769
- const suffixTier = parts[1]?.toLowerCase();
20770
- const mapping = TIER_MAPPING[base];
20771
- if (!mapping) {
20772
- return baseModelId;
20773
- }
20774
- const headerTier = getSafeHeader2(init?.headers, "x-agy-tier")?.toLowerCase() || null;
20775
- const requestedTier = headerTier || suffixTier;
20776
- if (requestedTier && Object.prototype.hasOwnProperty.call(mapping, requestedTier)) {
20777
- return mapping[requestedTier] || baseModelId;
20778
- }
20779
- return mapping["medium"] ?? mapping["high"];
20780
- }
20781
- var storedAuthOverrideForTesting = void 0;
20782
- function loadStoredAuthFromJson() {
20783
- if (storedAuthOverrideForTesting !== void 0) {
20784
- return storedAuthOverrideForTesting;
20785
- }
20786
- const authPath = join6(homedir4(), ".local", "share", "opencode", "auth.json");
20787
- try {
20788
- if (existsSync6(authPath)) {
20789
- const content = readFileSync5(authPath, "utf8");
20790
- const data = JSON.parse(content);
20791
- return data?.[AGY_PROVIDER_ID];
20792
- }
20793
- } catch {
20794
- }
20795
- return void 0;
20796
- }
20797
- function createV2FetchInterceptor(getAuthSnapshot) {
20798
- return async function agyV2Fetch(input, init) {
20799
- const isGL = isGenerativeLanguageRequest(input);
20800
- const isInternal = toUrlString2(input).includes("cloudcode-pa.googleapis.com");
20801
- if (!isGL && !isInternal) {
20802
- return agyFetch(input, init);
20803
- }
20804
- let rawAuth = getAuthSnapshot ? await getAuthSnapshot() : void 0;
20805
- if (!rawAuth) {
20806
- rawAuth = loadStoredAuthFromJson();
20807
- }
20808
- if (!rawAuth || !isOAuthAuth(rawAuth)) {
20809
- return agyFetch(input, init);
20810
- }
20811
- let authRecord = resolveCachedAuth(rawAuth);
20812
- if (accessTokenExpired(authRecord)) {
20813
- const refreshed = await refreshAccessToken(authRecord, { auth: { set: async () => {
20814
- } } });
20815
- if (refreshed) {
20816
- authRecord = refreshed;
20817
- }
20818
- }
20819
- if (!authRecord.access) {
20820
- return agyFetch(input, init);
20821
- }
20822
- if (isInternal) {
20823
- const hasAuth = getSafeHeader2(init?.headers, "Authorization") !== void 0;
20824
- if (hasAuth) {
20825
- return agyFetch(input, init);
20826
- }
20827
- const userAgent = buildAgyCliUserAgent();
20828
- const headers = setSafeHeaders2(init?.headers, {
20829
- Authorization: `Bearer ${authRecord.access}`,
20830
- "User-Agent": userAgent
20831
- });
20832
- return agyFetch(input, {
20833
- ...init,
20834
- headers
20835
- });
20836
- }
20837
- const requestTarget = parseGenerativeLanguageRequest(input);
20838
- const requestUserAgentModel = requestTarget?.effectiveModel;
20839
- let projectContext;
20840
- try {
20841
- projectContext = await ensureProjectContext(
20842
- authRecord,
20843
- { auth: { set: async () => {
20844
- } } },
20845
- void 0,
20846
- requestUserAgentModel
20847
- );
20848
- } catch {
20849
- projectContext = {
20850
- effectiveProjectId: parseRefreshParts(authRecord.refresh).projectId || "antigravity",
20851
- auth: authRecord
20852
- };
20853
- }
20854
- const originalRequestedModel = parseGenerativeLanguageRequest(input)?.effectiveModel;
20855
- let modifiedInput = input;
20856
- if (isGL && originalRequestedModel) {
20857
- const originalBase = originalRequestedModel.replace("google-agy/", "");
20858
- const resolvedBase = resolveModelTier2(originalBase, init);
20859
- if (originalBase !== resolvedBase) {
20860
- if (typeof modifiedInput === "string") {
20861
- modifiedInput = modifiedInput.replace(`models/${originalBase}`, `models/${resolvedBase}`);
20862
- } else if (typeof Request !== "undefined" && modifiedInput instanceof Request) {
20863
- const newUrl = modifiedInput.url.replace(`models/${originalBase}`, `models/${resolvedBase}`);
20864
- modifiedInput = new Request(newUrl, modifiedInput);
20865
- }
20866
- }
20867
- }
20868
- const transformed = prepareAgyRequest(
20869
- modifiedInput,
20870
- init,
20871
- authRecord.access,
20872
- projectContext.effectiveProjectId,
20873
- void 0
20874
- );
20875
- const chatLogger = createChatLogger();
20876
- if (chatLogger) {
20877
- chatLogger.logRequest(
20878
- toUrlString2(transformed.request),
20879
- transformed.init.method || "GET",
20880
- transformed.init.headers,
20881
- transformed.init.body
20882
- );
20883
- }
20884
- const response = await fetchWithRetry(transformed.request, transformed.init);
20885
- return transformAgyResponse(
20886
- response,
20887
- transformed.streaming,
20888
- null,
20889
- transformed.requestedModel,
20890
- transformed.sessionId,
20891
- chatLogger
20892
- );
20893
- };
20894
- }
20895
- async function setupOpenCodeV2(ctx) {
20896
- ctx.catalog.transform(async (editor) => {
20897
- if (!editor) return;
20898
- const resolveVariants = (modelId) => {
20899
- const mapping = TIER_MAPPING[modelId];
20900
- if (!mapping) return void 0;
20901
- const variants = [];
20902
- if (mapping.minimal !== void 0) variants.push({ id: "minimal" });
20903
- if (mapping.low !== void 0) variants.push({ id: "low" });
20904
- if (mapping.medium !== void 0) variants.push({ id: "medium" });
20905
- if (mapping.high !== void 0) variants.push({ id: "high" });
20906
- return variants.length > 0 ? variants : void 0;
20907
- };
20908
- if (typeof editor?.provider?.update === "function") {
20909
- editor.provider.update(AGY_PROVIDER_ID, (p) => {
20910
- p.name = "Antigravity CLI";
20911
- p.activation = "enabled";
20912
- p.package = "aisdk:@ai-sdk/google";
20913
- p.description = "Google Gemini Antigravity Code Assist OAuth provider";
20914
- p.settings = { ...p.settings || {}, apiKey: "dummy" };
20915
- p.integrationID = AGY_PROVIDER_ID;
20916
- });
20917
- if (typeof editor?.model?.update === "function") {
20918
- for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
20919
- editor.model.update(AGY_PROVIDER_ID, modelId, (m) => {
20920
- m.name = simple.name;
20921
- m.capabilities = {
20922
- tools: true,
20923
- input: ["text", "image"],
20924
- output: ["text"]
20925
- };
20926
- m.limit = {
20927
- context: simple.maxTokens,
20928
- output: simple.maxOutputTokens
20929
- };
20930
- m.family = "gemini";
20931
- if (simple.cost) {
20932
- m.cost = simple.cost;
20933
- }
20934
- const variants = resolveVariants(modelId);
20935
- if (variants) {
20936
- m.variants = variants;
20937
- }
20938
- });
20939
- }
20940
- }
20941
- return;
20942
- }
20943
- const catalog = editor;
20944
- catalog.providers = catalog.providers || {};
20945
- catalog.providers[AGY_PROVIDER_ID] = {
20946
- id: AGY_PROVIDER_ID,
20947
- name: "Antigravity CLI",
20948
- npm: "aisdk:@ai-sdk/google",
20949
- settings: { apiKey: "dummy" },
20950
- integrationID: AGY_PROVIDER_ID,
20951
- models: { ...catalog.providers[AGY_PROVIDER_ID]?.models || {} },
20952
- ...catalog.providers[AGY_PROVIDER_ID]
20953
- };
20954
- if (catalog.providers[AGY_PROVIDER_ID].settings) {
20955
- catalog.providers[AGY_PROVIDER_ID].settings = {
20956
- ...catalog.providers[AGY_PROVIDER_ID].settings,
20957
- apiKey: "dummy"
20958
- };
20959
- } else {
20960
- catalog.providers[AGY_PROVIDER_ID].settings = { apiKey: "dummy" };
20961
- }
20962
- catalog.providers[AGY_PROVIDER_ID].integrationID = AGY_PROVIDER_ID;
20963
- const targetModels = catalog.providers[AGY_PROVIDER_ID].models;
20964
- for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
20965
- const isClaude = modelId.startsWith("claude-");
20966
- const isGpt = modelId.startsWith("gpt-");
20967
- const variants = resolveVariants(modelId);
20968
- targetModels[modelId] = {
20969
- id: modelId,
20970
- providerID: AGY_PROVIDER_ID,
20971
- name: simple.name,
20972
- description: simple.description,
20973
- family: modelId.includes("gemini") ? "gemini" : isClaude ? "claude" : isGpt ? "gpt" : "unknown",
20974
- reasoning: simple.reasoning,
20975
- attachment: simple.attachment,
20976
- tool_call: simple.toolCall,
20977
- limit: {
20978
- context: simple.maxTokens,
20979
- output: simple.maxOutputTokens
20980
- },
20981
- cost: simple.cost || { input: 0, output: 0 },
20982
- ...variants ? { variants } : {},
20983
- ...targetModels[modelId] || {}
20984
- };
20985
- }
20986
- });
20987
- ctx.tool.transform(async (editor) => {
20988
- if (!editor) return;
20989
- const quotaTool = createAgyQuotaTool({
20990
- client: void 0,
20991
- getAuthResolver: () => void 0,
20992
- getConfiguredProjectId: () => void 0,
20993
- getUserAgentModel: () => void 0
20994
- });
20995
- const quotaSummaryTool = createAgyQuotaSummaryTool({
20996
- client: void 0,
20997
- getAuthResolver: () => void 0,
20998
- getConfiguredProjectId: () => void 0,
20999
- getUserAgentModel: () => void 0
21000
- });
21001
- if (typeof editor.add === "function") {
21002
- editor.add({
21003
- name: AGY_QUOTA_TOOL_NAME,
21004
- description: quotaTool.description,
21005
- input: {},
21006
- execute: async (args, context) => quotaTool.execute(args, context)
21007
- });
21008
- editor.add({
21009
- name: AGY_QUOTA_SUMMARY_TOOL_NAME,
21010
- description: quotaSummaryTool.description,
21011
- input: {},
21012
- execute: async (args, context) => quotaSummaryTool.execute(args, context)
21013
- });
21014
- } else if (typeof editor.set === "function") {
21015
- editor.set(AGY_QUOTA_TOOL_NAME, quotaTool);
21016
- editor.set(AGY_QUOTA_SUMMARY_TOOL_NAME, quotaSummaryTool);
21017
- } else if (editor.tools && typeof editor.tools === "object") {
21018
- editor.tools[AGY_QUOTA_TOOL_NAME] = quotaTool;
21019
- editor.tools[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21020
- } else if (typeof editor === "object") {
21021
- editor[AGY_QUOTA_TOOL_NAME] = quotaTool;
21022
- editor[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21023
- }
21024
- });
21025
- ctx.command.transform(async (editor) => {
21026
- if (!editor) return;
21027
- const commands = {
21028
- [AGY_V2_QUOTA_COMMAND]: {
21029
- description: "Show Agy Code Assist quota usage",
21030
- template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21031
- },
21032
- [AGY_V2_QUOTA_SUMMARY_COMMAND]: {
21033
- description: "Show Agy Code Assist quota summary with weekly and 5-hour limits",
21034
- template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21035
- }
21036
- };
21037
- if (typeof editor.add === "function") {
21038
- editor.add({
21039
- name: AGY_V2_QUOTA_COMMAND,
21040
- description: "Display current Antigravity quota usage",
21041
- template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21042
- });
21043
- editor.add({
21044
- name: AGY_V2_QUOTA_SUMMARY_COMMAND,
21045
- description: "Display Antigravity quota summary grouped by model family",
21046
- template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21047
- });
21048
- } else if (typeof editor.set === "function") {
21049
- editor.set(AGY_V2_QUOTA_COMMAND, commands[AGY_V2_QUOTA_COMMAND]);
21050
- editor.set(AGY_V2_QUOTA_SUMMARY_COMMAND, commands[AGY_V2_QUOTA_SUMMARY_COMMAND]);
21051
- } else if (editor.commands && typeof editor.commands === "object") {
21052
- editor.commands[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21053
- editor.commands[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21054
- } else if (typeof editor === "object") {
21055
- editor[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21056
- editor[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21057
- }
21058
- });
21059
- ctx.integration?.transform?.((editor) => {
21060
- if (!editor) return;
21061
- editor.update?.(AGY_PROVIDER_ID, (integration) => {
21062
- integration.name = "Antigravity CLI (plugin)";
21063
- });
21064
- editor.method?.update?.({
21065
- integrationID: AGY_PROVIDER_ID,
21066
- method: {
21067
- id: "oauth",
21068
- type: "oauth",
21069
- label: "Antigravity CLI (OAuth)"
21070
- },
21071
- authorize: async () => {
21072
- const authorization = await authorizeAgy();
21073
- return {
21074
- mode: "code",
21075
- url: authorization.url,
21076
- instructions: "Please complete Google account authorization in your browser. After authorization, copy the full redirect URL or code and paste it below:",
21077
- callback: async (code) => {
21078
- const trimmed = code.trim();
21079
- const parsed = parseOAuthCallbackInput(trimmed);
21080
- const authCode = parsed.code || trimmed;
21081
- if (!authCode) {
21082
- return { type: "failed", error: "Missing authorization code in callback input" };
21083
- }
21084
- if (parsed.state && parsed.state !== authorization.state) {
21085
- return { type: "failed", error: "State mismatch in callback input (possible CSRF attempt)" };
21086
- }
21087
- const exchangeResult = await exchangeAgyWithVerifier(authCode, authorization.verifier);
21088
- if (exchangeResult.type !== "success") {
21089
- return exchangeResult;
21090
- }
21091
- const initialRefresh = formatRefreshParts({
21092
- refreshToken: exchangeResult.refresh
21093
- });
21094
- let authRecord = {
21095
- type: "oauth",
21096
- refresh: initialRefresh,
21097
- access: exchangeResult.access,
21098
- expires: exchangeResult.expires
21099
- };
21100
- try {
21101
- const projectContext = await ensureProjectContext(
21102
- authRecord,
21103
- { auth: { set: async () => {
21104
- } } }
21105
- );
21106
- authRecord = {
21107
- ...authRecord,
21108
- refresh: projectContext.auth.refresh
21109
- };
21110
- } catch {
21111
- }
21112
- return {
21113
- type: "success",
21114
- refresh: authRecord.refresh,
21115
- access: authRecord.access,
21116
- expires: authRecord.expires
21117
- };
21118
- }
21119
- };
21120
- }
21121
- });
21122
- });
21123
- ctx.aisdk?.hook("sdk", async (event) => {
21124
- if (!event) return;
21125
- const isMatchingProvider = event.providerID === AGY_PROVIDER_ID || event.model?.providerID === AGY_PROVIDER_ID;
21126
- if (!isMatchingProvider) return;
21127
- event.options = event.options || {};
21128
- event.options.apiKey = "dummy";
21129
- event.options.fetch = createV2FetchInterceptor();
21130
- });
21131
- ctx.session.hook(
21132
- "http.request",
21133
- async (event) => {
21134
- if (!event) return;
21135
- const rawUrl = typeof event.url === "string" ? event.url : event.request?.url || "";
21136
- const isGL = isGenerativeLanguageRequest(rawUrl);
21137
- const isInternal = rawUrl.includes("cloudcode-pa.googleapis.com");
21138
- if (!isGL && !isInternal) {
21139
- return;
21140
- }
21141
- event.headers = event.headers || {};
21142
- let modelName;
21143
- if (isGL) {
21144
- const parsed = parseGenerativeLanguageRequest(rawUrl);
21145
- modelName = parsed?.effectiveModel;
21146
- if (typeof event.headers.delete === "function") {
21147
- event.headers.delete("x-goog-api-key");
21148
- event.headers.delete("api-key");
21149
- } else {
21150
- for (const key of Object.keys(event.headers)) {
21151
- const lower = key.toLowerCase();
21152
- if (lower === "x-goog-api-key" || lower === "api-key") {
21153
- delete event.headers[key];
21154
- }
21155
- }
21156
- }
21157
- if (event.request?.headers) {
21158
- if (typeof event.request.headers.delete === "function") {
21159
- event.request.headers.delete("x-goog-api-key");
21160
- event.request.headers.delete("api-key");
21161
- } else {
21162
- for (const key of Object.keys(event.request.headers)) {
21163
- const lower = key.toLowerCase();
21164
- if (lower === "x-goog-api-key" || lower === "api-key") {
21165
- delete event.request.headers[key];
21166
- }
21167
- }
21168
- }
21169
- }
21170
- try {
21171
- const parsedUrl = new URL(rawUrl);
21172
- let urlChanged = false;
21173
- for (const param of ["key", "x-goog-api-key", "api-key"]) {
21174
- if (parsedUrl.searchParams.has(param)) {
21175
- parsedUrl.searchParams.delete(param);
21176
- urlChanged = true;
21177
- }
21178
- }
21179
- if (urlChanged) {
21180
- const cleanedUrl = parsedUrl.toString();
21181
- if (typeof event.url === "string") {
21182
- event.url = cleanedUrl;
21183
- }
21184
- if (event.request && typeof event.request === "object") {
21185
- if (typeof event.request.url === "string") {
21186
- event.request.url = cleanedUrl;
21187
- }
21188
- }
21189
- }
21190
- } catch {
21191
- }
21192
- const hasAuth = typeof event.headers?.get === "function" ? !!event.headers.get("Authorization") : event.headers && Object.keys(event.headers).some((k) => k.toLowerCase() === "authorization");
21193
- if (!hasAuth) {
21194
- let token;
21195
- if (typeof event.auth?.access === "string" && event.auth.access) {
21196
- token = event.auth.access;
21197
- } else if (typeof event.auth?.token === "string" && event.auth.token) {
21198
- token = event.auth.token;
21199
- } else {
21200
- const storedAuth = loadStoredAuthFromJson();
21201
- if (storedAuth && isOAuthAuth(storedAuth)) {
21202
- const resolved = resolveCachedAuth(storedAuth);
21203
- token = resolved.access;
21204
- }
21205
- }
21206
- if (token) {
21207
- if (typeof event.headers?.set === "function") {
21208
- event.headers.set("Authorization", `Bearer ${token}`);
21209
- } else if (event.headers) {
21210
- event.headers["Authorization"] = `Bearer ${token}`;
21211
- }
21212
- if (event.request?.headers && typeof event.request.headers.set === "function") {
21213
- event.request.headers.set("Authorization", `Bearer ${token}`);
21214
- }
21215
- }
21216
- }
21217
- }
21218
- const userAgent = buildAgyCliUserAgent(modelName);
21219
- if (typeof event.headers.set === "function") {
21220
- if (!event.headers.get("User-Agent")) {
21221
- event.headers.set("User-Agent", userAgent);
21222
- }
21223
- } else {
21224
- if (!event.headers["User-Agent"] && !event.headers["user-agent"]) {
21225
- event.headers["User-Agent"] = userAgent;
21226
- }
21227
- }
21228
- },
21229
- { providerID: AGY_PROVIDER_ID }
21230
- );
21231
- ctx.session.hook(
21232
- "http.response",
21233
- async (event) => {
21234
- if (!event) return;
21235
- if (event.response?.status === 429) {
21236
- return;
21237
- }
21238
- },
21239
- { providerID: AGY_PROVIDER_ID }
21240
- );
21241
- ctx.session.hook(
21242
- "retry",
21243
- async (event) => {
21244
- if (!event) return;
21245
- const response = event.response;
21246
- if (response instanceof Response) {
21247
- if (response.status === 429 || response.status === 503) {
21248
- const quota = await classifyQuotaResponse(response);
21249
- if (quota?.retryDelayMs) {
21250
- event.retryDelayMs = quota.retryDelayMs;
21251
- } else {
21252
- event.retryDelayMs = await resolveRetryDelayMs(response, event.attempt || 1);
21253
- }
21254
- }
21255
- } else if (event.details && Array.isArray(event.details)) {
21256
- const retryInfo = event.details.find(
21257
- (d) => d && d["@type"] === "type.googleapis.com/google.rpc.RetryInfo"
21258
- );
21259
- if (retryInfo?.retryDelay) {
21260
- const delayMs = retryInternals.parseRetryDelayValue(retryInfo.retryDelay);
21261
- if (delayMs !== null) {
21262
- event.retryDelayMs = delayMs;
21263
- }
21264
- }
21265
- }
21266
- },
21267
- { providerID: AGY_PROVIDER_ID }
21268
- );
21269
- }
21270
- var v2PluginDefinition = defineOpenCodeV2Plugin({
21271
- id: AGY_PROVIDER_ID,
21272
- setup: setupOpenCodeV2
21273
- });
21274
-
21275
20672
  // index.ts
21276
- var dualPlugin = {
21277
- ...v2PluginDefinition,
20673
+ var index_default = {
20674
+ id: "@anthonyhaussman/opencode-agy-auth",
21278
20675
  server: AgyCLIOAuthPlugin
21279
20676
  };
21280
- var index_default = dualPlugin;
21281
20677
  export {
21282
20678
  AgyCLIOAuthPlugin,
21283
20679
  GoogleOAuthPlugin,
21284
- index_default as default,
21285
- defineOpenCodeV2Plugin,
21286
- setupOpenCodeV2,
21287
- v2PluginDefinition
20680
+ index_default as default
21288
20681
  };
21289
20682
  //# sourceMappingURL=index.js.map