3a7145db1a
* Scope installation token permissions in restricted mode
In restricted/disabled bash mode, the installation token is now scoped
to match the workflow's permissions block. This preserves fork push
capability while limiting what the agent can do with the token.
- Read workflow permissions from pullfrog.yml at runtime
- Pass permissions to API when acquiring installation token
- Clear OIDC env vars in restricted mode to prevent token minting
- Simplify setupGit by moving token resolution to main.ts
* Address review feedback: fail closed with default permissions
- Add restrictive default permissions (contents:read, pull_requests:read,
issues:read) as fallback when workflow permissions can't be read
- Add support for job-level permissions via GITHUB_JOB env var
- Fix misleading comment about token resolution in restricted mode
- Add documentation about fork PR checkout behavior
* Simplify to separate git/MCP tokens without workflow permission scoping
- gitToken: minimal contents:write only (assumed exfiltratable)
- mcpToken: full installation token (not exfiltratable via MCP tools)
- Remove workflowPermissions.ts - security-conscious users can pass
their own token via GH_TOKEN or inputs.token
- Add type-safe InstallationTokenPermissions to github.ts and API route
* Rename `write` permission to `push` and remove vestigial tool blocking
The `write` permission was previously used to block local file write tools
in agents. This was security theater since bash can write files anyway.
Now `push` only controls the git token scope:
- push: enabled → contents:write (can push commits)
- push: disabled → contents:read (read-only, can't push)
Changes:
- Rename `write` to `push` in action.yml, Prisma schema, and all TS types
- Remove vestigial write tool blocking from all agents (claude, cursor,
gemini, opencode, codex)
- Add data-preserving Prisma migration using RENAME COLUMN
- Update UI: "Write files" → "Git push" with updated description
* add PID namespace isolation for bash sandbox
when running in CI, attempts to use unshare --pid to create a new PID
namespace for bash subprocesses. this prevents the /proc/$PPID/environ
attack where a malicious command could read secrets from the parent
process's environment.
the protection works by:
1. creating a new PID namespace (subprocess becomes PID 1)
2. mounting fresh /proc showing only sandbox PIDs
3. parent PIDs become invisible (PPID = 0, /proc/0 doesn't exist)
combined with filterEnv(), this provides complete protection against
/proc-based secret theft. falls back gracefully if namespaces aren't
available.
includes test script to verify the protection works.
* add PID namespace test to CI workflow
tests whether unshare --pid works on GHA runners out of the box,
and if not, whether enabling via sysctl helps. also runs the
pidNamespace.ts test to verify the full protection.
* fix pnpm setup and add procIsolation agent test
- fix pnpm/action-setup by specifying package_json_file path
- add procIsolation crossagent test that has agent attempt to
read secrets via /proc/$PPID/environ
- add procIsolation to CI test matrix
* add pid-namespace test job to main workflow
this job tests unshare --pid capabilities on GHA runners and runs
the pidNamespace.ts adhoc test to verify /proc isolation works
* test bubblewrap's sysctl approach for enabling namespaces
- write to /etc/sysctl.d/99-userns.conf and run sysctl --system
- try aa-complain on unshare binary
- more detailed diagnostics
* fix pidNamespace test and add sudo-unshare fallback for GHA
- fix reference error in pidNamespace.ts (renamed function but didn't update calls)
- add sudo-unshare as fallback method for GHA runners where unprivileged
namespaces are blocked but sudo is available
- update bash.ts to detect and use sudo unshare when unprivileged fails
* consolidate security docs and document PID namespace isolation
- update security.md with current implementation details
- document sudo unshare fallback for GHA runners
- add testing instructions for local Docker and CI
- add "Further Exploration" section with Landlock and path validation ideas
- delete bash-sandbox.md and landlock.md (consolidated into security.md)
* move procIsolation test to adhoc folder
the procIsolation test requires PID namespace capabilities that aren't
available in the Docker test environment. moved to adhoc/ so it's excluded
from default test runs and can be run explicitly when needed (e.g. via
the pid-namespace CI job or locally with --privileged docker).
* fix Docker test environment for PID namespace isolation
- add CI and GITHUB_ACTIONS to testEnvAllowList so sandbox detection runs
- add --privileged to Docker run for PID namespace support (unshare)
this fixes the test environment to properly test the sandbox. in production,
the action runs directly on GHA runner where sudo unshare works.
* fix getJobToken() to work in test environment
add fallback to GH_TOKEN and GITHUB_TOKEN when INPUT_TOKEN is not set.
this allows tests to run without requiring workflow-level token input.
the token resolution order is:
1. INPUT_TOKEN (from workflow `with: token:`)
2. GH_TOKEN (external token override)
3. GITHUB_TOKEN (pre-acquired in tests or from GHA env)
* security: filter secrets from all subprocess environments
- extract filterEnv() to shared utils/secrets.ts
- make $() utility filter secrets by default (git, npm, etc. don't need them)
- disable git hooks via core.hooksPath to prevent hook-based exfiltration
- git auth uses token embedded in URL, not env vars
this prevents malicious git hooks, npm postinstall scripts, and other
code execution vectors from exfiltrating GITHUB_TOKEN and API keys.
* docs: clarify defense-in-depth security model
update security.md to explain why BOTH layers are required:
- filterEnv(): cleans child's own /proc/self/environ
- PID namespace: hides parent's /proc entries
PID namespace alone isn't sufficient - with --mount-proc, the child
becomes PID 1, so /proc/1/environ is the child's OWN environment.
without filterEnv(), secrets would still be accessible there.
* add procSandbox crossagent test for PID namespace security
- add crossagent/procSandbox.ts: security test that instructs agent to try
various /proc attack vectors and validates sandbox blocks them
- update wiki/security.md: document PID namespace isolation details, add
verification commands, explain why sudo inside sandbox doesn't break security
- update docker.ts: use node:24 with sudo for GHA-like test environment
- update instructions.ts: allow disabling security messaging for pentests
- clean up adhoc test files (procIsolation.ts, securityAudit.ts)
the procSandbox test sets SANDBOX_TEST_TOKEN (matches *_TOKEN filter), gives
the agent explicit hints about attack vectors (/proc, sudo, nsenter, etc.),
disables prompt-based mitigations, and validates the secret is never leaked.
* move procSandbox test to agnostic/ (runs with one agent)
* WIP
* docs: add agent testing guide (pnpm play, Docker, pentesting)
* docs: add CI details to agent testing guide
* docs: add interesting findings and gotchas from pentesting
* improve test fidelity: auto-set CI=true, verify sandbox active
- docker.ts: always set CI=true in container so sandbox activates
- docker.ts: skip sudo/user setup if already done (faster reruns)
- bash.ts: export getSandboxMethod() for diagnostics
- bash.ts: add debug log when sandbox disabled
- procSandbox.ts: add sandbox_was_active check to catch vacuous passes
the CI=true change is critical: without it, PID namespace isolation
is skipped and security tests pass without actually testing anything.
* docs: update agent-testing.md with CI=true auto-set note
* docs: clarify log format is agent-specific
* fix git auth, simplify MCP tools, add adversarial tests
- fix gitWithAuth to use Basic auth format (Bearer doesn't work with git's http.extraheader)
- fix token.ts: push:restricted now correctly gets contents:write
- fix github.ts: pass permissions when acquiring installation tokens locally
- remove commit_files and create_branch MCP tools (redundant, don't require credentials)
- remove containsSecrets() - trivially bypassable, not sound security
- add agnostic adversarial tests: pushDisabled, pushRestricted, tokenExfil
- update instructions.ts to clearly list available git MCP tools
- add wiki/git.md documenting credential isolation and push permission tiers
- update wiki/docker.md with custom image considerations
- update wiki/agent-testing.md with adversarial testing patterns
* fix type errors after rebase
- change ResolveTokensParams.push from ToolPermission to PushPermission
- use tags: ["agnostic"] instead of agnostic: true in test files
* fix cleanup permission error in sandbox tests
when sandbox isolation is enabled (CI=true), files created by the unshare
subprocess may have different ownership, causing rmSync to fail with EACCES.
this error in the finally block was overriding the test's success result.
fix: wrap cleanup in try-catch and fall back to sudo rm if rmSync fails.
* Add adhoc
* Handle git config/remote bypasses
* add git hooks protection and simplify ToolState
- disable git hooks in restricted mode via -c core.hooksPath=/dev/null
- add gitHooks adversarial test to verify hook protection works
- unify prNumber/issueNumber into single issueNumber field
- add pushUrl to ToolState for push validation
- add generateTestMarker() for simpler single-agent test markers
- export SENSITIVE_PATTERNS and isSensitiveEnvName from secrets.ts
- remove redundant pidNamespace.ts (duplicated by procSandbox.ts)
- update documentation
* harden $git() auth: subcommand whitelist, binary tamper detection
- rename gitWithAuth() to $git() with explicit subcommand first arg
- restrict to "fetch" | "push" at type level (filters don't run for these)
- resolve git binary path at startup via resolveGit(), sha256 fingerprint
- verify hash before each $git() call to detect binary replacement
- rename disableHooks to restricted for cleaner semantics
- document filter exfiltration attack and empirical verification in wiki
* remove redundant pid-namespace CI job
the PID namespace isolation testing is now handled by
action/test/agnostic/procSandbox.ts via pnpm runtest agnostic
* fix push_branch for new branches and improve token leak detection
- getPushDestination now falls back to origin/<branch> when @{push}
is not configured (happens for new branches created locally)
- gitPerms validator now checks for actual token patterns instead
of matching "x-access-token" string in test instructions
* use kebab-case for test names
* simplify shell env API: "restricted" | "inherit" | object
replace passFullEnv boolean with cleaner env option that accepts:
- "restricted" (default): filterEnv() to prevent secret leakage
- "inherit": full process.env
- object: custom env merged with restricted base
* share EnvMode and resolveEnv between shell.ts and bash.ts
move shared env resolution logic to secrets.ts
* add env option to bash tool (default: restricted)
* delete agent-testing.md (renamed to adversarial.md)
* Add checkout tests
* reframe githooks test prompt to avoid claude safety refusal
claude was refusing to execute the test because the prompt used words
like "malicious" and "security testing". reframed as a debugging task
with innocuous env var name (TESTING_DEBUG_TAG) per adversarial.md guidance.
Co-authored-by: Cursor <cursoragent@cursor.com>
* clean up verbose token acquisition logs
move logging responsibility to call sites which have better context
(git token vs MCP token). remove redundant intermediate OIDC logs
and unused "(permission-scoped)" suffix.
Co-authored-by: Cursor <cursoragent@cursor.com>
* isolate agnostic tests with matrix strategy, fix .pullfrog-env secret leak
- split action-agnostic into per-test matrix jobs for isolated logs and filesystems
- only write explicitly opted-in env vars to .pullfrog-env via fileAgentEnv
(fixes token-exfil test where claude found SANDBOX_TEST_TOKEN on disk)
- mcpmerge test opts in via fileAgentEnv for cursor's repo-level MCP fallback
Co-authored-by: Cursor <cursoragent@cursor.com>
* remove env parameter from bash tool to prevent agents bypassing filterEnv
the bash tool exposed an `env` parameter accepting "restricted" | "inherit"
which allowed agents to pass env: "inherit" and see all secrets including
SANDBOX_TEST_TOKEN, bypassing the restricted environment filtering entirely.
env mode is now determined internally (always restricted).
Co-authored-by: Cursor <cursoragent@cursor.com>
* use pullfrog/test-repo for push tests to stop polluting main repo
push tests were creating branches and tags on pullfrog/app directly.
now all push tests (push-restricted, push-disabled, push-enabled,
git-permissions) target pullfrog/test-repo instead.
Co-authored-by: Cursor <cursoragent@cursor.com>
* use pullfrog/test-repo for all tests, not just push tests
no test should clone or operate on pullfrog/app directly.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix token scoping for test-repo and bash timeout defaults
- acquireTokenViaOIDC now includes GITHUB_REPOSITORY repo in token
scope so push tests work against pullfrog/test-repo
- bash tool default timeout: 120s -> 30s, cap: 600s -> 120s
- activity timeout: 30s -> 60s
- prevents hung bash commands (e.g. find /) from killing the agent
via activity timeout
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
363 lines
12 KiB
TypeScript
363 lines
12 KiB
TypeScript
// changes to effort level configuration should be reflected in wiki/effort.md and docs/effort.mdx
|
|
// changes to tool permissions should be reflected in wiki/granular-tools.md
|
|
// changes to web search configuration should be reflected in wiki/websearch.md
|
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
import { homedir } from "node:os";
|
|
import { join } from "node:path";
|
|
import type { Effort } from "../external.ts";
|
|
import { ghPullfrogMcpName } from "../external.ts";
|
|
import { markActivity } from "../utils/activity.ts";
|
|
import { log } from "../utils/cli.ts";
|
|
import { installFromGithub } from "../utils/install.ts";
|
|
import { spawn } from "../utils/subprocess.ts";
|
|
import { getGitHubInstallationToken } from "../utils/token.ts";
|
|
import { type AgentRunContext, agent } from "./shared.ts";
|
|
|
|
// effort configuration: model + thinking level
|
|
// thinkingLevel is set via settings.json modelConfig.generateContentConfig.thinkingConfig
|
|
// see: https://ai.google.dev/gemini-api/docs/thinking#thinking-levels
|
|
// latest models:
|
|
const geminiEffortConfig: Record<Effort, { model: string; thinkingLevel: string }> = {
|
|
// https://ai.google.dev/gemini-api/docs/models
|
|
// the docs mention needing to enable preview features for these models but if you
|
|
// pass the model directly it works if we ever did need to do something like this,
|
|
// we could write to .gemini/settings.json
|
|
mini: { model: "gemini-3-flash-preview", thinkingLevel: "LOW" },
|
|
auto: { model: "gemini-3-flash-preview", thinkingLevel: "HIGH" },
|
|
max: { model: "gemini-3-pro-preview", thinkingLevel: "HIGH" },
|
|
} as const;
|
|
|
|
// gemini cli event types inferred from stream-json output (NDJSON format)
|
|
interface GeminiInitEvent {
|
|
type: "init";
|
|
timestamp?: string;
|
|
session_id?: string;
|
|
model?: string;
|
|
[key: string]: unknown;
|
|
}
|
|
|
|
interface GeminiMessageEvent {
|
|
type: "message";
|
|
timestamp?: string;
|
|
role?: "user" | "assistant";
|
|
content?: string;
|
|
delta?: boolean;
|
|
[key: string]: unknown;
|
|
}
|
|
|
|
interface GeminiToolUseEvent {
|
|
type: "tool_use";
|
|
timestamp?: string;
|
|
tool_name?: string;
|
|
tool_id?: string;
|
|
parameters?: unknown;
|
|
[key: string]: unknown;
|
|
}
|
|
|
|
interface GeminiToolResultEvent {
|
|
type: "tool_result";
|
|
timestamp?: string;
|
|
tool_id?: string;
|
|
status?: "success" | "error";
|
|
output?: string;
|
|
[key: string]: unknown;
|
|
}
|
|
|
|
interface GeminiResultEvent {
|
|
type: "result";
|
|
timestamp?: string;
|
|
status?: "success" | "error";
|
|
stats?: {
|
|
total_tokens?: number;
|
|
input_tokens?: number;
|
|
output_tokens?: number;
|
|
duration_ms?: number;
|
|
tool_calls?: number;
|
|
};
|
|
[key: string]: unknown;
|
|
}
|
|
|
|
type GeminiEvent =
|
|
| GeminiInitEvent
|
|
| GeminiMessageEvent
|
|
| GeminiToolUseEvent
|
|
| GeminiToolResultEvent
|
|
| GeminiResultEvent;
|
|
|
|
let assistantMessageBuffer = "";
|
|
|
|
const messageHandlers = {
|
|
init: (_event: GeminiInitEvent) => {
|
|
log.debug(JSON.stringify(_event, null, 2));
|
|
// initialization event - no logging needed
|
|
assistantMessageBuffer = "";
|
|
},
|
|
message: (event: GeminiMessageEvent) => {
|
|
log.debug(JSON.stringify(event, null, 2));
|
|
if (event.role === "assistant" && event.content?.trim()) {
|
|
if (event.delta) {
|
|
// accumulate delta messages
|
|
assistantMessageBuffer += event.content;
|
|
} else {
|
|
// final message - log it
|
|
const message = event.content.trim();
|
|
if (message) {
|
|
log.box(message, { title: "Gemini" });
|
|
}
|
|
assistantMessageBuffer = "";
|
|
}
|
|
} else if (event.role === "assistant" && !event.delta && assistantMessageBuffer.trim()) {
|
|
// if we have buffered content and get a non-delta message, log the buffer
|
|
log.box(assistantMessageBuffer.trim(), { title: "Gemini" });
|
|
assistantMessageBuffer = "";
|
|
}
|
|
},
|
|
tool_use: (event: GeminiToolUseEvent) => {
|
|
log.debug(JSON.stringify(event, null, 2));
|
|
if (event.tool_name) {
|
|
log.toolCall({
|
|
toolName: event.tool_name,
|
|
input: event.parameters || {},
|
|
});
|
|
}
|
|
},
|
|
tool_result: (event: GeminiToolResultEvent) => {
|
|
log.debug(JSON.stringify(event, null, 2));
|
|
if (event.status === "error") {
|
|
const errorMsg =
|
|
typeof event.output === "string" ? event.output : JSON.stringify(event.output);
|
|
log.warning(`Tool call failed: ${errorMsg}`);
|
|
} else if (event.output) {
|
|
// log successful tool result so it appears in output
|
|
const outputStr =
|
|
typeof event.output === "string" ? event.output : JSON.stringify(event.output);
|
|
log.debug(`tool output: ${outputStr}`);
|
|
}
|
|
},
|
|
result: async (event: GeminiResultEvent) => {
|
|
log.debug(JSON.stringify(event, null, 2));
|
|
// log any remaining buffered assistant message
|
|
if (assistantMessageBuffer.trim()) {
|
|
log.box(assistantMessageBuffer.trim(), { title: "Gemini" });
|
|
assistantMessageBuffer = "";
|
|
}
|
|
|
|
if (event.status === "success" && event.stats) {
|
|
const stats = event.stats;
|
|
const rows: Array<Array<{ data: string; header?: boolean } | string>> = [
|
|
[
|
|
{ data: "Input Tokens", header: true },
|
|
{ data: "Output Tokens", header: true },
|
|
{ data: "Total Tokens", header: true },
|
|
{ data: "Tool Calls", header: true },
|
|
{ data: "Duration (ms)", header: true },
|
|
],
|
|
[
|
|
String(stats.input_tokens || 0),
|
|
String(stats.output_tokens || 0),
|
|
String(stats.total_tokens || 0),
|
|
String(stats.tool_calls || 0),
|
|
String(stats.duration_ms || 0),
|
|
],
|
|
];
|
|
log.table(rows);
|
|
} else if (event.status === "error") {
|
|
log.error(`Gemini CLI failed: ${JSON.stringify(event)}`);
|
|
}
|
|
},
|
|
};
|
|
|
|
async function installGemini(githubInstallationToken?: string): Promise<string> {
|
|
return await installFromGithub({
|
|
owner: "google-gemini",
|
|
repo: "gemini-cli",
|
|
assetName: "gemini.js",
|
|
...(githubInstallationToken && { githubInstallationToken }),
|
|
});
|
|
}
|
|
|
|
export const gemini = agent({
|
|
name: "gemini",
|
|
install: installGemini,
|
|
run: async (ctx) => {
|
|
// install CLI at start of run - use token for GitHub API rate limiting
|
|
const cliPath = await installGemini(getGitHubInstallationToken());
|
|
|
|
const model = configureGeminiSettings(ctx);
|
|
|
|
if (!process.env.GOOGLE_API_KEY && !process.env.GEMINI_API_KEY) {
|
|
throw new Error("GOOGLE_API_KEY or GEMINI_API_KEY is required for gemini agent");
|
|
}
|
|
|
|
// build CLI args - --yolo for auto-approval
|
|
// tool restrictions handled via settings.json tools.exclude
|
|
const args = [
|
|
"--model",
|
|
model,
|
|
"--yolo",
|
|
"--output-format=stream-json",
|
|
"-p",
|
|
ctx.instructions.full,
|
|
];
|
|
|
|
let finalOutput = "";
|
|
let stdoutBuffer = "";
|
|
|
|
try {
|
|
const result = await spawn({
|
|
cmd: "node",
|
|
args: [cliPath, ...args],
|
|
env: process.env,
|
|
onStdout: async (chunk) => {
|
|
const text = chunk.toString();
|
|
finalOutput += text;
|
|
|
|
// buffer incomplete lines across chunks (NDJSON format)
|
|
stdoutBuffer += text;
|
|
const lines = stdoutBuffer.split("\n");
|
|
|
|
// keep the last element (may be incomplete) in the buffer
|
|
stdoutBuffer = lines.pop() || "";
|
|
|
|
for (const line of lines) {
|
|
const trimmed = line.trim();
|
|
if (!trimmed) continue;
|
|
|
|
log.debug(`[gemini stdout] ${trimmed}`);
|
|
|
|
try {
|
|
const event = JSON.parse(trimmed) as GeminiEvent;
|
|
markActivity(); // reset activity timeout on every event
|
|
const handler = messageHandlers[event.type as keyof typeof messageHandlers];
|
|
if (handler) {
|
|
await handler(event as never);
|
|
}
|
|
} catch {
|
|
// ignore parse errors - might be non-JSON output from gemini cli
|
|
log.debug(`[gemini] non-JSON stdout line: ${trimmed.substring(0, 200)}`);
|
|
}
|
|
}
|
|
},
|
|
onStderr: (chunk) => {
|
|
const trimmed = chunk.trim();
|
|
if (trimmed) {
|
|
log.debug(`[gemini stderr] ${trimmed}`);
|
|
log.warning(trimmed);
|
|
finalOutput += trimmed + "\n";
|
|
}
|
|
},
|
|
});
|
|
|
|
if (result.exitCode !== 0) {
|
|
const errorMessage =
|
|
result.stderr ||
|
|
finalOutput ||
|
|
result.stdout ||
|
|
"Unknown error - no output from Gemini CLI";
|
|
log.error(`Gemini CLI exited with code ${result.exitCode}: ${errorMessage}`);
|
|
return {
|
|
success: false,
|
|
error: errorMessage,
|
|
output: finalOutput || result.stdout || "",
|
|
};
|
|
}
|
|
|
|
finalOutput = finalOutput || result.stdout || "Gemini CLI completed successfully.";
|
|
log.info("» Gemini CLI completed successfully");
|
|
|
|
return {
|
|
success: true,
|
|
output: finalOutput,
|
|
};
|
|
} catch (error) {
|
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
log.error(`Failed to run Gemini CLI: ${errorMessage}`);
|
|
return {
|
|
success: false,
|
|
error: errorMessage,
|
|
output: finalOutput || "",
|
|
};
|
|
}
|
|
},
|
|
});
|
|
|
|
/**
|
|
* Configure Gemini CLI settings by writing to settings.json.
|
|
* Returns the model to use for CLI args.
|
|
*
|
|
* See: https://github.com/google-gemini/gemini-cli/blob/main/docs/get-started/configuration.md
|
|
*/
|
|
function configureGeminiSettings(ctx: AgentRunContext): string {
|
|
const { model, thinkingLevel } = geminiEffortConfig[ctx.payload.effort];
|
|
log.info(`» using model: ${model}, thinkingLevel: ${thinkingLevel}`);
|
|
|
|
const realHome = homedir();
|
|
const geminiConfigDir = join(realHome, ".gemini");
|
|
const settingsPath = join(geminiConfigDir, "settings.json");
|
|
mkdirSync(geminiConfigDir, { recursive: true });
|
|
|
|
// read existing settings if present
|
|
let existingSettings: Record<string, unknown> = {};
|
|
try {
|
|
const content = readFileSync(settingsPath, "utf-8");
|
|
existingSettings = JSON.parse(content);
|
|
} catch {
|
|
// file doesn't exist or is invalid - start fresh
|
|
}
|
|
|
|
// convert to Gemini's expected format (httpUrl for HTTP transport, no type field)
|
|
interface GeminiMcpServerConfig {
|
|
command?: string;
|
|
args?: string[];
|
|
env?: Record<string, string>;
|
|
cwd?: string;
|
|
url?: string;
|
|
httpUrl?: string;
|
|
headers?: Record<string, string>;
|
|
timeout?: number;
|
|
trust?: boolean;
|
|
description?: string;
|
|
includeTools?: string[];
|
|
excludeTools?: string[];
|
|
}
|
|
log.info(`» adding MCP server '${ghPullfrogMcpName}' at ${ctx.mcpServerUrl}...`);
|
|
const geminiMcpServers: Record<string, GeminiMcpServerConfig> = {
|
|
[ghPullfrogMcpName]: {
|
|
httpUrl: ctx.mcpServerUrl,
|
|
trust: true, // trust our own MCP server to avoid confirmation prompts
|
|
},
|
|
};
|
|
|
|
// build tools.exclude based on permissions (v0.3.0+ nested format)
|
|
const bash = ctx.payload.bash;
|
|
const exclude: string[] = [];
|
|
if (bash !== "enabled") exclude.push("run_shell_command");
|
|
if (ctx.payload.web === "disabled") exclude.push("web_fetch");
|
|
if (ctx.payload.search === "disabled") exclude.push("google_web_search");
|
|
|
|
// merge with existing settings, overwriting mcpServers and modelConfig
|
|
const newSettings: Record<string, unknown> = {
|
|
...existingSettings,
|
|
mcpServers: geminiMcpServers,
|
|
// configure thinking level via modelConfig
|
|
// see: https://ai.google.dev/api/generate-content (ThinkingConfig)
|
|
modelConfig: {
|
|
generateContentConfig: {
|
|
thinkingConfig: {
|
|
thinkingLevel,
|
|
},
|
|
},
|
|
},
|
|
// v0.3.0+ nested format
|
|
...(exclude.length > 0 && { tools: { exclude } }),
|
|
};
|
|
|
|
writeFileSync(settingsPath, JSON.stringify(newSettings, null, 2), "utf-8");
|
|
log.info(`» Gemini settings written to ${settingsPath}`);
|
|
if (exclude.length > 0) {
|
|
log.info(`» excluded tools: ${exclude.join(", ")}`);
|
|
}
|
|
|
|
return model;
|
|
}
|