Skip to content

Commit 29bcd2a

Browse files
committed
Probe runtime package roots; detect export-blocks
Add explicit probing of runtime package roots under runtime cache 'packages' directories and centralize package root resolution via getRuntimePackageRoots. Update resolver to track export-blocked packages (ERR_PACKAGE_PATH_NOT_EXPORTED) using a CompanionResolutionContext and markPackageFoundForExportBlock, so callers can report an 'invalid' presence when exports block resolution. Adjust runtime credential/constant path lookups to use package roots and introduce direct candidate paths for the Gemini companion. Add tests covering probing of package roots and export-block detection, and apply small refactors/formatting improvements.
1 parent f7fcd4a commit 29bcd2a

4 files changed

Lines changed: 186 additions & 50 deletions

‎src/lib/google-antigravity-companion.ts‎

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -104,39 +104,39 @@ function normalizeCredential(value: unknown): string {
104104
}
105105

106106
function getCompanionResolvePaths(): string[] {
107+
return [...getOpencodeRuntimeDirCandidates().cacheDirs];
108+
}
109+
110+
function getRuntimePackageRoots(): string[] {
107111
const cacheDirs = getOpencodeRuntimeDirCandidates().cacheDirs;
108-
const resolvePaths: string[] = [...cacheDirs];
112+
const packageRoots = cacheDirs.map((cacheDir) =>
113+
join(cacheDir, "node_modules", COMPANION_PACKAGE_NAME),
114+
);
109115

110116
for (const cacheDir of cacheDirs) {
111117
try {
112118
const packagesDir = join(cacheDir, "packages");
113119
const entries = readdirSync(packagesDir, { withFileTypes: true });
114120
for (const entry of entries) {
115121
if (entry.isDirectory() && entry.name.startsWith(COMPANION_PACKAGE_NAME)) {
116-
resolvePaths.push(join(packagesDir, entry.name));
122+
packageRoots.push(join(packagesDir, entry.name));
117123
}
118124
}
119125
} catch {
120126
// Ignore if packages dir doesn't exist
121127
}
122128
}
123129

124-
return resolvePaths;
130+
return packageRoots;
125131
}
126132

127-
function markPackageFoundForExportBlock(
128-
error: unknown,
129-
context: CompanionResolutionContext,
130-
): void {
133+
function markPackageFoundForExportBlock(error: unknown, context: CompanionResolutionContext): void {
131134
if (isPackagePathNotExportedError(error)) {
132135
context.packageFound = true;
133136
}
134137
}
135138

136-
function resolveCompanionSpecifier(
137-
specifier: string,
138-
context: CompanionResolutionContext,
139-
): string {
139+
function resolveCompanionSpecifier(specifier: string, context: CompanionResolutionContext): string {
140140
try {
141141
return require.resolve(specifier);
142142
} catch (error) {
@@ -191,11 +191,17 @@ function buildInvalidState(importSpecifier: string, resolvedPath?: string): Reso
191191
};
192192
}
193193

194-
function parseSourceCredentials(content: string): { clientId: string; clientSecret: string } | null {
194+
function parseSourceCredentials(
195+
content: string,
196+
): { clientId: string; clientSecret: string } | null {
195197
const clientId =
196-
content.match(/(?:export\s+const|const|var)\s+ANTIGRAVITY_CLIENT_ID\s*=\s*["']([^"']+)["']/)?.[1]?.trim() ?? "";
198+
content
199+
.match(/(?:export\s+const|const|var)\s+ANTIGRAVITY_CLIENT_ID\s*=\s*["']([^"']+)["']/)?.[1]
200+
?.trim() ?? "";
197201
const clientSecret =
198-
content.match(/(?:export\s+const|const|var)\s+ANTIGRAVITY_CLIENT_SECRET\s*=\s*["']([^"']+)["']/)?.[1]?.trim() ?? "";
202+
content
203+
.match(/(?:export\s+const|const|var)\s+ANTIGRAVITY_CLIENT_SECRET\s*=\s*["']([^"']+)["']/)?.[1]
204+
?.trim() ?? "";
199205

200206
return clientId && clientSecret ? { clientId, clientSecret } : null;
201207
}
@@ -205,9 +211,7 @@ function getPackageCredentialPaths(packageRoot: string): string[] {
205211
}
206212

207213
function getRuntimeCredentialPaths(): string[] {
208-
return getCompanionResolvePaths().flatMap((cacheDir) =>
209-
getPackageCredentialPaths(join(cacheDir, "node_modules", COMPANION_PACKAGE_NAME)),
210-
);
214+
return getRuntimePackageRoots().flatMap((packageRoot) => getPackageCredentialPaths(packageRoot));
211215
}
212216

213217
function isMissingFileError(error: unknown): boolean {
@@ -332,9 +336,7 @@ async function tryResolvePackageEntry(
332336
try {
333337
packageEntryPath = resolveCompanionSpecifier(COMPANION_PACKAGE_NAME, context);
334338
} catch (error) {
335-
return isFallthroughResolutionError(error)
336-
? null
337-
: buildInvalidState(COMPANION_PACKAGE_NAME);
339+
return isFallthroughResolutionError(error) ? null : buildInvalidState(COMPANION_PACKAGE_NAME);
338340
}
339341

340342
return (

‎src/lib/google-gemini-cli-companion.ts‎

Lines changed: 67 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ const COMPANION_JS_IMPORT_SPECIFIERS = [
1515
] as const;
1616
const COMPANION_SOURCE_IMPORT_SPECIFIER = `${COMPANION_PACKAGE_NAME}/src/constants.ts`;
1717
const COMPANION_PACKAGE_JSON_SPECIFIER = `${COMPANION_PACKAGE_NAME}/package.json`;
18+
const COMPANION_DIRECT_CANDIDATE_PATHS = [
19+
["src", "constants.ts"],
20+
["src", "constants.js"],
21+
["dist", "src", "constants.js"],
22+
["dist", "index.js"],
23+
] as const;
1824
const COMPANION_MISSING_ERROR = `Install ${COMPANION_PACKAGE_NAME} separately to enable Gemini CLI quota`;
1925
const COMPANION_INVALID_ERROR = `Installed ${COMPANION_PACKAGE_NAME} package is incompatible`;
2026

@@ -61,6 +67,10 @@ type CompanionModule = {
6167
GEMINI_CLIENT_SECRET?: unknown;
6268
};
6369

70+
type CompanionResolutionContext = {
71+
packageFound: boolean;
72+
};
73+
6474
let resolvedCompanionStatePromise: Promise<ResolvedCompanionState> | null = null;
6575

6676
function isModuleNotFoundError(error: unknown): boolean {
@@ -94,34 +104,53 @@ function normalizeCredential(value: unknown): string {
94104
}
95105

96106
function getCompanionResolvePaths(): string[] {
107+
return [...getOpencodeRuntimeDirCandidates().cacheDirs];
108+
}
109+
110+
function getRuntimePackageRoots(): string[] {
97111
const cacheDirs = getOpencodeRuntimeDirCandidates().cacheDirs;
98-
const resolvePaths: string[] = [...cacheDirs];
112+
const packageRoots = cacheDirs.map((cacheDir) =>
113+
join(cacheDir, "node_modules", COMPANION_PACKAGE_NAME),
114+
);
99115

100116
for (const cacheDir of cacheDirs) {
101117
try {
102118
const packagesDir = join(cacheDir, "packages");
103119
const entries = readdirSync(packagesDir, { withFileTypes: true });
104120
for (const entry of entries) {
105121
if (entry.isDirectory() && entry.name.startsWith(COMPANION_PACKAGE_NAME)) {
106-
resolvePaths.push(join(packagesDir, entry.name));
122+
packageRoots.push(join(packagesDir, entry.name));
107123
}
108124
}
109125
} catch {
110126
// Ignore if packages dir doesn't exist
111127
}
112128
}
113129

114-
return resolvePaths;
130+
return packageRoots;
115131
}
116132

117-
function resolveCompanionSpecifier(specifier: string): string {
133+
function markPackageFoundForExportBlock(error: unknown, context: CompanionResolutionContext): void {
134+
if (isPackagePathNotExportedError(error)) {
135+
context.packageFound = true;
136+
}
137+
}
138+
139+
function resolveCompanionSpecifier(specifier: string, context: CompanionResolutionContext): string {
118140
try {
119141
return require.resolve(specifier);
120142
} catch (error) {
143+
markPackageFoundForExportBlock(error, context);
121144
if (!isFallthroughResolutionError(error)) {
122145
throw error;
123146
}
124-
return require.resolve(specifier, { paths: getCompanionResolvePaths() });
147+
148+
try {
149+
return require.resolve(specifier, { paths: getCompanionResolvePaths() });
150+
} catch (resolvePathsError) {
151+
markPackageFoundForExportBlock(resolvePathsError, context);
152+
throw resolvePathsError;
153+
}
125154
}
126155
}
127156

@@ -162,22 +191,27 @@ function buildInvalidState(importSpecifier: string, resolvedPath?: string): Reso
162191
};
163192
}
164193

165-
function parseSourceCredentials(content: string): { clientId: string; clientSecret: string } | null {
194+
function parseSourceCredentials(
195+
content: string,
196+
): { clientId: string; clientSecret: string } | null {
166197
const clientId =
167-
content.match(/(?:export\s+const|const|var)\s+GEMINI_CLIENT_ID\s*=\s*["']([^"']+)["']/)?.[1]?.trim() ?? "";
198+
content
199+
.match(/(?:export\s+const|const|var)\s+GEMINI_CLIENT_ID\s*=\s*["']([^"']+)["']/)?.[1]
200+
?.trim() ?? "";
168201
const clientSecret =
169-
content.match(/(?:export\s+const|const|var)\s+GEMINI_CLIENT_SECRET\s*=\s*["']([^"']+)["']/)?.[1]?.trim() ?? "";
202+
content
203+
.match(/(?:export\s+const|const|var)\s+GEMINI_CLIENT_SECRET\s*=\s*["']([^"']+)["']/)?.[1]
204+
?.trim() ?? "";
170205

171206
return clientId && clientSecret ? { clientId, clientSecret } : null;
172207
}
173208

209+
function getPackageCredentialPaths(packageRoot: string): string[] {
210+
return COMPANION_DIRECT_CANDIDATE_PATHS.map((parts) => join(packageRoot, ...parts));
211+
}
212+
174213
function getRuntimeSourceConstantPaths(): string[] {
175-
return getCompanionResolvePaths().flatMap((cacheDir) => [
176-
join(cacheDir, "node_modules", COMPANION_PACKAGE_NAME, "src", "constants.ts"),
177-
join(cacheDir, "node_modules", COMPANION_PACKAGE_NAME, "src", "constants.js"),
178-
join(cacheDir, "node_modules", COMPANION_PACKAGE_NAME, "dist", "src", "constants.js"),
179-
join(cacheDir, "node_modules", COMPANION_PACKAGE_NAME, "dist", "index.js"),
180-
]);
214+
return getRuntimePackageRoots().flatMap((packageRoot) => getPackageCredentialPaths(packageRoot));
181215
}
182216

183217
async function tryReadSourceConstantsPath(
@@ -202,10 +236,11 @@ async function tryReadSourceConstantsPath(
202236

203237
async function tryResolveJsConstants(
204238
importSpecifier: string,
239+
context: CompanionResolutionContext,
205240
): Promise<ResolvedCompanionState | null> {
206241
let resolvedPath: string;
207242
try {
208-
resolvedPath = resolveCompanionSpecifier(importSpecifier);
243+
resolvedPath = resolveCompanionSpecifier(importSpecifier, context);
209244
} catch (error) {
210245
if (isFallthroughResolutionError(error)) {
211246
return null;
@@ -229,17 +264,21 @@ async function tryResolveJsConstants(
229264
return buildConfiguredState({ importSpecifier, resolvedPath, clientId, clientSecret });
230265
}
231266

232-
async function tryResolvePackageEntry(): Promise<ResolvedCompanionState | null> {
267+
async function tryResolvePackageEntry(
268+
context: CompanionResolutionContext,
269+
): Promise<ResolvedCompanionState | null> {
233270
try {
234-
const packageEntryPath = resolveCompanionSpecifier(COMPANION_PACKAGE_NAME);
271+
const packageEntryPath = resolveCompanionSpecifier(COMPANION_PACKAGE_NAME, context);
235272
const packageEntryResolved = await tryReadSourceConstantsPath(packageEntryPath);
236273
return packageEntryResolved ?? buildInvalidState(COMPANION_PACKAGE_NAME, packageEntryPath);
237274
} catch (error) {
238275
return isFallthroughResolutionError(error) ? null : buildInvalidState(COMPANION_PACKAGE_NAME);
239276
}
240277
}
241278

242-
async function tryResolveSourceConstants(): Promise<ResolvedCompanionState | null> {
279+
async function tryResolveSourceConstants(
280+
context: CompanionResolutionContext,
281+
): Promise<ResolvedCompanionState | null> {
243282
let resolvedPath: string;
244283
try {
245284
resolvedPath = require.resolve(COMPANION_SOURCE_IMPORT_SPECIFIER);
@@ -256,7 +295,7 @@ async function tryResolveSourceConstants(): Promise<ResolvedCompanionState | nul
256295
}
257296

258297
try {
259-
const packageJsonPath = resolveCompanionSpecifier(COMPANION_PACKAGE_JSON_SPECIFIER);
298+
const packageJsonPath = resolveCompanionSpecifier(COMPANION_PACKAGE_JSON_SPECIFIER, context);
260299
const packageRoot = dirname(packageJsonPath);
261300
for (const candidatePath of [
262301
join(packageRoot, "src", "constants.ts"),
@@ -270,7 +309,7 @@ async function tryResolveSourceConstants(): Promise<ResolvedCompanionState | nul
270309
resolvedPath = join(packageRoot, "src", "constants.ts");
271310
} catch (packageError) {
272311
if (isFallthroughResolutionError(packageError)) {
273-
return tryResolvePackageEntry();
312+
return tryResolvePackageEntry(context);
274313
}
275314

276315
return buildInvalidState(COMPANION_SOURCE_IMPORT_SPECIFIER);
@@ -284,18 +323,24 @@ async function tryResolveSourceConstants(): Promise<ResolvedCompanionState | nul
284323
}
285324

286325
async function resolveCompanionState(): Promise<ResolvedCompanionState> {
326+
const context: CompanionResolutionContext = { packageFound: false };
327+
287328
for (const importSpecifier of COMPANION_JS_IMPORT_SPECIFIERS) {
288-
const resolved = await tryResolveJsConstants(importSpecifier);
329+
const resolved = await tryResolveJsConstants(importSpecifier, context);
289330
if (resolved) {
290331
return resolved;
291332
}
292333
}
293334

294-
const sourceResolved = await tryResolveSourceConstants();
335+
const sourceResolved = await tryResolveSourceConstants(context);
295336
if (sourceResolved) {
296337
return sourceResolved;
297338
}
298339

340+
if (context.packageFound) {
341+
return buildInvalidState(COMPANION_PACKAGE_NAME);
342+
}
343+
299344
return {
300345
presence: {
301346
state: "missing",

‎tests/lib.google-antigravity-companion.test.ts‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,15 @@ function moduleNotFound(): Error & { code?: string } {
2929
}
3030

3131
function packagePathNotExported(): Error & { code?: string } {
32-
const error = new Error("Package subpath is not defined by \"exports\"");
32+
const error = new Error('Package subpath is not defined by "exports"');
3333
error.code = "ERR_PACKAGE_PATH_NOT_EXPORTED";
3434
return error;
3535
}
3636

37-
function writeAntigravityCredentials(path: string, params?: { declaration?: "export const" | "const" | "var" }): void {
37+
function writeAntigravityCredentials(
38+
path: string,
39+
params?: { declaration?: "export const" | "const" | "var" },
40+
): void {
3841
const declaration = params?.declaration ?? "export const";
3942
writeFileSync(
4043
path,
@@ -234,6 +237,27 @@ describe("google antigravity companion resolution", () => {
234237
});
235238
});
236239

240+
it("directly probes package roots under the runtime packages directory", async () => {
241+
const runtimeCacheDir = join(tempDir, "cache", "opencode");
242+
const packageRoot = join(runtimeCacheDir, "packages", "opencode-antigravity-auth-1.0.0");
243+
const candidatePath = join(packageRoot, "dist", "index.js");
244+
mkdirSync(join(packageRoot, "dist"), { recursive: true });
245+
writeAntigravityCredentials(candidatePath, { declaration: "var" });
246+
moduleMocks.runtimeDirs.value = { cacheDirs: [runtimeCacheDir] };
247+
moduleMocks.resolveImpl.mockImplementation(() => {
248+
throw moduleNotFound();
249+
});
250+
251+
const mod = await import("../src/lib/google-antigravity-companion.js");
252+
253+
await expect(mod.resolveAntigravityClientCredentials()).resolves.toMatchObject({
254+
state: "configured",
255+
clientId: "client-id",
256+
clientSecret: "client-secret",
257+
resolvedPath: candidatePath,
258+
});
259+
});
260+
237261
it("reports invalid when a runtime candidate exists but cannot be read", async () => {
238262
const runtimeCacheDir = join(tempDir, "cache", "opencode");
239263
const candidatePath = join(

0 commit comments

Comments
 (0)