@anthonyhaussman/opencode-agy-auth 1.2.16-alpha.0 → 1.2.16-alpha.2

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
  }
@@ -15320,6 +15337,12 @@ function formatRelativeResetTime(resetTime) {
15320
15337
 
15321
15338
  // src/plugin/quota.ts
15322
15339
  var AGY_QUOTA_TOOL_NAME = "agy_quota";
15340
+ var AGY_V2_QUOTA_COMMAND = "agy-quota";
15341
+ var AGY_V2_QUOTA_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota usage for the current authenticated account.
15342
+
15343
+ Immediately call \`${AGY_QUOTA_TOOL_NAME}\` with no arguments and return its output verbatim.
15344
+ Do not call other tools.
15345
+ `;
15323
15346
  function createAgyQuotaTool({
15324
15347
  client,
15325
15348
  getAuthResolver,
@@ -15559,6 +15582,12 @@ function splitModelVariant(modelId) {
15559
15582
 
15560
15583
  // src/plugin/quota-summary.ts
15561
15584
  var AGY_QUOTA_SUMMARY_TOOL_NAME = "agy_quota_summary";
15585
+ var AGY_V2_QUOTA_SUMMARY_COMMAND = "agy-quota-summary";
15586
+ 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.
15587
+
15588
+ Immediately call \`${AGY_QUOTA_SUMMARY_TOOL_NAME}\` with no arguments and return its output verbatim.
15589
+ Do not call other tools.
15590
+ `;
15562
15591
  function createAgyQuotaSummaryTool({
15563
15592
  client,
15564
15593
  getAuthResolver,
@@ -19656,6 +19685,34 @@ function getModelEnum(modelName) {
19656
19685
  }
19657
19686
  return "MODEL_PLACEHOLDER_M16";
19658
19687
  }
19688
+ function isClaudeModel(model) {
19689
+ return model.toLowerCase().includes("claude");
19690
+ }
19691
+ function sanitizeClaudeThinkingParts(contents, model) {
19692
+ if (!isClaudeModel(model) || !Array.isArray(contents)) {
19693
+ return;
19694
+ }
19695
+ for (const turn of contents) {
19696
+ if (!turn || typeof turn !== "object") continue;
19697
+ if (turn.role !== "model" && turn.role !== "assistant") continue;
19698
+ if (!Array.isArray(turn.parts)) continue;
19699
+ const filteredParts = turn.parts.filter((part) => {
19700
+ if (!part || typeof part !== "object") return true;
19701
+ const isThinking = part.thought === true || part.type === "thinking" || typeof part.thinking === "string";
19702
+ if (!isThinking) {
19703
+ return true;
19704
+ }
19705
+ const sig = typeof part.signature === "string" ? part.signature : typeof part.thoughtSignature === "string" ? part.thoughtSignature : void 0;
19706
+ const isValidSig = typeof sig === "string" && sig.length > 0 && sig !== "skip_thought_signature_validator";
19707
+ return isValidSig;
19708
+ });
19709
+ if (filteredParts.length === 0) {
19710
+ turn.parts = [{ text: "" }];
19711
+ } else {
19712
+ turn.parts = filteredParts;
19713
+ }
19714
+ }
19715
+ }
19659
19716
  function transformRequestBody(body, projectId, effectiveModel, requestedModel, thinkingConfigDefaults) {
19660
19717
  const fallbackId = randomUUID3();
19661
19718
  try {
@@ -19689,7 +19746,7 @@ function transformRequestBody(body, projectId, effectiveModel, requestedModel, t
19689
19746
  last_step_index: "0",
19690
19747
  model_enum: getModelEnum(effectiveModel),
19691
19748
  trajectory_id: randomUUID3(),
19692
- used_claude: "false",
19749
+ used_claude: isClaudeModel(effectiveModel) || isClaudeModel(requestedModel) ? "true" : "false",
19693
19750
  used_claude_conservative: "false"
19694
19751
  };
19695
19752
  }
@@ -19717,6 +19774,7 @@ function transformRequestBody(body, projectId, effectiveModel, requestedModel, t
19717
19774
  contents2 = ensureTrailingUserTurn(contents2);
19718
19775
  const latestSig = getLatestSignature(sessionId2);
19719
19776
  applyLatestSignature(contents2, latestSig);
19777
+ sanitizeClaudeThinkingParts(contents2, effectiveModel || requestedModel);
19720
19778
  requestPayloadInside.contents = contents2;
19721
19779
  }
19722
19780
  return { body: JSON.stringify(wrappedBody2), userPromptId: userPromptId2, sessionId: sessionId2 };
@@ -19758,6 +19816,7 @@ function transformRequestBody(body, projectId, effectiveModel, requestedModel, t
19758
19816
  contents = ensureTrailingUserTurn(contents);
19759
19817
  const latestSig = getLatestSignature(sessionId);
19760
19818
  applyLatestSignature(contents, latestSig);
19819
+ sanitizeClaudeThinkingParts(contents, effectiveModel || requestedModel);
19761
19820
  requestPayload.contents = contents;
19762
19821
  }
19763
19822
  if ("model" in requestPayload) {
@@ -19769,7 +19828,7 @@ function transformRequestBody(body, projectId, effectiveModel, requestedModel, t
19769
19828
  last_step_index: "0",
19770
19829
  model_enum: getModelEnum(effectiveModel),
19771
19830
  trajectory_id: randomUUID3(),
19772
- used_claude: "false",
19831
+ used_claude: isClaudeModel(effectiveModel) || isClaudeModel(requestedModel) ? "true" : "false",
19773
19832
  used_claude_conservative: "false"
19774
19833
  };
19775
19834
  }
@@ -19928,9 +19987,14 @@ function normalizeToolSchemaTypes(tools, toolMapper) {
19928
19987
  fn.name = toolMapper ? toolMapper.toGemini(fn.name) : sanitizeToolName(fn.name);
19929
19988
  }
19930
19989
  if (fn) {
19990
+ if (!fn.parameters) {
19991
+ fn.parameters = fn.parameters_json_schema ?? fn.parametersJsonSchema;
19992
+ }
19931
19993
  if (!fn.parameters) {
19932
19994
  fn.parameters = { type: "OBJECT", properties: {} };
19933
19995
  }
19996
+ delete fn.parameters_json_schema;
19997
+ delete fn.parametersJsonSchema;
19934
19998
  sanitizeSchema(fn.parameters);
19935
19999
  }
19936
20000
  }
@@ -20355,22 +20419,81 @@ var ChatLoggerImpl = class {
20355
20419
  }
20356
20420
  };
20357
20421
 
20358
- // src/plugin.ts
20359
- var AGY_QUOTA_COMMAND = "agyquota";
20360
- var AGY_QUOTA_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota usage for the current authenticated account.
20361
-
20362
- Immediately call \`${AGY_QUOTA_TOOL_NAME}\` with no arguments and return its output verbatim.
20363
- Do not call other tools.
20364
- `;
20365
- var AGY_QUOTA_SUMMARY_COMMAND = "agyquotasummary";
20366
- var AGY_QUOTA_SUMMARY_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota summary (weekly and 5-hour limits by model group) for the current authenticated account.
20422
+ // src/plugin/headers.ts
20423
+ function getSafeHeader(headers, key) {
20424
+ if (!headers) {
20425
+ return void 0;
20426
+ }
20427
+ const targetKey = key.toLowerCase();
20428
+ if (typeof headers.get === "function") {
20429
+ try {
20430
+ return headers.get(targetKey) || void 0;
20431
+ } catch {
20432
+ }
20433
+ }
20434
+ if (Array.isArray(headers)) {
20435
+ const found = headers.find((item) => {
20436
+ if (Array.isArray(item) && typeof item[0] === "string") {
20437
+ return item[0].toLowerCase() === targetKey;
20438
+ }
20439
+ return false;
20440
+ });
20441
+ return found ? String(found[1]) : void 0;
20442
+ }
20443
+ if (typeof headers === "object") {
20444
+ const foundKey = Object.keys(headers).find((k) => k.toLowerCase() === targetKey);
20445
+ return foundKey ? headers[foundKey] !== void 0 ? String(headers[foundKey]) : void 0 : void 0;
20446
+ }
20447
+ return void 0;
20448
+ }
20449
+ function setSafeHeaders(initHeaders, newHeaders) {
20450
+ if (typeof globalThis.Headers !== "undefined") {
20451
+ const headers = new globalThis.Headers(initHeaders ?? {});
20452
+ for (const [k, v] of Object.entries(newHeaders)) {
20453
+ headers.set(k, v);
20454
+ }
20455
+ return headers;
20456
+ }
20457
+ if (Array.isArray(initHeaders)) {
20458
+ const nextHeaders2 = [...initHeaders];
20459
+ for (const [k, v] of Object.entries(newHeaders)) {
20460
+ const idx = nextHeaders2.findIndex((item) => Array.isArray(item) && typeof item[0] === "string" && item[0].toLowerCase() === k.toLowerCase());
20461
+ if (idx !== -1) {
20462
+ nextHeaders2[idx] = [k, v];
20463
+ } else {
20464
+ nextHeaders2.push([k, v]);
20465
+ }
20466
+ }
20467
+ return nextHeaders2;
20468
+ }
20469
+ const nextHeaders = {};
20470
+ if (initHeaders && typeof initHeaders === "object") {
20471
+ for (const [k, v] of Object.entries(initHeaders)) {
20472
+ nextHeaders[k] = String(v);
20473
+ }
20474
+ }
20475
+ for (const [k, v] of Object.entries(newHeaders)) {
20476
+ const existingKey = Object.keys(nextHeaders).find((key) => key.toLowerCase() === k.toLowerCase());
20477
+ if (existingKey) {
20478
+ nextHeaders[existingKey] = v;
20479
+ } else {
20480
+ nextHeaders[k] = v;
20481
+ }
20482
+ }
20483
+ return nextHeaders;
20484
+ }
20485
+ function toUrlString(value) {
20486
+ if (typeof value === "string") {
20487
+ return value;
20488
+ }
20489
+ const candidate = value.url;
20490
+ if (candidate) {
20491
+ return candidate;
20492
+ }
20493
+ return value.toString();
20494
+ }
20367
20495
 
20368
- Immediately call \`${AGY_QUOTA_SUMMARY_TOOL_NAME}\` with no arguments and return its output verbatim.
20369
- Do not call other tools.
20370
- `;
20371
- var latestAgyAuthResolver;
20372
- var latestAgyConfiguredProjectId;
20373
- var latestAgyUserAgentModel;
20496
+ // src/plugin/tier.ts
20374
20497
  var STATIC_MODELS_SIMPLE = {
20375
20498
  "gemini-3.8-flash": {
20376
20499
  name: "Gemini 3.8 Flash",
@@ -20468,6 +20591,39 @@ var TIER_MAPPING = {
20468
20591
  high: "claude-sonnet-5-5-high"
20469
20592
  }
20470
20593
  };
20594
+ function resolveModelTier(baseModelId, headersOrInit) {
20595
+ const parts = baseModelId.split("@");
20596
+ const base = parts[0] || "";
20597
+ const suffixTier = parts[1]?.toLowerCase();
20598
+ const mapping = TIER_MAPPING[base];
20599
+ if (!mapping) {
20600
+ return baseModelId;
20601
+ }
20602
+ const rawHeaders = headersOrInit && typeof headersOrInit === "object" && "headers" in headersOrInit ? headersOrInit.headers : headersOrInit;
20603
+ const headerTier = getSafeHeader(rawHeaders, "x-agy-tier")?.toLowerCase() || null;
20604
+ const requestedTier = headerTier || suffixTier;
20605
+ if (requestedTier && Object.prototype.hasOwnProperty.call(mapping, requestedTier)) {
20606
+ return mapping[requestedTier] || baseModelId;
20607
+ }
20608
+ return mapping["medium"] ?? mapping["high"] ?? baseModelId;
20609
+ }
20610
+
20611
+ // src/plugin.ts
20612
+ var AGY_QUOTA_COMMAND = "agyquota";
20613
+ var AGY_QUOTA_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota usage for the current authenticated account.
20614
+
20615
+ Immediately call \`${AGY_QUOTA_TOOL_NAME}\` with no arguments and return its output verbatim.
20616
+ Do not call other tools.
20617
+ `;
20618
+ var AGY_QUOTA_SUMMARY_COMMAND = "agyquotasummary";
20619
+ var AGY_QUOTA_SUMMARY_COMMAND_TEMPLATE = `Retrieve Agy Code Assist quota summary (weekly and 5-hour limits by model group) for the current authenticated account.
20620
+
20621
+ Immediately call \`${AGY_QUOTA_SUMMARY_TOOL_NAME}\` with no arguments and return its output verbatim.
20622
+ Do not call other tools.
20623
+ `;
20624
+ var latestAgyAuthResolver;
20625
+ var latestAgyConfiguredProjectId;
20626
+ var latestAgyUserAgentModel;
20471
20627
  var buildModelFromSimple = (modelId, simple) => {
20472
20628
  const isClaude = modelId.startsWith("claude-");
20473
20629
  const isGpt = modelId.startsWith("gpt-");
@@ -20561,83 +20717,6 @@ var STATIC_MODELS = {};
20561
20717
  for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
20562
20718
  STATIC_MODELS[modelId] = buildModelFromSimple(modelId, simple);
20563
20719
  }
20564
- function getSafeHeader(headers, key) {
20565
- if (!headers) {
20566
- return void 0;
20567
- }
20568
- const targetKey = key.toLowerCase();
20569
- if (typeof headers.get === "function") {
20570
- try {
20571
- return headers.get(targetKey) || void 0;
20572
- } catch {
20573
- }
20574
- }
20575
- if (Array.isArray(headers)) {
20576
- const found = headers.find((item) => {
20577
- if (Array.isArray(item) && typeof item[0] === "string") {
20578
- return item[0].toLowerCase() === targetKey;
20579
- }
20580
- return false;
20581
- });
20582
- return found ? String(found[1]) : void 0;
20583
- }
20584
- if (typeof headers === "object") {
20585
- const foundKey = Object.keys(headers).find((k) => k.toLowerCase() === targetKey);
20586
- return foundKey ? headers[foundKey] !== void 0 ? String(headers[foundKey]) : void 0 : void 0;
20587
- }
20588
- return void 0;
20589
- }
20590
- function setSafeHeaders(initHeaders, newHeaders) {
20591
- if (typeof globalThis.Headers !== "undefined") {
20592
- const headers = new globalThis.Headers(initHeaders ?? {});
20593
- for (const [k, v] of Object.entries(newHeaders)) {
20594
- headers.set(k, v);
20595
- }
20596
- return headers;
20597
- }
20598
- if (Array.isArray(initHeaders)) {
20599
- const nextHeaders2 = [...initHeaders];
20600
- for (const [k, v] of Object.entries(newHeaders)) {
20601
- const idx = nextHeaders2.findIndex((item) => Array.isArray(item) && typeof item[0] === "string" && item[0].toLowerCase() === k.toLowerCase());
20602
- if (idx !== -1) {
20603
- nextHeaders2[idx] = [k, v];
20604
- } else {
20605
- nextHeaders2.push([k, v]);
20606
- }
20607
- }
20608
- return nextHeaders2;
20609
- }
20610
- const nextHeaders = {};
20611
- if (initHeaders && typeof initHeaders === "object") {
20612
- for (const [k, v] of Object.entries(initHeaders)) {
20613
- nextHeaders[k] = String(v);
20614
- }
20615
- }
20616
- for (const [k, v] of Object.entries(newHeaders)) {
20617
- const existingKey = Object.keys(nextHeaders).find((key) => key.toLowerCase() === k.toLowerCase());
20618
- if (existingKey) {
20619
- nextHeaders[existingKey] = v;
20620
- } else {
20621
- nextHeaders[k] = v;
20622
- }
20623
- }
20624
- return nextHeaders;
20625
- }
20626
- function resolveModelTier(baseModelId, init) {
20627
- const parts = baseModelId.split("@");
20628
- const base = parts[0] || "";
20629
- const suffixTier = parts[1]?.toLowerCase();
20630
- const mapping = TIER_MAPPING[base];
20631
- if (!mapping) {
20632
- return baseModelId;
20633
- }
20634
- const headerTier = getSafeHeader(init?.headers, "x-agy-tier")?.toLowerCase() || null;
20635
- const requestedTier = headerTier || suffixTier;
20636
- if (requestedTier && Object.prototype.hasOwnProperty.call(mapping, requestedTier)) {
20637
- return mapping[requestedTier] || baseModelId;
20638
- }
20639
- return mapping["medium"] ?? mapping["high"];
20640
- }
20641
20720
  var AgyCLIOAuthPlugin = async ({ client }) => {
20642
20721
  let latestConfig;
20643
20722
  updateStaticModelsWithPricing(STATIC_MODELS);
@@ -20965,25 +21044,782 @@ async function ensureProjectContextOrThrow(authRecord, client, configuredProject
20965
21044
  throw error45;
20966
21045
  }
20967
21046
  }
20968
- function toUrlString(value) {
20969
- if (typeof value === "string") {
20970
- return value;
21047
+
21048
+ // src/plugin/types.ts
21049
+ function defineOpenCodeV2Plugin(def) {
21050
+ return def;
21051
+ }
21052
+
21053
+ // src/plugin/v2-storage.ts
21054
+ import { closeSync, existsSync as existsSync6, mkdirSync as mkdirSync5, openSync, readFileSync as readFileSync5, renameSync as renameSync4, unlinkSync as unlinkSync4, writeFileSync as writeFileSync5 } from "fs";
21055
+ import { randomUUID as randomUUID4 } from "crypto";
21056
+ import { homedir as homedir4 } from "os";
21057
+ import { join as join6 } from "path";
21058
+ var storedAuthOverrideForTesting = void 0;
21059
+ function loadStoredAuthFromJson() {
21060
+ if (storedAuthOverrideForTesting !== void 0) {
21061
+ return storedAuthOverrideForTesting;
21062
+ }
21063
+ const authPath = join6(homedir4(), ".local", "share", "opencode", "auth.json");
21064
+ try {
21065
+ if (existsSync6(authPath)) {
21066
+ const content = readFileSync5(authPath, "utf8");
21067
+ const data = JSON.parse(content);
21068
+ return data?.[AGY_PROVIDER_ID];
21069
+ }
21070
+ } catch {
20971
21071
  }
20972
- const candidate = value.url;
20973
- if (candidate) {
20974
- return candidate;
21072
+ return void 0;
21073
+ }
21074
+ function saveStoredAuthToJson(authRecord) {
21075
+ if (process.env.NODE_ENV === "test" || process.env.VITEST || storedAuthOverrideForTesting !== void 0) {
21076
+ return;
20975
21077
  }
20976
- return value.toString();
21078
+ const dirPath = join6(homedir4(), ".local", "share", "opencode");
21079
+ if (!existsSync6(dirPath)) {
21080
+ mkdirSync5(dirPath, { recursive: true });
21081
+ }
21082
+ const authPath = join6(dirPath, "auth.json");
21083
+ const data = existsSync6(authPath) ? JSON.parse(readFileSync5(authPath, "utf8")) : {};
21084
+ data[AGY_PROVIDER_ID] = {
21085
+ type: "oauth",
21086
+ refresh: authRecord.refresh,
21087
+ access: authRecord.access,
21088
+ expires: authRecord.expires
21089
+ };
21090
+ const tempPath = `${authPath}.${process.pid}.${randomUUID4()}.tmp`;
21091
+ let tempFileDescriptor;
21092
+ let ownsTempFile = false;
21093
+ try {
21094
+ tempFileDescriptor = openSync(tempPath, "wx", 384);
21095
+ ownsTempFile = true;
21096
+ writeFileSync5(tempFileDescriptor, JSON.stringify(data, null, 2), {
21097
+ encoding: "utf8"
21098
+ });
21099
+ closeSync(tempFileDescriptor);
21100
+ tempFileDescriptor = void 0;
21101
+ renameSync4(tempPath, authPath);
21102
+ } catch (error45) {
21103
+ if (tempFileDescriptor !== void 0) {
21104
+ try {
21105
+ closeSync(tempFileDescriptor);
21106
+ } catch {
21107
+ }
21108
+ }
21109
+ if (ownsTempFile) {
21110
+ try {
21111
+ unlinkSync4(tempPath);
21112
+ } catch {
21113
+ }
21114
+ }
21115
+ throw error45;
21116
+ }
21117
+ }
21118
+
21119
+ // src/plugin/v2-fetch.ts
21120
+ function createV2FetchInterceptor(getAuthSnapshot) {
21121
+ return async function agyV2Fetch(input, init) {
21122
+ const isGL = isGenerativeLanguageRequest(input);
21123
+ const isInternal = toUrlString(input).includes("cloudcode-pa.googleapis.com");
21124
+ if (!isGL && !isInternal) {
21125
+ return (globalThis.fetch || fetch)(input, init);
21126
+ }
21127
+ let rawAuth = getAuthSnapshot ? await getAuthSnapshot() : void 0;
21128
+ if (!rawAuth) {
21129
+ rawAuth = loadStoredAuthFromJson();
21130
+ }
21131
+ if (!rawAuth || !isOAuthAuth(rawAuth)) {
21132
+ return (globalThis.fetch || fetch)(input, init);
21133
+ }
21134
+ let authRecord = resolveCachedAuth(rawAuth);
21135
+ if (accessTokenExpired(authRecord)) {
21136
+ const refreshed = await refreshAccessToken(authRecord, { auth: { set: async () => {
21137
+ } } });
21138
+ if (refreshed) {
21139
+ authRecord = refreshed;
21140
+ }
21141
+ }
21142
+ if (!authRecord.access) {
21143
+ return (globalThis.fetch || fetch)(input, init);
21144
+ }
21145
+ if (isInternal) {
21146
+ const hasAuth = getSafeHeader(init?.headers, "Authorization") !== void 0;
21147
+ if (hasAuth) {
21148
+ return (globalThis.fetch || fetch)(input, init);
21149
+ }
21150
+ const userAgent = buildAgyCliUserAgent();
21151
+ const headers = setSafeHeaders(init?.headers, {
21152
+ Authorization: `Bearer ${authRecord.access}`,
21153
+ "User-Agent": userAgent
21154
+ });
21155
+ return (globalThis.fetch || fetch)(input, {
21156
+ ...init,
21157
+ headers
21158
+ });
21159
+ }
21160
+ const requestTarget = parseGenerativeLanguageRequest(input);
21161
+ const requestUserAgentModel = requestTarget?.effectiveModel;
21162
+ let projectContext;
21163
+ try {
21164
+ projectContext = await ensureProjectContext(
21165
+ authRecord,
21166
+ { auth: { set: async () => {
21167
+ } } },
21168
+ void 0,
21169
+ requestUserAgentModel
21170
+ );
21171
+ } catch {
21172
+ projectContext = {
21173
+ effectiveProjectId: parseRefreshParts(authRecord.refresh).projectId || "antigravity",
21174
+ auth: authRecord
21175
+ };
21176
+ }
21177
+ const originalRequestedModel = parseGenerativeLanguageRequest(input)?.effectiveModel;
21178
+ let modifiedInput = input;
21179
+ if (isGL && originalRequestedModel) {
21180
+ const originalBase = originalRequestedModel.replace("google-agy/", "");
21181
+ const resolvedBase = resolveModelTier(originalBase, init);
21182
+ if (originalBase !== resolvedBase) {
21183
+ if (typeof modifiedInput === "string") {
21184
+ modifiedInput = modifiedInput.replace(`models/${originalBase}`, `models/${resolvedBase}`);
21185
+ } else if (typeof Request !== "undefined" && modifiedInput instanceof Request) {
21186
+ const newUrl = modifiedInput.url.replace(`models/${originalBase}`, `models/${resolvedBase}`);
21187
+ modifiedInput = new Request(newUrl, modifiedInput);
21188
+ }
21189
+ }
21190
+ }
21191
+ const transformed = prepareAgyRequest(
21192
+ modifiedInput,
21193
+ init,
21194
+ authRecord.access,
21195
+ projectContext.effectiveProjectId,
21196
+ void 0
21197
+ );
21198
+ const chatLogger = createChatLogger();
21199
+ if (chatLogger) {
21200
+ chatLogger.logRequest(
21201
+ toUrlString(transformed.request),
21202
+ transformed.init.method || "GET",
21203
+ transformed.init.headers,
21204
+ transformed.init.body
21205
+ );
21206
+ }
21207
+ const response = await fetchWithRetry(transformed.request, transformed.init);
21208
+ return transformAgyResponse(
21209
+ response,
21210
+ transformed.streaming,
21211
+ null,
21212
+ transformed.requestedModel,
21213
+ transformed.sessionId,
21214
+ chatLogger
21215
+ );
21216
+ };
21217
+ }
21218
+
21219
+ // src/plugin/v2-session.ts
21220
+ function createV2HttpRequestHook(state = {}) {
21221
+ return async (event) => {
21222
+ if (!event) return;
21223
+ const rawUrl = typeof event.url === "string" ? event.url : event.request?.url || "";
21224
+ const isGL = isGenerativeLanguageRequest(rawUrl);
21225
+ const isInternal = rawUrl.includes("cloudcode-pa.googleapis.com");
21226
+ if (!isGL && !isInternal) {
21227
+ return;
21228
+ }
21229
+ event.headers = event.headers || {};
21230
+ let modelName;
21231
+ let rawAuth = event.auth;
21232
+ if (rawAuth && !rawAuth.type) {
21233
+ const tokenVal = rawAuth.access || rawAuth.token;
21234
+ if (tokenVal || rawAuth.refresh) {
21235
+ rawAuth = { type: "oauth", access: tokenVal, ...rawAuth };
21236
+ }
21237
+ }
21238
+ if (!rawAuth || !isOAuthAuth(rawAuth)) {
21239
+ rawAuth = loadStoredAuthFromJson();
21240
+ }
21241
+ let authRecord = rawAuth && isOAuthAuth(rawAuth) ? resolveCachedAuth(rawAuth) : void 0;
21242
+ if (authRecord && accessTokenExpired(authRecord)) {
21243
+ const refreshed = await refreshAccessToken(authRecord, { auth: { set: async () => {
21244
+ } } });
21245
+ if (refreshed) {
21246
+ authRecord = refreshed;
21247
+ try {
21248
+ saveStoredAuthToJson(refreshed);
21249
+ } catch {
21250
+ console.warn("[Agy Auth] Refreshed credentials could not be persisted; the current request will continue.");
21251
+ }
21252
+ }
21253
+ }
21254
+ if (isGL) {
21255
+ const parsed = parseGenerativeLanguageRequest(rawUrl);
21256
+ modelName = parsed?.effectiveModel;
21257
+ if (modelName) {
21258
+ state.lastInterceptedModel = modelName;
21259
+ }
21260
+ if (typeof event.headers.delete === "function") {
21261
+ event.headers.delete("x-goog-api-key");
21262
+ event.headers.delete("api-key");
21263
+ } else {
21264
+ for (const key of Object.keys(event.headers)) {
21265
+ const lower = key.toLowerCase();
21266
+ if (lower === "x-goog-api-key" || lower === "api-key") {
21267
+ delete event.headers[key];
21268
+ }
21269
+ }
21270
+ }
21271
+ if (event.request?.headers) {
21272
+ if (typeof event.request.headers.delete === "function") {
21273
+ event.request.headers.delete("x-goog-api-key");
21274
+ event.request.headers.delete("api-key");
21275
+ } else {
21276
+ for (const key of Object.keys(event.request.headers)) {
21277
+ const lower = key.toLowerCase();
21278
+ if (lower === "x-goog-api-key" || lower === "api-key") {
21279
+ delete event.request.headers[key];
21280
+ }
21281
+ }
21282
+ }
21283
+ }
21284
+ let cleanUrl = rawUrl;
21285
+ try {
21286
+ const parsedUrl = new URL(rawUrl);
21287
+ let urlChanged = false;
21288
+ for (const param of ["key", "x-goog-api-key", "api-key"]) {
21289
+ if (parsedUrl.searchParams.has(param)) {
21290
+ parsedUrl.searchParams.delete(param);
21291
+ urlChanged = true;
21292
+ }
21293
+ }
21294
+ if (urlChanged) {
21295
+ cleanUrl = parsedUrl.toString();
21296
+ }
21297
+ } catch {
21298
+ }
21299
+ if (authRecord && authRecord.access) {
21300
+ let projectContext;
21301
+ try {
21302
+ projectContext = await ensureProjectContext(
21303
+ authRecord,
21304
+ { auth: { set: async () => {
21305
+ } } },
21306
+ void 0,
21307
+ modelName
21308
+ );
21309
+ } catch {
21310
+ projectContext = {
21311
+ effectiveProjectId: parseRefreshParts(authRecord.refresh).projectId || "antigravity",
21312
+ auth: authRecord
21313
+ };
21314
+ }
21315
+ const originalRequestedModel = modelName;
21316
+ let modifiedUrl = cleanUrl;
21317
+ if (originalRequestedModel) {
21318
+ const originalBase = originalRequestedModel.replace("google-agy/", "");
21319
+ const initHeaders = event.headers instanceof Headers ? event.headers : event.request?.headers;
21320
+ const resolvedBase = resolveModelTier(originalBase, { headers: initHeaders });
21321
+ if (originalBase !== resolvedBase) {
21322
+ modifiedUrl = modifiedUrl.replace(`models/${originalBase}`, `models/${resolvedBase}`);
21323
+ }
21324
+ }
21325
+ let bodyPayload = event.body;
21326
+ if (bodyPayload === void 0 && event.request) {
21327
+ if (typeof event.request.clone === "function") {
21328
+ try {
21329
+ bodyPayload = await event.request.clone().text();
21330
+ } catch {
21331
+ }
21332
+ } else if (event.request.body !== void 0) {
21333
+ bodyPayload = event.request.body;
21334
+ }
21335
+ }
21336
+ let preExistingUserAgent;
21337
+ if (typeof event.headers?.get === "function") {
21338
+ preExistingUserAgent = event.headers.get("user-agent") || event.headers.get("User-Agent") || void 0;
21339
+ } else if (event.headers && typeof event.headers === "object") {
21340
+ preExistingUserAgent = event.headers["user-agent"] || event.headers["User-Agent"] || void 0;
21341
+ }
21342
+ if (!preExistingUserAgent && typeof event.request?.headers?.get === "function") {
21343
+ preExistingUserAgent = event.request.headers.get("user-agent") || event.request.headers.get("User-Agent") || void 0;
21344
+ } else if (!preExistingUserAgent && event.request?.headers && typeof event.request.headers === "object") {
21345
+ preExistingUserAgent = event.request.headers["user-agent"] || event.request.headers["User-Agent"] || void 0;
21346
+ }
21347
+ const method = event.method || event.request?.method || "POST";
21348
+ const requestHeaders = event.headers || event.request?.headers;
21349
+ const transformed = prepareAgyRequest(
21350
+ modifiedUrl,
21351
+ {
21352
+ method,
21353
+ headers: requestHeaders,
21354
+ body: bodyPayload
21355
+ },
21356
+ authRecord.access,
21357
+ projectContext.effectiveProjectId
21358
+ );
21359
+ const targetUrl = toUrlString(transformed.request);
21360
+ if (typeof event.url === "string") {
21361
+ event.url = targetUrl;
21362
+ }
21363
+ if (event.request && typeof event.request === "object") {
21364
+ if (typeof Request !== "undefined" && event.request instanceof Request) {
21365
+ event.request = new Request(targetUrl, {
21366
+ method: transformed.init.method,
21367
+ headers: transformed.init.headers,
21368
+ body: transformed.init.body
21369
+ });
21370
+ } else if (typeof event.request.url === "string") {
21371
+ try {
21372
+ event.request.url = targetUrl;
21373
+ } catch {
21374
+ }
21375
+ }
21376
+ }
21377
+ const headerEntries = transformed.init.headers instanceof Headers ? Array.from(transformed.init.headers.entries()) : Object.entries(transformed.init.headers || {});
21378
+ for (const [k, v] of headerEntries) {
21379
+ const lowerK = k.toLowerCase();
21380
+ if (lowerK === "user-agent") {
21381
+ if (preExistingUserAgent) {
21382
+ continue;
21383
+ }
21384
+ if (typeof event.headers?.set === "function") {
21385
+ event.headers.set("User-Agent", v);
21386
+ } else if (event.headers) {
21387
+ event.headers["User-Agent"] = v;
21388
+ }
21389
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21390
+ event.request.headers.set("User-Agent", v);
21391
+ } else if (event.request?.headers && typeof event.request.headers === "object") {
21392
+ event.request.headers["User-Agent"] = v;
21393
+ }
21394
+ continue;
21395
+ }
21396
+ if (typeof event.headers?.set === "function") {
21397
+ event.headers.set(k, v);
21398
+ } else if (event.headers) {
21399
+ event.headers[k] = v;
21400
+ }
21401
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21402
+ event.request.headers.set(k, v);
21403
+ } else if (event.request?.headers && typeof event.request.headers === "object") {
21404
+ event.request.headers[k] = v;
21405
+ }
21406
+ }
21407
+ if (transformed.init.body !== void 0) {
21408
+ event.body = transformed.init.body;
21409
+ if (event.request && typeof event.request === "object" && !(event.request instanceof Request)) {
21410
+ event.request.body = transformed.init.body;
21411
+ }
21412
+ }
21413
+ } else {
21414
+ if (typeof event.url === "string") {
21415
+ event.url = cleanUrl;
21416
+ }
21417
+ if (event.request && typeof event.request === "object") {
21418
+ if (typeof Request !== "undefined" && event.request instanceof Request) {
21419
+ event.request = new Request(cleanUrl, event.request);
21420
+ } else if (typeof event.request.url === "string") {
21421
+ try {
21422
+ event.request.url = cleanUrl;
21423
+ } catch {
21424
+ }
21425
+ }
21426
+ }
21427
+ }
21428
+ }
21429
+ if (authRecord && authRecord.access) {
21430
+ if (typeof event.headers?.set === "function") {
21431
+ event.headers.set("Authorization", `Bearer ${authRecord.access}`);
21432
+ } else if (event.headers) {
21433
+ event.headers["Authorization"] = `Bearer ${authRecord.access}`;
21434
+ }
21435
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21436
+ event.request.headers.set("Authorization", `Bearer ${authRecord.access}`);
21437
+ } else if (event.request?.headers && typeof event.request.headers === "object") {
21438
+ event.request.headers["Authorization"] = `Bearer ${authRecord.access}`;
21439
+ }
21440
+ }
21441
+ const userAgent = buildAgyCliUserAgent(modelName);
21442
+ if (typeof event.headers?.set === "function") {
21443
+ if (!event.headers.get("User-Agent") && !event.headers.get("user-agent")) {
21444
+ event.headers.set("User-Agent", userAgent);
21445
+ }
21446
+ } else if (event.headers) {
21447
+ if (!event.headers["User-Agent"] && !event.headers["user-agent"]) {
21448
+ event.headers["User-Agent"] = userAgent;
21449
+ }
21450
+ }
21451
+ if (event.request?.headers && typeof event.request.headers.set === "function") {
21452
+ if (!event.request.headers.get("User-Agent") && !event.request.headers.get("user-agent")) {
21453
+ event.request.headers.set("User-Agent", userAgent);
21454
+ }
21455
+ } else if (event.request?.headers && typeof event.request.headers === "object") {
21456
+ if (!event.request.headers["User-Agent"] && !event.request.headers["user-agent"]) {
21457
+ event.request.headers["User-Agent"] = userAgent;
21458
+ }
21459
+ }
21460
+ };
20977
21461
  }
21462
+ function createV2HttpResponseHook(state = {}) {
21463
+ return async (event) => {
21464
+ if (!event || !event.response) return;
21465
+ const rawUrl = typeof event.url === "string" ? event.url : event.request?.url || "";
21466
+ const isInternal = rawUrl.includes("cloudcode-pa.googleapis.com");
21467
+ if (isInternal && event.response instanceof Response) {
21468
+ const isStreaming = rawUrl.includes(":streamGenerateCode") || event.response.headers.get("content-type")?.includes("text/event-stream");
21469
+ const parsedModel = parseGenerativeLanguageRequest(rawUrl)?.effectiveModel || state.lastInterceptedModel;
21470
+ const transformed = await transformAgyResponse(
21471
+ event.response,
21472
+ !!isStreaming,
21473
+ null,
21474
+ parsedModel,
21475
+ void 0,
21476
+ void 0
21477
+ );
21478
+ event.response = transformed;
21479
+ }
21480
+ };
21481
+ }
21482
+ function createV2RetryHook() {
21483
+ return async (event) => {
21484
+ if (!event) return;
21485
+ const response = event.response;
21486
+ if (response instanceof Response) {
21487
+ if (response.status === 429 || response.status === 503) {
21488
+ const quota = await classifyQuotaResponse(response);
21489
+ if (quota?.retryDelayMs) {
21490
+ event.retryDelayMs = quota.retryDelayMs;
21491
+ } else {
21492
+ event.retryDelayMs = await resolveRetryDelayMs(response, event.attempt || 1);
21493
+ }
21494
+ }
21495
+ } else if (event.details && Array.isArray(event.details)) {
21496
+ const retryInfo = event.details.find(
21497
+ (d) => d && d["@type"] === "type.googleapis.com/google.rpc.RetryInfo"
21498
+ );
21499
+ if (retryInfo?.retryDelay) {
21500
+ const delayMs = retryInternals.parseRetryDelayValue(retryInfo.retryDelay);
21501
+ if (delayMs !== null) {
21502
+ event.retryDelayMs = delayMs;
21503
+ }
21504
+ }
21505
+ }
21506
+ };
21507
+ }
21508
+ function registerV2SessionHooks(ctx) {
21509
+ const state = {};
21510
+ ctx.session.hook("http.request", createV2HttpRequestHook(state), { providerID: AGY_PROVIDER_ID });
21511
+ ctx.session.hook("http.response", createV2HttpResponseHook(state), { providerID: AGY_PROVIDER_ID });
21512
+ ctx.session.hook("retry", createV2RetryHook(), { providerID: AGY_PROVIDER_ID });
21513
+ }
21514
+
21515
+ // src/plugin/v2.ts
21516
+ async function setupOpenCodeV2(ctx) {
21517
+ const resolveVariants = (modelId) => {
21518
+ const mapping = TIER_MAPPING[modelId];
21519
+ if (!mapping) return void 0;
21520
+ const variants = [];
21521
+ if (mapping.minimal !== void 0) variants.push({ id: "minimal" });
21522
+ if (mapping.low !== void 0) variants.push({ id: "low" });
21523
+ if (mapping.medium !== void 0) variants.push({ id: "medium" });
21524
+ if (mapping.high !== void 0) variants.push({ id: "high" });
21525
+ return variants.length > 0 ? variants : void 0;
21526
+ };
21527
+ const updateProviderRecord = (p) => {
21528
+ p.name = "Antigravity CLI";
21529
+ p.activation = "enabled";
21530
+ p.package = "aisdk:@ai-sdk/google";
21531
+ p.description = "Google Gemini Antigravity Code Assist OAuth provider";
21532
+ p.settings = { ...p.settings || {}, apiKey: "dummy" };
21533
+ p.integrationID = AGY_PROVIDER_ID;
21534
+ };
21535
+ const buildModelRecord = (modelId, simple, existingModel) => {
21536
+ const isClaude = modelId.startsWith("claude-");
21537
+ const isGpt = modelId.startsWith("gpt-");
21538
+ const variants = resolveVariants(modelId);
21539
+ return {
21540
+ id: modelId,
21541
+ providerID: AGY_PROVIDER_ID,
21542
+ name: simple.name,
21543
+ description: simple.description,
21544
+ family: modelId.includes("gemini") ? "gemini" : isClaude ? "claude" : isGpt ? "gpt" : "unknown",
21545
+ reasoning: simple.reasoning,
21546
+ attachment: simple.attachment,
21547
+ tool_call: simple.toolCall,
21548
+ limit: {
21549
+ context: simple.maxTokens,
21550
+ output: simple.maxOutputTokens
21551
+ },
21552
+ cost: simple.cost || { input: 0, output: 0 },
21553
+ ...variants ? { variants } : {},
21554
+ ...existingModel || {}
21555
+ };
21556
+ };
21557
+ const updateModelRecord = (m, modelId, simple) => {
21558
+ m.name = simple.name;
21559
+ m.capabilities = {
21560
+ tools: true,
21561
+ input: ["text", "image"],
21562
+ output: ["text"]
21563
+ };
21564
+ m.limit = {
21565
+ context: simple.maxTokens,
21566
+ output: simple.maxOutputTokens
21567
+ };
21568
+ m.family = "gemini";
21569
+ if (simple.cost) {
21570
+ m.cost = simple.cost;
21571
+ }
21572
+ const variants = resolveVariants(modelId);
21573
+ if (variants) {
21574
+ m.variants = variants;
21575
+ }
21576
+ };
21577
+ if (ctx.provider?.transform) {
21578
+ ctx.provider.transform(async (editor) => {
21579
+ if (!editor) return;
21580
+ if (typeof editor.update === "function") {
21581
+ editor.update(AGY_PROVIDER_ID, updateProviderRecord);
21582
+ } else if (typeof editor.set === "function") {
21583
+ const p = { id: AGY_PROVIDER_ID };
21584
+ updateProviderRecord(p);
21585
+ editor.set(AGY_PROVIDER_ID, p);
21586
+ } else if (typeof editor === "object") {
21587
+ const p = editor[AGY_PROVIDER_ID] || { id: AGY_PROVIDER_ID };
21588
+ updateProviderRecord(p);
21589
+ editor[AGY_PROVIDER_ID] = p;
21590
+ }
21591
+ });
21592
+ }
21593
+ if (ctx.model?.transform) {
21594
+ ctx.model.transform(async (editor) => {
21595
+ if (!editor) return;
21596
+ if (typeof editor.update === "function") {
21597
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21598
+ editor.update(AGY_PROVIDER_ID, modelId, (m) => updateModelRecord(m, modelId, simple));
21599
+ }
21600
+ } else if (typeof editor.set === "function") {
21601
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21602
+ const m = buildModelRecord(modelId, simple);
21603
+ editor.set(`${AGY_PROVIDER_ID}:${modelId}`, m);
21604
+ }
21605
+ } else if (typeof editor === "object") {
21606
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21607
+ const key = `${AGY_PROVIDER_ID}:${modelId}`;
21608
+ editor[key] = buildModelRecord(modelId, simple, editor[key]);
21609
+ }
21610
+ }
21611
+ });
21612
+ }
21613
+ if (ctx.catalog?.transform) {
21614
+ ctx.catalog.transform(async (editor) => {
21615
+ if (!editor) return;
21616
+ if (typeof editor?.provider?.update === "function") {
21617
+ editor.provider.update(AGY_PROVIDER_ID, updateProviderRecord);
21618
+ if (typeof editor?.model?.update === "function") {
21619
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21620
+ editor.model.update(AGY_PROVIDER_ID, modelId, (m) => updateModelRecord(m, modelId, simple));
21621
+ }
21622
+ }
21623
+ return;
21624
+ }
21625
+ const catalog = editor;
21626
+ catalog.providers = catalog.providers || {};
21627
+ catalog.providers[AGY_PROVIDER_ID] = {
21628
+ id: AGY_PROVIDER_ID,
21629
+ name: "Antigravity CLI",
21630
+ npm: "aisdk:@ai-sdk/google",
21631
+ settings: { apiKey: "dummy" },
21632
+ integrationID: AGY_PROVIDER_ID,
21633
+ models: { ...catalog.providers[AGY_PROVIDER_ID]?.models || {} },
21634
+ ...catalog.providers[AGY_PROVIDER_ID]
21635
+ };
21636
+ if (catalog.providers[AGY_PROVIDER_ID].settings) {
21637
+ catalog.providers[AGY_PROVIDER_ID].settings = {
21638
+ ...catalog.providers[AGY_PROVIDER_ID].settings,
21639
+ apiKey: "dummy"
21640
+ };
21641
+ } else {
21642
+ catalog.providers[AGY_PROVIDER_ID].settings = { apiKey: "dummy" };
21643
+ }
21644
+ catalog.providers[AGY_PROVIDER_ID].integrationID = AGY_PROVIDER_ID;
21645
+ const targetModels = catalog.providers[AGY_PROVIDER_ID].models;
21646
+ for (const [modelId, simple] of Object.entries(STATIC_MODELS_SIMPLE)) {
21647
+ targetModels[modelId] = buildModelRecord(modelId, simple, targetModels[modelId]);
21648
+ }
21649
+ });
21650
+ }
21651
+ ctx.tool.transform(async (editor) => {
21652
+ if (!editor) return;
21653
+ const quotaTool = createAgyQuotaTool({
21654
+ client: void 0,
21655
+ getAuthResolver: () => void 0,
21656
+ getConfiguredProjectId: () => void 0,
21657
+ getUserAgentModel: () => void 0
21658
+ });
21659
+ const quotaSummaryTool = createAgyQuotaSummaryTool({
21660
+ client: void 0,
21661
+ getAuthResolver: () => void 0,
21662
+ getConfiguredProjectId: () => void 0,
21663
+ getUserAgentModel: () => void 0
21664
+ });
21665
+ if (typeof editor.add === "function") {
21666
+ editor.add({
21667
+ name: AGY_QUOTA_TOOL_NAME,
21668
+ description: quotaTool.description,
21669
+ input: {},
21670
+ execute: async (args, context) => quotaTool.execute(args, context)
21671
+ });
21672
+ editor.add({
21673
+ name: AGY_QUOTA_SUMMARY_TOOL_NAME,
21674
+ description: quotaSummaryTool.description,
21675
+ input: {},
21676
+ execute: async (args, context) => quotaSummaryTool.execute(args, context)
21677
+ });
21678
+ } else if (typeof editor.set === "function") {
21679
+ editor.set(AGY_QUOTA_TOOL_NAME, quotaTool);
21680
+ editor.set(AGY_QUOTA_SUMMARY_TOOL_NAME, quotaSummaryTool);
21681
+ } else if (editor.tools && typeof editor.tools === "object") {
21682
+ editor.tools[AGY_QUOTA_TOOL_NAME] = quotaTool;
21683
+ editor.tools[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21684
+ } else if (typeof editor === "object") {
21685
+ editor[AGY_QUOTA_TOOL_NAME] = quotaTool;
21686
+ editor[AGY_QUOTA_SUMMARY_TOOL_NAME] = quotaSummaryTool;
21687
+ }
21688
+ });
21689
+ ctx.command.transform(async (editor) => {
21690
+ if (!editor) return;
21691
+ const commands = {
21692
+ [AGY_V2_QUOTA_COMMAND]: {
21693
+ description: "Show Agy Code Assist quota usage",
21694
+ template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21695
+ },
21696
+ [AGY_V2_QUOTA_SUMMARY_COMMAND]: {
21697
+ description: "Show Agy Code Assist quota summary with weekly and 5-hour limits",
21698
+ template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21699
+ }
21700
+ };
21701
+ if (typeof editor.add === "function") {
21702
+ editor.add({
21703
+ name: AGY_V2_QUOTA_COMMAND,
21704
+ description: "Display current Antigravity quota usage",
21705
+ template: AGY_V2_QUOTA_COMMAND_TEMPLATE
21706
+ });
21707
+ editor.add({
21708
+ name: AGY_V2_QUOTA_SUMMARY_COMMAND,
21709
+ description: "Display Antigravity quota summary grouped by model family",
21710
+ template: AGY_V2_QUOTA_SUMMARY_COMMAND_TEMPLATE
21711
+ });
21712
+ } else if (typeof editor.set === "function") {
21713
+ editor.set(AGY_V2_QUOTA_COMMAND, commands[AGY_V2_QUOTA_COMMAND]);
21714
+ editor.set(AGY_V2_QUOTA_SUMMARY_COMMAND, commands[AGY_V2_QUOTA_SUMMARY_COMMAND]);
21715
+ } else if (editor.commands && typeof editor.commands === "object") {
21716
+ editor.commands[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21717
+ editor.commands[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21718
+ } else if (typeof editor === "object") {
21719
+ editor[AGY_V2_QUOTA_COMMAND] = commands[AGY_V2_QUOTA_COMMAND];
21720
+ editor[AGY_V2_QUOTA_SUMMARY_COMMAND] = commands[AGY_V2_QUOTA_SUMMARY_COMMAND];
21721
+ }
21722
+ });
21723
+ ctx.integration?.transform?.((editor) => {
21724
+ if (!editor) return;
21725
+ editor.update?.(AGY_PROVIDER_ID, (integration) => {
21726
+ integration.name = "Antigravity CLI (plugin)";
21727
+ });
21728
+ editor.method?.update?.({
21729
+ integrationID: AGY_PROVIDER_ID,
21730
+ method: {
21731
+ id: "oauth",
21732
+ type: "oauth",
21733
+ label: "Antigravity CLI (OAuth)"
21734
+ },
21735
+ authorize: async () => {
21736
+ const authorization = await authorizeAgy();
21737
+ return {
21738
+ mode: "code",
21739
+ url: authorization.url,
21740
+ instructions: "Please complete Google account authorization in your browser. After authorization, copy the full redirect URL or code and paste it below:",
21741
+ callback: async (code) => {
21742
+ const trimmed = code.trim();
21743
+ const parsed = parseOAuthCallbackInput(trimmed);
21744
+ const authCode = parsed.code || trimmed;
21745
+ if (!authCode) {
21746
+ return { type: "failed", error: "Missing authorization code in callback input" };
21747
+ }
21748
+ if (parsed.state && parsed.state !== authorization.state) {
21749
+ return { type: "failed", error: "State mismatch in callback input (possible CSRF attempt)" };
21750
+ }
21751
+ const exchangeResult = await exchangeAgyWithVerifier(authCode, authorization.verifier);
21752
+ if (exchangeResult.type !== "success") {
21753
+ return exchangeResult;
21754
+ }
21755
+ const initialRefresh = formatRefreshParts({
21756
+ refreshToken: exchangeResult.refresh
21757
+ });
21758
+ let authRecord = {
21759
+ type: "oauth",
21760
+ refresh: initialRefresh,
21761
+ access: exchangeResult.access,
21762
+ expires: exchangeResult.expires
21763
+ };
21764
+ try {
21765
+ const projectContext = await ensureProjectContext(
21766
+ authRecord,
21767
+ { auth: { set: async () => {
21768
+ } } }
21769
+ );
21770
+ authRecord = {
21771
+ ...authRecord,
21772
+ refresh: projectContext.auth.refresh
21773
+ };
21774
+ } catch {
21775
+ }
21776
+ try {
21777
+ saveStoredAuthToJson(authRecord);
21778
+ } catch {
21779
+ return {
21780
+ type: "failed",
21781
+ error: "Google authentication succeeded but AGY credentials could not be stored. Check filesystem access and retry."
21782
+ };
21783
+ }
21784
+ return {
21785
+ type: "oauth",
21786
+ methodID: "oauth",
21787
+ refresh: authRecord.refresh,
21788
+ access: authRecord.access,
21789
+ expires: authRecord.expires
21790
+ };
21791
+ }
21792
+ };
21793
+ }
21794
+ });
21795
+ });
21796
+ ctx.aisdk?.hook("sdk", async (event) => {
21797
+ if (!event) return;
21798
+ const isMatchingProvider = event.providerID === AGY_PROVIDER_ID || event.model?.providerID === AGY_PROVIDER_ID;
21799
+ if (!isMatchingProvider) return;
21800
+ event.options = event.options || {};
21801
+ event.options.apiKey = "dummy";
21802
+ event.options.fetch = createV2FetchInterceptor();
21803
+ });
21804
+ registerV2SessionHooks(ctx);
21805
+ }
21806
+ var v2PluginDefinition = defineOpenCodeV2Plugin({
21807
+ id: AGY_PROVIDER_ID,
21808
+ setup: setupOpenCodeV2
21809
+ });
20978
21810
 
20979
21811
  // index.ts
20980
- var index_default = {
20981
- id: "@anthonyhaussman/opencode-agy-auth",
21812
+ var dualPlugin = {
21813
+ ...v2PluginDefinition,
20982
21814
  server: AgyCLIOAuthPlugin
20983
21815
  };
21816
+ var index_default = dualPlugin;
20984
21817
  export {
20985
21818
  AgyCLIOAuthPlugin,
20986
21819
  GoogleOAuthPlugin,
20987
- index_default as default
21820
+ index_default as default,
21821
+ defineOpenCodeV2Plugin,
21822
+ setupOpenCodeV2,
21823
+ v2PluginDefinition
20988
21824
  };
20989
21825
  //# sourceMappingURL=index.js.map