OpenTalon / app · opentalon.ai / native / runtime / gemini-agent.cjs
| 1 | // Gemini runs through Google's Antigravity CLI (agy), the signed-in successor to the |
| 2 | // Gemini CLI. Tasks and chat use `agy acp`: JSON-RPC 2.0 over stdio with a session-scoped |
| 3 | // MCP list, permission requests, resume and cancel. Drafting uses documented print mode. |
| 4 | // Verified November 23, 2026 against agy 1.5.15 (`agy --help`, `agy acp --help`, a live |
| 5 | // initialize and signed-out session/new) and the official docs: |
| 6 | // https://antigravity.google/docs/cli/acp/ https://antigravity.google/docs/cli/headless/ |
| 7 | // https://agentclientprotocol.com/protocol/v1/ |
| 8 | const fs = require('node:fs') |
| 9 | const os = require('node:os') |
| 10 | const path = require('node:path') |
| 11 | const { AppError } = require('./contracts.cjs') |
| 12 | |
| 13 | const protocolVersion = 1 |
| 14 | const signInMethods = ['oauth-personal', 'oauth-business'] |
| 15 | // OpenTalon supports the cached Google sign-in only. These would switch agy to an API |
| 16 | // key, default credentials or another endpoint without the owner choosing that here. |
| 17 | const unsupportedAuthEnvironment = ['GEMINI_API_KEY', 'AGY_ADC_AUTH', 'GOOGLE_GEMINI_BASE_URL'] |
| 18 | const transportOptions = { jsonrpc: true, withoutEnvironment: unsupportedAuthEnvironment } |
| 19 | const thinkingLevels = { |
| 20 | low: ['low'], medium: ['medium'], high: ['high'], xhigh: ['xhigh', 'extra'], max: ['max'], |
| 21 | } |
| 22 | |
| 23 | function geminiArguments(permissionMode, scopedSettings = []) { |
| 24 | // Full access is the only mode that skips approval. Every other mode keeps agy's |
| 25 | // terminal sandbox on and routes approvals back to OpenTalon. |
| 26 | return [...scopedSettings, 'acp', permissionMode === 'full-access' ? '--dangerously-skip-permissions' : '--sandbox'] |
| 27 | } |
| 28 | |
| 29 | function geminiToolServer(config) { |
| 30 | return { |
| 31 | name: 'opentalon', |
| 32 | command: config.command, |
| 33 | args: config.args ?? [], |
| 34 | env: Object.entries(config.env ?? {}).map(([name, value]) => ({ name, value })), |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // Session-only CLI permissions keep user-installed servers out of this task without |
| 39 | // changing their registration or the owner's saved rules. |
| 40 | function geminiScopedSettings(cwd, home = os.homedir()) { |
| 41 | const files = [path.join(home, '.gemini', 'config'), path.join(cwd, '.agents')].flatMap((folder) => { |
| 42 | let plugins = [] |
| 43 | try { |
| 44 | plugins = fs.readdirSync(path.join(folder, 'plugins')) |
| 45 | .map((plugin) => path.join(folder, 'plugins', plugin, 'mcp_config.json')) |
| 46 | } catch {} |
| 47 | return [path.join(folder, 'mcp_config.json'), ...plugins] |
| 48 | }) |
| 49 | const names = new Set() |
| 50 | for (const file of files) { |
| 51 | let text |
| 52 | try { text = fs.readFileSync(file, 'utf8') } catch { continue } |
| 53 | if (!text.trim()) continue |
| 54 | let servers |
| 55 | try { servers = JSON.parse(text).mcpServers ?? {} } catch { servers = null } |
| 56 | if (!servers || typeof servers !== 'object' || Array.isArray(servers)) |
| 57 | throw new AppError('AGENT_TOOL_SERVERS', `Gemini’s tool server settings could not be read (${file}). Fix or remove that file, then send this again.`) |
| 58 | for (const [name, server] of Object.entries(servers)) if (server?.disabled !== true) names.add(name) |
| 59 | } |
| 60 | if (!names.size) return [] |
| 61 | if (names.has('opentalon') || [...names].some(name => !/^[\w.-]+$/.test(name))) |
| 62 | throw new AppError('AGENT_TOOL_SERVERS', 'A saved Gemini server conflicts with the scoped OpenTalon task connection. Rename that server before sending this task.') |
| 63 | const permissions = {} |
| 64 | for (const file of [path.join(home, '.gemini', 'antigravity-cli', 'settings.json'), path.join(cwd, '.agents', 'settings.json')]) { |
| 65 | if (!fs.existsSync(file)) continue |
| 66 | try { |
| 67 | const saved = JSON.parse(fs.readFileSync(file, 'utf8')).permissions ?? {} |
| 68 | for (const key of ['deny', 'ask', 'allow']) { |
| 69 | if (saved[key] === undefined) continue |
| 70 | if (!Array.isArray(saved[key]) || saved[key].some(rule => typeof rule !== 'string')) throw Error() |
| 71 | permissions[key] = [...new Set([...(permissions[key] || []), ...saved[key]])] |
| 72 | } |
| 73 | } catch { throw new AppError('AGENT_TOOL_SERVERS', 'Gemini’s saved permission rules could not be read safely.') } |
| 74 | } |
| 75 | permissions.deny = [...new Set([...(permissions.deny || []), ...[...names].map(name => `mcp(${name}/*)`)])] |
| 76 | return ['--settings', JSON.stringify({permissions})] |
| 77 | } |
| 78 | |
| 79 | function geminiFailure(error) { |
| 80 | if (error instanceof AppError) return error |
| 81 | if (/authenticat|auth_required|not signed in|log ?in required/i.test(error?.message ?? '')) |
| 82 | return new AppError('AGENT_AUTH_REQUIRED', 'Gemini needs you to sign in. Run agy in Terminal, sign in with Google, then send this again.') |
| 83 | return error |
| 84 | } |
| 85 | |
| 86 | function assertGeminiRuntime(result) { |
| 87 | if (result?.protocolVersion !== protocolVersion) |
| 88 | throw new AppError('AGENT_UNSUPPORTED', 'This Antigravity CLI is not compatible with OpenTalon. Update it with agy update, then send this again.') |
| 89 | if (!result.authMethods?.some((method) => signInMethods.includes(method?.id))) |
| 90 | throw new AppError('AGENT_AUTH_UNSUPPORTED', 'This Antigravity CLI does not offer Google sign-in, the only Gemini sign-in OpenTalon supports.') |
| 91 | return result.agentCapabilities ?? {} |
| 92 | } |
| 93 | |
| 94 | async function geminiInitialize(transport) { |
| 95 | return assertGeminiRuntime(await transport.request('initialize', { |
| 96 | protocolVersion, |
| 97 | // No file or terminal delegation: agy uses its own sandboxed tools. |
| 98 | clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, |
| 99 | clientInfo: { name: 'opentalon', title: 'OpenTalon', version: '0.1.0' }, |
| 100 | })) |
| 101 | } |
| 102 | |
| 103 | // Starts or reopens one conversation. Never calls `authenticate`: that opens a browser |
| 104 | // sign-in the owner did not ask for. A signed-out CLI fails here instead. |
| 105 | async function geminiSession(transport, capabilities, { cwd, server, sessionId }) { |
| 106 | const params = { cwd, mcpServers: [server] } |
| 107 | try { |
| 108 | if (!sessionId) { |
| 109 | const session = await transport.request('session/new', params) |
| 110 | if (typeof session?.sessionId !== 'string' || !/^[A-Za-z0-9_-]{1,150}$/.test(session.sessionId)) |
| 111 | throw new AppError('AGENT_UNSUPPORTED', 'Gemini did not return a conversation OpenTalon can save.') |
| 112 | return session |
| 113 | } |
| 114 | const resume = capabilities.sessionCapabilities?.resume ? 'session/resume' |
| 115 | : capabilities.loadSession ? 'session/load' : null |
| 116 | if (!resume) |
| 117 | throw new AppError('AGENT_UNSUPPORTED', 'This Antigravity CLI cannot reopen a saved conversation. Update it with agy update.') |
| 118 | const session = (await transport.request(resume, { ...params, sessionId })) ?? {} |
| 119 | if (session.sessionId !== undefined && session.sessionId !== sessionId) |
| 120 | throw new AppError('AGENT_RESUME_MISMATCH', 'Gemini did not resume the original conversation. Review it before resending the comments.') |
| 121 | return { ...session, sessionId } |
| 122 | } catch (error) { |
| 123 | throw geminiFailure(error) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | // ACP agents advertise choices as config options, with models/modes as the older form. |
| 128 | function choice(session, category) { |
| 129 | const option = (session.configOptions ?? []) |
| 130 | .find((entry) => entry?.category === category && Array.isArray(entry.options)) |
| 131 | if (option) { |
| 132 | const entries = option.options.flatMap((entry) => Array.isArray(entry.options) ? entry.options : [entry]) |
| 133 | return { |
| 134 | entries: entries.map((entry) => ({ id: entry.value, name: entry.name })), |
| 135 | current: option.currentValue, |
| 136 | set: (id) => ['session/set_config_option', { sessionId: session.sessionId, configId: option.id, value: id }], |
| 137 | } |
| 138 | } |
| 139 | if (category === 'model' && Array.isArray(session.models?.availableModels)) |
| 140 | return { |
| 141 | entries: session.models.availableModels.map((model) => ({ id: model.modelId, name: model.name })), |
| 142 | current: session.models.currentModelId, |
| 143 | set: (id) => ['session/set_model', { sessionId: session.sessionId, modelId: id }], |
| 144 | } |
| 145 | if (category === 'mode' && Array.isArray(session.modes?.availableModes)) |
| 146 | return { |
| 147 | entries: session.modes.availableModes.map((mode) => ({ id: mode.id, name: mode.name })), |
| 148 | current: session.modes.currentModeId, |
| 149 | set: (id) => ['session/set_mode', { sessionId: session.sessionId, modeId: id }], |
| 150 | } |
| 151 | return null |
| 152 | } |
| 153 | |
| 154 | async function choose(transport, session, category, id) { |
| 155 | const available = choice(session, category) |
| 156 | if (available.current === id) return |
| 157 | const result = await transport.request(...available.set(id)) |
| 158 | if (Array.isArray(result?.configOptions)) { |
| 159 | session.configOptions = result.configOptions |
| 160 | if (choice(session, category)?.current !== id) throw new Error(`Gemini kept a different ${category}.`) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | const unavailableModel = (model) => new AppError('AGENT_MODEL_UNAVAILABLE', |
| 165 | `Gemini does not offer ${model} to this account. Choose another Gemini model, then send this again. OpenTalon did not switch models for you.`) |
| 166 | |
| 167 | // Applies exactly the requested model or throws. A slug such as gemini-4-carbon-high may be |
| 168 | // one listed model, or a listed model plus a listed thinking level. Nothing else matches. |
| 169 | async function selectGeminiModel(transport, session, model) { |
| 170 | if (typeof model !== 'string' || !model) |
| 171 | throw new AppError('AGENT_MODEL_REQUIRED', 'Choose a Gemini model before sending this.') |
| 172 | try { |
| 173 | const models = choice(session, 'model') |
| 174 | if (!models) throw unavailableModel(model) |
| 175 | const listed = (id) => models.entries.some((entry) => entry.id === id) |
| 176 | if (listed(model)) { |
| 177 | await choose(transport, session, 'model', model) |
| 178 | return { model } |
| 179 | } |
| 180 | const [, base, level] = /^(.+)-(low|medium|high|xhigh|max)$/.exec(model) ?? [] |
| 181 | if (!base || !listed(base)) throw unavailableModel(model) |
| 182 | await choose(transport, session, 'model', base) |
| 183 | const thinking = choice(session, 'thought_level')?.entries.find((entry) => |
| 184 | [entry.id, entry.name].some((label) => thinkingLevels[level].includes(String(label).toLowerCase()))) |
| 185 | if (!thinking) throw unavailableModel(model) |
| 186 | await choose(transport, session, 'thought_level', thinking.id) |
| 187 | return { model: base, thinking: thinking.id } |
| 188 | } catch (error) { |
| 189 | if (error instanceof AppError) throw error |
| 190 | throw unavailableModel(model) |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | // True when a later update shows Gemini moved off the model this run selected. |
| 195 | function geminiModelChanged(update, selected) { |
| 196 | if (update?.sessionUpdate !== 'config_option_update' || !Array.isArray(update.configOptions)) return false |
| 197 | const current = (category) => update.configOptions.find((entry) => entry?.category === category)?.currentValue |
| 198 | return (current('model') !== undefined && current('model') !== selected.model) || |
| 199 | (selected.thinking !== undefined && current('thought_level') !== undefined && current('thought_level') !== selected.thinking) |
| 200 | } |
| 201 | |
| 202 | async function selectGeminiMode(transport, session, permissionMode) { |
| 203 | if (permissionMode === 'full-access') return |
| 204 | const modes = choice(session, 'mode') |
| 205 | const offered = (id) => modes?.entries.some((entry) => entry.id === id) |
| 206 | // Without agy's reviewed auto mode, Automatic falls back to asking the owner. |
| 207 | const mode = permissionMode === 'auto' && offered('auto') ? 'auto' : 'default' |
| 208 | if (!offered(mode)) |
| 209 | throw new AppError('AGENT_UNSUPPORTED', 'Gemini did not offer an approval mode OpenTalon can enforce. Update the Antigravity CLI with agy update.') |
| 210 | try { |
| 211 | await choose(transport, session, 'mode', mode) |
| 212 | } catch (error) { |
| 213 | throw new AppError('AGENT_UNSUPPORTED', 'Gemini could not switch to the access mode chosen in Settings.') |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | function permissionOutcome(options, allow) { |
| 218 | const option = (options ?? []).find((entry) => entry?.kind === (allow ? 'allow_once' : 'reject_once')) |
| 219 | return { outcome: option ? { outcome: 'selected', optionId: option.optionId } : { outcome: 'cancelled' } } |
| 220 | } |
| 221 | |
| 222 | function geminiPrompt(text, images, capabilities) { |
| 223 | return [ |
| 224 | { type: 'text', text }, |
| 225 | ...(capabilities.promptCapabilities?.image ? images : []) |
| 226 | .map((image) => ({ type: 'image', data: image.data, mimeType: image.mimeType })), |
| 227 | ] |
| 228 | } |
| 229 | |
| 230 | function geminiStop(result, lastText) { |
| 231 | const reason = result?.stopReason |
| 232 | if (reason === 'end_turn') |
| 233 | return ['review', lastText || 'Gemini finished its response. Review the result before marking the task done.'] |
| 234 | if (reason === 'cancelled') return ['canceled', 'Gemini stopped this turn.'] |
| 235 | if (reason === 'refusal') return ['failed', 'Gemini declined this request.'] |
| 236 | return ['failed', `Gemini stopped before finishing${reason ? ` (${reason.replaceAll('_', ' ')})` : ''}. Review its work before sending again.`] |
| 237 | } |
| 238 | |
| 239 | // One complete Ask my agent turn. Approvals have no owner to answer them here, so every |
| 240 | // request is declined unless the owner chose Full access. |
| 241 | async function geminiChat({ file, cwd, permissionMode, model, config, prompt, signal, spawnTransport, home, timeout = 90_000 }) { |
| 242 | const scopedSettings = geminiScopedSettings(cwd, home) |
| 243 | let text = '' |
| 244 | let declined = 0 |
| 245 | let prompted = false |
| 246 | let answered = false |
| 247 | let session |
| 248 | let transport |
| 249 | let exited |
| 250 | const ended = new Promise((_, reject) => { exited = reject }) |
| 251 | const onMessage = (message) => { |
| 252 | if (message.id !== undefined && message.method) { |
| 253 | if (message.method !== 'session/request_permission') |
| 254 | return transport.write({ id: message.id, error: { code: -32601, message: 'OpenTalon chat does not provide this.' } }) |
| 255 | declined += 1 |
| 256 | return transport.write({ id: message.id, result: permissionOutcome(message.params?.options, false) }) |
| 257 | } |
| 258 | const update = message.params?.update |
| 259 | if (message.method !== 'session/update' || !prompted || message.params.sessionId !== session?.sessionId) return |
| 260 | if (update?.sessionUpdate === 'agent_message_chunk' && update.content?.type === 'text') |
| 261 | text = (text + update.content.text).slice(-16000) |
| 262 | } |
| 263 | transport = spawnTransport(file, geminiArguments(permissionMode, scopedSettings), cwd, onMessage, exited, transportOptions) |
| 264 | const timer = setTimeout(() => exited(new Error('Gemini did not reply in time.')), timeout) |
| 265 | const abort = () => exited(new Error('Stopped.')) |
| 266 | signal?.addEventListener('abort', abort, { once: true }) |
| 267 | try { |
| 268 | return await Promise.race([ended, (async () => { |
| 269 | const capabilities = await geminiInitialize(transport) |
| 270 | session = await geminiSession(transport, capabilities, { cwd, server: geminiToolServer(config) }) |
| 271 | await selectGeminiModel(transport, session, model) |
| 272 | await selectGeminiMode(transport, session, permissionMode) |
| 273 | prompted = true |
| 274 | const result = await transport.request('session/prompt', |
| 275 | { sessionId: session.sessionId, prompt: geminiPrompt(prompt, [], capabilities) }, false, 0) |
| 276 | answered = true |
| 277 | if (declined) |
| 278 | throw new AppError('CHAT_PERMISSION_REQUIRED', 'Gemini asked for an approval that Ask my agent cannot give. Send this as a task, or choose Full access in Settings.') |
| 279 | if (result?.stopReason !== 'end_turn' || !text.trim()) throw new Error(geminiStop(result, '')[1]) |
| 280 | return { text: text.trim() } |
| 281 | })()]) |
| 282 | } catch (error) { |
| 283 | throw geminiFailure(error) |
| 284 | } finally { |
| 285 | clearTimeout(timer) |
| 286 | signal?.removeEventListener('abort', abort) |
| 287 | if (session && !answered) try { transport.write({ method: 'session/cancel', params: { sessionId: session.sessionId } }) } catch {} |
| 288 | transport.close() |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | // Documented print mode: plan mode is read-only and the JSON envelope carries the schema result. |
| 293 | function geminiDraftArguments({ model, schema, prompt }) { |
| 294 | return [ |
| 295 | '--output-format', 'json', '--json-schema', JSON.stringify(schema), '--model', model, |
| 296 | '--mode', 'plan', '--sandbox', '--disable-slash-commands', '--print-timeout', '40s', '--print', prompt, |
| 297 | ] |
| 298 | } |
| 299 | |
| 300 | function geminiDraftResult(stdout) { |
| 301 | let reply |
| 302 | try { reply = JSON.parse(stdout) } catch { throw new Error('Gemini returned an unreadable draft.') } |
| 303 | if (reply.status !== 'SUCCESS' || !reply.structured_output || typeof reply.structured_output !== 'object') |
| 304 | throw geminiFailure(new Error(typeof reply.error === 'string' ? reply.error : reply.error?.message ?? 'Gemini returned no draft.')) |
| 305 | return reply.structured_output |
| 306 | } |
| 307 | |
| 308 | module.exports = { |
| 309 | transportOptions, unsupportedAuthEnvironment, geminiArguments, geminiToolServer, geminiScopedSettings, |
| 310 | geminiFailure, assertGeminiRuntime, geminiInitialize, geminiSession, selectGeminiModel, geminiModelChanged, |
| 311 | selectGeminiMode, permissionOutcome, geminiPrompt, geminiStop, geminiChat, geminiDraftArguments, geminiDraftResult, |
| 312 | } |