Compare commits

..
Author SHA1 Message Date
Peter Steinberger 6607f865cf fix: harden gemini cli oauth discovery (#1773) (thanks @benostein) 2026-01-25 13:07:03 +00:00
Ben Stein f0f5bc6cf1 fix(gemini-cli-auth): auto-extract OAuth credentials from installed Gemini CLI
Fixes #1765

- Extract client ID and secret from Gemini CLI's bundled oauth2.js
- Cross-platform binary lookup (no shell commands)
- Fallback to env vars for user override
- Add tests for credential extraction
2026-01-25 12:58:13 +00:00
13 changed files with 469 additions and 171 deletions

No files matched your search

+31 -33
View File
@@ -5,64 +5,62 @@ Docs: https://docs.clawd.bot
## 2026.1.24
### Highlights
- Providers: Ollama discovery + docs; Venice guide upgrades + cross-links. (#1606) Thanks @abhaymundhara. https://docs.clawd.bot/providers/ollama https://docs.clawd.bot/providers/venice
- Channels: LINE plugin (Messaging API) with rich replies + quick replies. (#1630) Thanks @plum-dawg.
- TTS: Edge fallback (keyless) + `/tts` auto modes. (#1668, #1667) Thanks @steipete, @sebslight. https://docs.clawd.bot/tts
- Exec approvals: approve in-chat via `/approve` across all channels (including plugins). (#1621) Thanks @czekaj. https://docs.clawd.bot/tools/exec-approvals https://docs.clawd.bot/tools/slash-commands
- Telegram: DM topics as separate sessions + outbound link preview toggle. (#1597, #1700) Thanks @rohannagpal, @zerone0x. https://docs.clawd.bot/channels/telegram
- Ollama: provider discovery + docs. (#1606) Thanks @abhaymundhara. https://docs.clawd.bot/providers/ollama
- Venius (Venice AI): highlight provider guide + cross-links + expanded guidance. https://docs.clawd.bot/providers/venice
### Changes
- Channels: add LINE plugin (Messaging API) with rich replies, quick replies, and plugin HTTP registry. (#1630) Thanks @plum-dawg.
- TTS: add Edge TTS provider fallback, defaulting to keyless Edge with MP3 retry on format failures. (#1668) Thanks @steipete. https://docs.clawd.bot/tts
- TTS: add auto mode enum (off/always/inbound/tagged) with per-session `/tts` override. (#1667) Thanks @sebslight. https://docs.clawd.bot/tts
- Telegram: treat DM topics as separate sessions and keep DM history limits stable with thread suffixes. (#1597) Thanks @rohannagpal.
- Telegram: add `channels.telegram.linkPreview` to toggle outbound link previews. (#1700) Thanks @zerone0x. https://docs.clawd.bot/channels/telegram
- Web search: add Brave freshness filter parameter for time-scoped results. (#1688) Thanks @JonUleis. https://docs.clawd.bot/tools/web
- TTS: add auto mode enum (off/always/inbound/tagged) with per-session `/tts` override. (#1667) Thanks @sebslight. https://docs.clawd.bot/tts
- Channels: add LINE plugin (Messaging API) with rich replies, quick replies, and plugin HTTP registry. (#1630) Thanks @plum-dawg.
- Dev: add prek pre-commit hooks + dependabot config for weekly updates. (#1720) Thanks @dguido.
- UI: refresh Control UI dashboard design system (typography, colors, spacing). (#1786) Thanks @mousberg.
- Exec approvals: forward approval prompts to chat with `/approve` for all channels (including plugins). (#1621) Thanks @czekaj. https://docs.clawd.bot/tools/exec-approvals https://docs.clawd.bot/tools/slash-commands
- Gateway: expose config.patch in the gateway tool with safe partial updates + restart sentinel. (#1653) Thanks @Glucksberg.
- Diagnostics: add diagnostic flags for targeted debug logs (config + env override). https://docs.clawd.bot/diagnostics/flags
- Docs: expand FAQ (migration, scheduling, concurrency, model recommendations, OpenAI subscription auth, Pi sizing, hackable install, docs SSL workaround).
- Docs: add verbose installer troubleshooting guidance.
- Docs: add macOS VM guide with local/hosted options + VPS/nodes guidance. (#1693) Thanks @f-trycua.
- Docs: add Bedrock EC2 instance role setup + IAM steps. (#1625) Thanks @sergical. https://docs.clawd.bot/bedrock
- Docs: update Fly.io guide notes.
- Dev: add prek pre-commit hooks + dependabot config for weekly updates. (#1720) Thanks @dguido.
- Docs: add Bedrock EC2 instance role setup + IAM steps. (#1625) Thanks @sergical. https://docs.clawd.bot/bedrock
- Exec approvals: forward approval prompts to chat with `/approve` for all channels (including plugins). (#1621) Thanks @czekaj. https://docs.clawd.bot/tools/exec-approvals https://docs.clawd.bot/tools/slash-commands
- Gateway: expose config.patch in the gateway tool with safe partial updates + restart sentinel. (#1653) Thanks @Glucksberg.
- Telegram: add `channels.telegram.linkPreview` to toggle outbound link previews. (#1700) Thanks @zerone0x. https://docs.clawd.bot/channels/telegram
- Telegram: treat DM topics as separate sessions and keep DM history limits stable with thread suffixes. (#1597) Thanks @rohannagpal.
- Telegram: add verbose raw-update logging for inbound Telegram updates. (#1597) Thanks @rohannagpal.
- Diagnostics: add diagnostic flags for targeted debug logs (config + env override). https://docs.clawd.bot/diagnostics/flags
### Fixes
- Web UI: show Stop button during active runs, swap back to New session when idle. (#1664) Thanks @ndbroadbent.
- Web UI: clear stale disconnect banners on reconnect; allow form saves with unsupported schema paths but block missing schema. (#1707) Thanks @Glucksberg.
- Web UI: hide internal `message_id` hints in chat bubbles.
- Gateway: allow Control UI token-only auth to skip device pairing even when device identity is present (`gateway.controlUi.allowInsecureAuth`). (#1679) Thanks @steipete.
- Gemini CLI OAuth: auto-detect client id from installed CLI and harden discovery paths. (#1773) Thanks @benostein.
- Matrix: decrypt E2EE media attachments with preflight size guard. (#1744) Thanks @araa47.
- Gateway: allow Control UI token-only auth to skip device pairing even when device identity is present (`gateway.controlUi.allowInsecureAuth`). (#1679) Thanks @steipete.
- Gateway: include inline config env vars in service install environments. (#1735) Thanks @Seredeep.
- Exec: treat Windows platform labels as Windows for node shell selection. (#1760) Thanks @ymat19.
- BlueBubbles: route phone-number targets to DMs, avoid leaking routing IDs, and auto-create missing DMs (Private API required). (#1751) Thanks @tyler6204. https://docs.clawd.bot/channels/bluebubbles
- BlueBubbles: keep part-index GUIDs in reply tags when short IDs are missing.
- Web UI: hide internal `message_id` hints in chat bubbles.
- Web UI: show Stop button during active runs, swap back to New session when idle. (#1664) Thanks @ndbroadbent.
- Web UI: clear stale disconnect banners on reconnect; allow form saves with unsupported schema paths but block missing schema. (#1707) Thanks @Glucksberg.
- Heartbeat: normalize target identifiers for consistent routing.
- TUI: reload history after gateway reconnect to restore session state. (#1663)
- Telegram: use wrapped fetch for long-polling on Node to normalize AbortSignal handling. (#1639)
- Telegram: set fetch duplex="half" for uploads on Node 22 to avoid sendPhoto failures. (#1684) Thanks @commdata2338.
- Telegram: honor per-account proxy for outbound API calls. (#1774) Thanks @radek-paclt.
- Signal: repair reaction sends (group/UUID targets + CLI author flags). (#1651) Thanks @vilkasdev.
- Signal: add configurable signal-cli startup timeout + external daemon mode docs. (#1677) https://docs.clawd.bot/channels/signal
- Telegram: set fetch duplex="half" for uploads on Node 22 to avoid sendPhoto failures. (#1684) Thanks @commdata2338.
- Telegram: use wrapped fetch for long-polling on Node to normalize AbortSignal handling. (#1639)
- Telegram: honor per-account proxy for outbound API calls. (#1774) Thanks @radek-paclt.
- Voice Call: return stream TwiML for outbound conversation calls on initial Twilio webhook. (#1634)
- Voice Call: serialize Twilio TTS playback and cancel on barge-in to prevent overlap. (#1713) Thanks @dguido.
- Google Chat: tighten email allowlist matching, typing cleanup, media caps, and onboarding/docs/tests. (#1635) Thanks @iHildy.
- Google Chat: normalize space targets without double `spaces/` prefix.
- Exec: keep approvals for elevated ask unless full mode. (#1616) Thanks @ivancasco.
- Agents: auto-compact on context overflow prompt errors before failing. (#1627) Thanks @rodrigouroz.
- Agents: use the active auth profile for auto-compaction recovery.
- Agents: let cron isolated runs inherit subagent allowlists from the parent agent. (#1771) Thanks @Noctivoro.
- Media understanding: skip image understanding when the primary model already supports vision. (#1747) Thanks @tyler6204.
- Models: default missing custom provider fields so minimal configs are accepted.
- Messaging: keep newline chunking safe for fenced markdown blocks across channels.
- TUI: reload history after gateway reconnect to restore session state. (#1663)
- Heartbeat: normalize target identifiers for consistent routing.
- Exec: keep approvals for elevated ask unless full mode. (#1616) Thanks @ivancasco.
- Exec: treat Windows platform labels as Windows for node shell selection. (#1760) Thanks @ymat19.
- Gateway: include inline config env vars in service install environments. (#1735) Thanks @Seredeep.
- Media understanding: skip image understanding when the primary model already supports vision. (#1747) Thanks @tyler6204.
- Gateway: skip Tailscale DNS probing when tailscale.mode is off. (#1671)
- Gateway: reduce log noise for late invokes + remote node probes; debounce skills refresh. (#1607) Thanks @petter-b.
- Gateway: clarify Control UI/WebChat auth error hints for missing tokens. (#1690)
- Gateway: listen on IPv6 loopback when bound to 127.0.0.1 so localhost webhooks work.
- Gateway: store lock files in the temp directory to avoid stale locks on persistent volumes. (#1676)
- macOS: default direct-transport `ws://` URLs to port 18789; document `gateway.remote.transport`. (#1603) Thanks @ngutman.
- Voice Call: return stream TwiML for outbound conversation calls on initial Twilio webhook. (#1634)
- Voice Call: serialize Twilio TTS playback and cancel on barge-in to prevent overlap. (#1713) Thanks @dguido.
- Google Chat: tighten email allowlist matching, typing cleanup, media caps, and onboarding/docs/tests. (#1635) Thanks @iHildy.
- Google Chat: normalize space targets without double `spaces/` prefix.
- Messaging: keep newline chunking safe for fenced markdown blocks across channels.
- Tests: cap Vitest workers on CI macOS to reduce timeouts. (#1597) Thanks @rohannagpal.
- Tests: avoid fake-timer dependency in embedded runner stream mock to reduce CI flakes. (#1597) Thanks @rohannagpal.
- Tests: increase embedded runner ordering test timeout to reduce CI flakes. (#1597) Thanks @rohannagpal.
+15 -15
View File
@@ -26,7 +26,7 @@ Minimal config:
```
### Setup
1) Create a Slack app (From scratch) in https://api.slack.com/apps.
1) Create a Slack app (From scratch) in https://api.channels.slack.com/apps.
2) **Socket Mode** → toggle on. Then go to **Basic Information** → **App-Level Tokens** → **Generate Token and Scopes** with scope `connections:write`. Copy the **App Token** (`xapp-...`).
3) **OAuth & Permissions** → add bot token scopes (use the manifest below). Click **Install to Workspace**. Copy the **Bot User OAuth Token** (`xoxb-...`).
4) Optional: **OAuth & Permissions** → add **User Token Scopes** (see the read-only list below). Reinstall the app and copy the **User OAuth Token** (`xoxp-...`).
@@ -245,29 +245,29 @@ If you enable native commands, add one `slash_commands` entry per command you wa
## Scopes (current vs optional)
Slack's Conversations API is type-scoped: you only need the scopes for the
conversation types you actually touch (channels, groups, im, mpim). See
https://docs.slack.dev/apis/web-api/using-the-conversations-api/ for the overview.
https://api.channels.slack.com/docs/conversations-api for the overview.
### Bot token scopes (required)
- `chat:write` (send/update/delete messages via `chat.postMessage`)
https://docs.slack.dev/reference/methods/chat.postMessage
https://api.channels.slack.com/methods/chat.postMessage
- `im:write` (open DMs via `conversations.open` for user DMs)
https://docs.slack.dev/reference/methods/conversations.open
https://api.channels.slack.com/methods/conversations.open
- `channels:history`, `groups:history`, `im:history`, `mpim:history`
https://docs.slack.dev/reference/methods/conversations.history
https://api.channels.slack.com/methods/conversations.history
- `channels:read`, `groups:read`, `im:read`, `mpim:read`
https://docs.slack.dev/reference/methods/conversations.info
https://api.channels.slack.com/methods/conversations.info
- `users:read` (user lookup)
https://docs.slack.dev/reference/methods/users.info
https://api.channels.slack.com/methods/users.info
- `reactions:read`, `reactions:write` (`reactions.get` / `reactions.add`)
https://docs.slack.dev/reference/methods/reactions.get
https://docs.slack.dev/reference/methods/reactions.add
https://api.channels.slack.com/methods/reactions.get
https://api.channels.slack.com/methods/reactions.add
- `pins:read`, `pins:write` (`pins.list` / `pins.add` / `pins.remove`)
https://docs.slack.dev/reference/scopes/pins.read
https://docs.slack.dev/reference/scopes/pins.write
https://api.channels.slack.com/scopes/pins:read
https://api.channels.slack.com/scopes/pins:write
- `emoji:read` (`emoji.list`)
https://docs.slack.dev/reference/scopes/emoji.read
https://api.channels.slack.com/scopes/emoji:read
- `files:write` (uploads via `files.uploadV2`)
https://docs.slack.dev/messaging/working-with-files/#upload
https://api.channels.slack.com/messaging/files/uploading
### User token scopes (optional, read-only by default)
Add these under **User Token Scopes** if you configure `channels.slack.userToken`.
@@ -284,9 +284,9 @@ Add these under **User Token Scopes** if you configure `channels.slack.userToken
- `mpim:write` (only if we add group-DM open/DM start via `conversations.open`)
- `groups:write` (only if we add private-channel management: create/rename/invite/archive)
- `chat:write.public` (only if we want to post to channels the bot isn't in)
https://docs.slack.dev/reference/scopes/chat.write.public
https://api.channels.slack.com/scopes/chat:write.public
- `users:read.email` (only if we need email fields from `users.info`)
https://docs.slack.dev/changelog/2017-04-narrowing-email-access
https://api.channels.slack.com/changelog/2017-04-narrowing-email-access
- `files:read` (only if we start listing/reading file metadata)
## Config
+12 -1
View File
@@ -18,7 +18,18 @@ Restart the Gateway after enabling.
clawdbot models auth login --provider google-gemini-cli --set-default
```
## Env vars
## Requirements
If the Gemini CLI is installed, Clawdbot extracts the OAuth client ID automatically.
```bash
brew install gemini-cli
# or: npm install -g @google/gemini-cli
```
## Env vars (optional)
Override auto-detected credentials with:
- `CLAWDBOT_GEMINI_OAUTH_CLIENT_ID` / `GEMINI_CLI_OAUTH_CLIENT_ID`
- `CLAWDBOT_GEMINI_OAUTH_CLIENT_SECRET` / `GEMINI_CLI_OAUTH_CLIENT_SECRET`
@@ -0,0 +1,205 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { join } from "node:path";
// Mock fs module before importing the module under test
const mockExistsSync = vi.fn();
const mockReadFileSync = vi.fn();
const mockRealpathSync = vi.fn();
const mockReaddirSync = vi.fn();
vi.mock("node:fs", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs")>();
return {
...actual,
existsSync: (...args: Parameters<typeof actual.existsSync>) => mockExistsSync(...args),
readFileSync: (...args: Parameters<typeof actual.readFileSync>) => mockReadFileSync(...args),
realpathSync: (...args: Parameters<typeof actual.realpathSync>) => mockRealpathSync(...args),
readdirSync: (...args: Parameters<typeof actual.readdirSync>) => mockReaddirSync(...args),
};
});
describe("extractGeminiCliCredentials", () => {
const FAKE_CLIENT_ID = "123456789-abcdef.apps.googleusercontent.com";
const FAKE_CLIENT_SECRET = "GOCSPX-FakeSecretValue123";
const FAKE_OAUTH2_CONTENT = `
const clientId = "${FAKE_CLIENT_ID}";
const clientSecret = "${FAKE_CLIENT_SECRET}";
`;
const FAKE_OAUTH2_ID_ONLY = `
const clientId = "${FAKE_CLIENT_ID}";
`;
let originalPath: string | undefined;
beforeEach(async () => {
vi.resetModules();
vi.clearAllMocks();
originalPath = process.env.PATH;
});
afterEach(() => {
process.env.PATH = originalPath;
});
it("returns null when gemini binary is not in PATH", async () => {
process.env.PATH = "/nonexistent";
mockExistsSync.mockReturnValue(false);
const { extractGeminiCliCredentials, clearCredentialsCache } = await import("./oauth.js");
clearCredentialsCache();
expect(extractGeminiCliCredentials()).toBeNull();
});
it("extracts credentials from oauth2.js in known path", async () => {
const fakeBinDir = "/fake/bin";
const fakeGeminiPath = join(fakeBinDir, "gemini");
const fakeCliRoot = "/fake/lib/node_modules/@google/gemini-cli";
const fakeResolvedPath = `${fakeCliRoot}/dist/index.js`;
const fakeOauth2Path = `${fakeCliRoot}/node_modules/@google/gemini-cli-core/dist/src/code_assist/oauth2.js`;
const fakeShimContent = `node "${fakeResolvedPath}"`;
process.env.PATH = fakeBinDir;
mockExistsSync.mockImplementation((p: string) => {
if (p === fakeGeminiPath) return true;
if (p === fakeCliRoot) return true;
if (p === fakeOauth2Path) return true;
return false;
});
mockRealpathSync.mockReturnValue(fakeResolvedPath);
mockReadFileSync.mockImplementation((p: string) => {
if (p === fakeGeminiPath || p === fakeResolvedPath) return fakeShimContent;
if (p === fakeOauth2Path) return FAKE_OAUTH2_CONTENT;
return "";
});
const { extractGeminiCliCredentials, clearCredentialsCache } = await import("./oauth.js");
clearCredentialsCache();
const result = extractGeminiCliCredentials();
expect(result).toEqual({
clientId: FAKE_CLIENT_ID,
clientSecret: FAKE_CLIENT_SECRET,
});
});
it("returns null when oauth2.js cannot be found", async () => {
const fakeBinDir = "/fake/bin";
const fakeGeminiPath = join(fakeBinDir, "gemini");
const fakeCliRoot = "/fake/lib/node_modules/@google/gemini-cli";
const fakeResolvedPath = `${fakeCliRoot}/dist/index.js`;
const fakeShimContent = `node "${fakeResolvedPath}"`;
process.env.PATH = fakeBinDir;
mockExistsSync.mockImplementation((p: string) => p === fakeGeminiPath || p === fakeCliRoot);
mockRealpathSync.mockReturnValue(fakeResolvedPath);
mockReaddirSync.mockReturnValue([]); // Empty directory for recursive search
mockReadFileSync.mockImplementation((p: string) => {
if (p === fakeGeminiPath || p === fakeResolvedPath) return fakeShimContent;
return "";
});
const { extractGeminiCliCredentials, clearCredentialsCache } = await import("./oauth.js");
clearCredentialsCache();
expect(extractGeminiCliCredentials()).toBeNull();
});
it("returns null when oauth2.js lacks credentials", async () => {
const fakeBinDir = "/fake/bin";
const fakeGeminiPath = join(fakeBinDir, "gemini");
const fakeCliRoot = "/fake/lib/node_modules/@google/gemini-cli";
const fakeResolvedPath = `${fakeCliRoot}/dist/index.js`;
const fakeOauth2Path = `${fakeCliRoot}/node_modules/@google/gemini-cli-core/dist/src/code_assist/oauth2.js`;
const fakeShimContent = `node "${fakeResolvedPath}"`;
process.env.PATH = fakeBinDir;
mockExistsSync.mockImplementation((p: string) => {
if (p === fakeGeminiPath) return true;
if (p === fakeCliRoot) return true;
if (p === fakeOauth2Path) return true;
return false;
});
mockRealpathSync.mockReturnValue(fakeResolvedPath);
mockReadFileSync.mockImplementation((p: string) => {
if (p === fakeGeminiPath || p === fakeResolvedPath) return fakeShimContent;
if (p === fakeOauth2Path) return "// no credentials here";
return "";
});
const { extractGeminiCliCredentials, clearCredentialsCache } = await import("./oauth.js");
clearCredentialsCache();
expect(extractGeminiCliCredentials()).toBeNull();
});
it("caches credentials after first extraction", async () => {
const fakeBinDir = "/fake/bin";
const fakeGeminiPath = join(fakeBinDir, "gemini");
const fakeCliRoot = "/fake/lib/node_modules/@google/gemini-cli";
const fakeResolvedPath = `${fakeCliRoot}/dist/index.js`;
const fakeOauth2Path = `${fakeCliRoot}/node_modules/@google/gemini-cli-core/dist/src/code_assist/oauth2.js`;
const fakeShimContent = `node "${fakeResolvedPath}"`;
process.env.PATH = fakeBinDir;
mockExistsSync.mockImplementation((p: string) => {
if (p === fakeGeminiPath) return true;
if (p === fakeCliRoot) return true;
if (p === fakeOauth2Path) return true;
return false;
});
mockRealpathSync.mockReturnValue(fakeResolvedPath);
mockReadFileSync.mockImplementation((p: string) => {
if (p === fakeGeminiPath || p === fakeResolvedPath) return fakeShimContent;
if (p === fakeOauth2Path) return FAKE_OAUTH2_CONTENT;
return "";
});
const { extractGeminiCliCredentials, clearCredentialsCache } = await import("./oauth.js");
clearCredentialsCache();
// First call
const result1 = extractGeminiCliCredentials();
expect(result1).not.toBeNull();
// Second call should use cache (readFileSync not called again)
const readCount = mockReadFileSync.mock.calls.length;
const result2 = extractGeminiCliCredentials();
expect(result2).toEqual(result1);
expect(mockReadFileSync.mock.calls.length).toBe(readCount);
});
it("returns client id when secret is missing", async () => {
const fakeBinDir = "/fake/bin";
const fakeGeminiPath = join(fakeBinDir, "gemini");
const fakeCliRoot = "/fake/lib/node_modules/@google/gemini-cli";
const fakeResolvedPath = `${fakeCliRoot}/dist/index.js`;
const fakeOauth2Path = `${fakeCliRoot}/node_modules/@google/gemini-cli-core/dist/src/code_assist/oauth2.js`;
const fakeShimContent = `node "${fakeResolvedPath}"`;
process.env.PATH = fakeBinDir;
mockExistsSync.mockImplementation((p: string) => {
if (p === fakeGeminiPath) return true;
if (p === fakeCliRoot) return true;
if (p === fakeOauth2Path) return true;
return false;
});
mockRealpathSync.mockReturnValue(fakeResolvedPath);
mockReadFileSync.mockImplementation((p: string) => {
if (p === fakeGeminiPath || p === fakeResolvedPath) return fakeShimContent;
if (p === fakeOauth2Path) return FAKE_OAUTH2_ID_ONLY;
return "";
});
const { extractGeminiCliCredentials, clearCredentialsCache } = await import("./oauth.js");
clearCredentialsCache();
const result = extractGeminiCliCredentials();
expect(result).toEqual({
clientId: FAKE_CLIENT_ID,
clientSecret: undefined,
});
});
});
+198 -9
View File
@@ -1,6 +1,7 @@
import { createHash, randomBytes } from "node:crypto";
import { readFileSync } from "node:fs";
import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs";
import { createServer } from "node:http";
import { delimiter, dirname, isAbsolute, join, normalize } from "node:path";
const CLIENT_ID_KEYS = ["CLAWDBOT_GEMINI_OAUTH_CLIENT_ID", "GEMINI_CLI_OAUTH_CLIENT_ID"];
const CLIENT_SECRET_KEYS = [
@@ -47,15 +48,203 @@ function resolveEnv(keys: string[]): string | undefined {
return undefined;
}
function resolveOAuthClientConfig(): { clientId: string; clientSecret?: string } {
const clientId = resolveEnv(CLIENT_ID_KEYS);
if (!clientId) {
throw new Error(
"Missing Gemini OAuth client ID. Set CLAWDBOT_GEMINI_OAUTH_CLIENT_ID (or GEMINI_CLI_OAUTH_CLIENT_ID).",
);
type GeminiCliClientConfig = { clientId: string; clientSecret?: string };
let cachedGeminiCliCredentials: GeminiCliClientConfig | null = null;
/** @internal */
export function clearCredentialsCache(): void {
cachedGeminiCliCredentials = null;
}
/** Extracts OAuth credentials from the installed Gemini CLI's bundled oauth2.js. */
export function extractGeminiCliCredentials(): GeminiCliClientConfig | null {
if (cachedGeminiCliCredentials) return cachedGeminiCliCredentials;
try {
const oauthPath = findGeminiCliOAuthPath();
if (!oauthPath) return null;
const content = readFileSync(oauthPath, "utf8");
const idMatch = content.match(/(\d+-[a-z0-9]+\.apps\.googleusercontent\.com)/i);
const secretMatch = content.match(/(GOCSPX-[A-Za-z0-9_-]+)/);
if (idMatch) {
cachedGeminiCliCredentials = { clientId: idMatch[1], clientSecret: secretMatch?.[1] };
return cachedGeminiCliCredentials;
}
} catch {
// Gemini CLI not installed or extraction failed
}
const clientSecret = resolveEnv(CLIENT_SECRET_KEYS);
return { clientId, clientSecret };
return null;
}
function findGeminiCliOAuthPath(): string | null {
const geminiPath = findInPath("gemini");
if (!geminiPath) return null;
for (const root of getGeminiCliRoots(geminiPath)) {
const searchPaths = [
join(root, "node_modules", "@google", "gemini-cli-core", "dist", "src", "code_assist", "oauth2.js"),
join(root, "node_modules", "@google", "gemini-cli-core", "dist", "code_assist", "oauth2.js"),
];
for (const p of searchPaths) {
if (existsSync(p)) return p;
}
if (shouldSearchRoot(root)) {
const found = findFile(root, "oauth2.js", 8);
if (found) return found;
}
}
return null;
}
function getGeminiCliRoots(geminiPath: string): string[] {
const roots = new Set<string>();
const resolved = safeRealpath(geminiPath);
for (const p of [geminiPath, resolved].filter(Boolean) as string[]) {
for (const root of extractGeminiCliRootsFromFile(p)) {
roots.add(root);
}
const fromPath = extractGeminiCliRootFromPath(p);
if (fromPath) roots.add(fromPath);
}
for (const globalRoot of getGlobalNodeModulesRoots()) {
const candidate = join(globalRoot, "@google", "gemini-cli");
if (existsSync(candidate)) roots.add(candidate);
}
return [...roots].filter((root) => existsSync(root));
}
function extractGeminiCliRootsFromFile(filePath: string): string[] {
const roots: string[] = [];
try {
const content = readFileSync(filePath, "utf8");
if (!content.includes("gemini-cli")) return roots;
const dir = dirname(filePath);
const regex = /["']([^"'\\r\\n]*@google[\\/]+gemini-cli[\\/]+dist[\\/]+index\\.js)["']/gi;
for (const match of content.matchAll(regex)) {
const resolved = resolveShimPath(dir, match[1]);
const root = extractGeminiCliRootFromPath(resolved);
if (root) roots.push(root);
}
} catch {
// ignore non-text files or missing paths
}
return roots;
}
function resolveShimPath(baseDir: string, rawPath: string): string {
let candidate = rawPath
.replace(/%~?dp0%/gi, baseDir)
.replace(/\$PSScriptRoot/gi, baseDir)
.replace(/__dirname/g, baseDir);
if (!isAbsolute(candidate)) {
candidate = join(baseDir, candidate);
}
return normalize(candidate);
}
function extractGeminiCliRootFromPath(pathValue: string): string | null {
const normalized = pathValue.replace(/\\/g, "/");
const marker = "/@google/gemini-cli/";
const idx = normalized.indexOf(marker);
if (idx === -1) return null;
return normalize(`${normalized.slice(0, idx)}${marker.slice(0, -1)}`);
}
function safeRealpath(pathValue: string): string | null {
try {
return realpathSync(pathValue);
} catch {
return null;
}
}
function getGlobalNodeModulesRoots(): string[] {
const roots = new Set<string>();
const prefix = process.env.npm_config_prefix ?? process.env.NPM_CONFIG_PREFIX ?? process.env.PREFIX;
if (prefix) {
if (process.platform === "win32") {
roots.add(join(prefix, "node_modules"));
} else {
roots.add(join(prefix, "lib", "node_modules"));
}
}
if (process.platform === "win32") {
const appData = process.env.APPDATA;
if (appData) roots.add(join(appData, "npm", "node_modules"));
} else {
roots.add("/usr/local/lib/node_modules");
roots.add("/opt/homebrew/lib/node_modules");
}
const pnpmHome = process.env.PNPM_HOME;
if (pnpmHome) {
roots.add(join(pnpmHome, "global", "5", "node_modules"));
roots.add(join(pnpmHome, "global", "4", "node_modules"));
}
return [...roots].filter((root) => existsSync(root));
}
function shouldSearchRoot(root: string): boolean {
const normalized = root.replace(/\\/g, "/");
if (normalized === "/" || /^[A-Za-z]:\/?$/.test(normalized)) return false;
const segments = normalized.split("/").filter(Boolean);
return segments.length >= 3;
}
function findInPath(name: string): string | null {
const exts = process.platform === "win32" ? [".cmd", ".bat", ".exe", ""] : [""];
for (const dir of (process.env.PATH ?? "").split(delimiter)) {
for (const ext of exts) {
const p = join(dir, name + ext);
if (existsSync(p)) return p;
}
}
return null;
}
function findFile(dir: string, name: string, depth: number): string | null {
if (depth <= 0) return null;
try {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const p = join(dir, entry.name);
if (entry.isFile() && entry.name === name) return p;
if (entry.isDirectory() && !entry.name.startsWith(".")) {
const found = findFile(p, name, depth - 1);
if (found) return found;
}
}
} catch {}
return null;
}
function resolveOAuthClientConfig(): { clientId: string; clientSecret?: string } {
// 1. Check env vars first (user override)
const envClientId = resolveEnv(CLIENT_ID_KEYS);
const envClientSecret = resolveEnv(CLIENT_SECRET_KEYS);
if (envClientId) {
return { clientId: envClientId, clientSecret: envClientSecret };
}
// 2. Try to extract from installed Gemini CLI
const extracted = extractGeminiCliCredentials();
if (extracted?.clientId) {
return extracted;
}
// 3. No credentials available
throw new Error(
"Gemini CLI credentials not found. Install it first: brew install gemini-cli (or npm install -g @google/gemini-cli), or set GEMINI_CLI_OAUTH_CLIENT_ID.",
);
}
function isWSL(): boolean {
-40
View File
@@ -157,44 +157,4 @@ describe("agents_list", () => {
const research = agents?.find((agent) => agent.id === "research");
expect(research?.configured).toBe(false);
});
it("uses requesterAgentIdOverride when resolving allowlists", async () => {
configOverride = {
session: {
mainKey: "main",
scope: "per-sender",
},
agents: {
list: [
{
id: "cron-owner",
subagents: {
allowAgents: ["research"],
},
},
{
id: "research",
name: "Research",
},
],
},
};
const tool = createClawdbotTools({
agentSessionKey: "cron:job-1",
requesterAgentIdOverride: "cron-owner",
}).find((candidate) => candidate.name === "agents_list");
if (!tool) throw new Error("missing agents_list tool");
const result = await tool.execute("call5", {});
const agents = (
result.details as {
agents?: Array<{ id: string }>;
}
).agents;
expect(agents?.map((agent) => agent.id)).toEqual(["cron-owner", "research"]);
expect(result.details).toMatchObject({
requester: "cron-owner",
});
});
});
@@ -87,52 +87,6 @@ describe("clawdbot-tools: subagents", () => {
});
expect(childSessionKey?.startsWith("agent:research:subagent:")).toBe(true);
});
it("sessions_spawn honors requesterAgentIdOverride for cron sessions", async () => {
resetSubagentRegistryForTests();
callGatewayMock.mockReset();
configOverride = {
session: {
mainKey: "main",
scope: "per-sender",
},
agents: {
list: [
{
id: "cron-owner",
subagents: {
allowAgents: ["research"],
},
},
],
},
};
callGatewayMock.mockImplementation(async (opts: unknown) => {
const request = opts as { method?: string; params?: unknown };
if (request.method === "agent") {
return { runId: "run-2", status: "accepted", acceptedAt: 5200 };
}
return {};
});
const tool = createClawdbotTools({
agentSessionKey: "cron:job-1",
requesterAgentIdOverride: "cron-owner",
agentChannel: "whatsapp",
}).find((candidate) => candidate.name === "sessions_spawn");
if (!tool) throw new Error("missing sessions_spawn tool");
const result = await tool.execute("call11", {
task: "do thing",
agentId: "research",
});
expect(result.details).toMatchObject({
status: "accepted",
runId: "run-2",
});
});
it("sessions_spawn forbids cross-agent spawning when not allowed", async () => {
resetSubagentRegistryForTests();
callGatewayMock.mockReset();
+5 -13
View File
@@ -54,8 +54,6 @@ export function createClawdbotTools(options?: {
hasRepliedRef?: { value: boolean };
/** If true, the model has native vision capability */
modelHasVision?: boolean;
/** Explicit agent ID override for cron/hook sessions. */
requesterAgentIdOverride?: string;
}): AnyAgentTool[] {
const imageTool = options?.agentDir?.trim()
? createImageTool({
@@ -107,10 +105,7 @@ export function createClawdbotTools(options?: {
agentSessionKey: options?.agentSessionKey,
config: options?.config,
}),
createAgentsListTool({
agentSessionKey: options?.agentSessionKey,
requesterAgentIdOverride: options?.requesterAgentIdOverride,
}),
createAgentsListTool({ agentSessionKey: options?.agentSessionKey }),
createSessionsListTool({
agentSessionKey: options?.agentSessionKey,
sandboxed: options?.sandboxed,
@@ -134,7 +129,6 @@ export function createClawdbotTools(options?: {
agentGroupChannel: options?.agentGroupChannel,
agentGroupSpace: options?.agentGroupSpace,
sandboxed: options?.sandboxed,
requesterAgentIdOverride: options?.requesterAgentIdOverride,
}),
createSessionStatusTool({
agentSessionKey: options?.agentSessionKey,
@@ -150,12 +144,10 @@ export function createClawdbotTools(options?: {
config: options?.config,
workspaceDir: options?.workspaceDir,
agentDir: options?.agentDir,
agentId:
options?.requesterAgentIdOverride ??
resolveSessionAgentId({
sessionKey: options?.agentSessionKey,
config: options?.config,
}),
agentId: resolveSessionAgentId({
sessionKey: options?.agentSessionKey,
config: options?.config,
}),
sessionKey: options?.agentSessionKey,
messageChannel: options?.agentChannel,
agentAccountId: options?.agentAccountId,
-1
View File
@@ -293,7 +293,6 @@ export function createClawdbotCodingTools(options?: {
agentGroupChannel: options?.groupChannel ?? null,
agentGroupSpace: options?.groupSpace ?? null,
agentDir: options?.agentDir,
requesterAgentIdOverride: agentId,
sandboxRoot,
workspaceDir: options?.workspaceDir,
sandboxed: !!sandbox,
+2 -8
View File
@@ -19,11 +19,7 @@ type AgentListEntry = {
configured: boolean;
};
export function createAgentsListTool(opts?: {
agentSessionKey?: string;
/** Explicit agent ID override for cron/hook sessions. */
requesterAgentIdOverride?: string;
}): AnyAgentTool {
export function createAgentsListTool(opts?: { agentSessionKey?: string }): AnyAgentTool {
return {
label: "Agents",
name: "agents_list",
@@ -41,9 +37,7 @@ export function createAgentsListTool(opts?: {
})
: alias;
const requesterAgentId = normalizeAgentId(
opts?.requesterAgentIdOverride ??
parseAgentSessionKey(requesterInternalKey)?.agentId ??
DEFAULT_AGENT_ID,
parseAgentSessionKey(requesterInternalKey)?.agentId ?? DEFAULT_AGENT_ID,
);
const allowAgents = resolveAgentConfig(cfg, requesterAgentId)?.subagents?.allowAgents ?? [];
+1 -3
View File
@@ -67,8 +67,6 @@ export function createSessionsSpawnTool(opts?: {
agentGroupChannel?: string | null;
agentGroupSpace?: string | null;
sandboxed?: boolean;
/** Explicit agent ID override for cron/hook sessions where session key parsing may not work. */
requesterAgentIdOverride?: string;
}): AnyAgentTool {
return {
label: "Sessions",
@@ -131,7 +129,7 @@ export function createSessionsSpawnTool(opts?: {
});
const requesterAgentId = normalizeAgentId(
opts?.requesterAgentIdOverride ?? parseAgentSessionKey(requesterInternalKey)?.agentId,
parseAgentSessionKey(requesterInternalKey)?.agentId,
);
const targetAgentId = requestedAgentId
? normalizeAgentId(requestedAgentId)
@@ -170,7 +170,6 @@ export async function handleInlineActions(params: {
agentAccountId: (ctx as { AccountId?: string }).AccountId,
agentTo: ctx.OriginatingTo ?? ctx.To,
agentThreadId: ctx.MessageThreadId ?? undefined,
requesterAgentIdOverride: agentId,
agentDir,
workspaceDir,
config: cfg,
-1
View File
@@ -148,7 +148,6 @@ export async function handleToolsInvokeHttpRequest(
agentSessionKey: sessionKey,
agentChannel: messageChannel ?? undefined,
agentAccountId: accountId,
requesterAgentIdOverride: agentId,
config: cfg,
pluginToolAllowlist: collectExplicitAllowlist([
profilePolicy,