diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 664019086ff9..e2c23bdf0590 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -2603,6 +2603,7 @@ "codexSystemNotSignedIn": "Codex isn't signed in. Run `{{loginCommand}}`.", "codexManagedNotSignedIn": "This Codex account isn't signed in. Sign in again in Codex Accounts settings.", "antigravityNotSignedIn": "Antigravity isn't signed in. Sign in under Settings → Accounts → Antigravity. Then send your message again.", + "antigravitySystemNotSignedIn": "Antigravity isn't signed in. Sign in by running `agy` on the computer running this chat, then send your message again.", "agentCommandNotSignedIn": "Sign in to {{agent}} with `{{loginCommand}}` on the computer running this chat.", "interactiveAgentNotSignedIn": "Sign in to {{agent}} by running `{{loginCommand}}` and using `{{slashCommand}}` on the computer running this chat.", "agentNotSignedIn": "Sign in to {{agent}}.", diff --git a/mobile/src/session/agent-session-start-failure-copy.ts b/mobile/src/session/agent-session-start-failure-copy.ts index 41dd368cca68..036264d4a0a8 100644 --- a/mobile/src/session/agent-session-start-failure-copy.ts +++ b/mobile/src/session/agent-session-start-failure-copy.ts @@ -126,6 +126,12 @@ export const START_FAILURE_COPY = { "Antigravity isn't signed in. Sign in under Settings → Accounts → Antigravity. Then send your message again.", values ), + antigravitySystemNotSignedIn: (values) => + translate( + 'session.failure.antigravitySystemNotSignedIn', + "Antigravity isn't signed in. Sign in by running `agy` on the computer running this chat, then send your message again.", + values + ), agentCommandNotSignedIn: (values) => translate( 'session.failure.agentCommandNotSignedIn', diff --git a/src/main/acp/acp-dialects/acp-dialect.ts b/src/main/acp/acp-dialects/acp-dialect.ts index 804b0ab02a2e..e5935a36f902 100644 --- a/src/main/acp/acp-dialects/acp-dialect.ts +++ b/src/main/acp/acp-dialects/acp-dialect.ts @@ -1,3 +1,4 @@ +import type { AgentSessionAccountKind } from '../../../shared/agent-session/agent-session-availability' import type { AgentSessionContextUsage } from '../../../shared/agent-session/agent-session-context-usage' import type { AgentSessionUsageLimit } from '../../../shared/agent-session/failures/agent-session-usage-limit' import type { AgentJournalToolCallItem } from '../../../shared/agent-session/journal/agent-session-journal-types' @@ -165,6 +166,8 @@ export type AcpDialect = { } /** Hide these commands and reject command-only prompts before dispatch. */ withheldCommands?: readonly string[] + /** Which sign-in a not-signed-in chat needs; absent is the agent's usual one. */ + signInAccount?: AgentSessionAccountKind /** Which session rows are the agent's own built-ins, as this process's initialize response proves. */ builtinCommands?(initialized: InitializeResponse): (command: AvailableCommand) => boolean } diff --git a/src/main/acp/acp-launch-command.ts b/src/main/acp/acp-launch-command.ts new file mode 100644 index 000000000000..8902e789a6cc --- /dev/null +++ b/src/main/acp/acp-launch-command.ts @@ -0,0 +1,91 @@ +// Which program an ACP chat runs: its Command setting, Orca's managed release, PATH, or a host backend. + +import { delimiter, isAbsolute } from 'node:path' +import { homedir } from 'node:os' +import type { AgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' +import type { resolveCliCommand } from '../../shared/node-cli-command-resolution' +import { hasExplicitTuiLaunchCommand } from '../../shared/agent-launch/startup/tui-agent-launch-command-override' +import { + resolveStructuredAgentCommand, + type StructuredAgentCommand, + type StructuredAgentCommandSettings +} from '../native-chat/structured-agent-command-resolution' +import { + copyBesidePinnedMembers, + resolveInstalledRuntimeRelease +} from '../node-runtime/managed-runtime-release' +import { STRUCTURED_CHILD_ENV_TO_DELETE } from '../runtime/agent-session/environment/structured-session-child-env' +import type { AcpLaunchSpec } from './acp-launch-specs' + +/** Prefer explicit commands, then managed releases, then complete pinned copies on PATH. */ +export function resolveAcpLaunchCommand( + spec: AcpLaunchSpec, + env: Readonly>, + options: { + commandSettings?: StructuredAgentCommandSettings + resolveCommand?: typeof resolveCliCommand + homePath?: string + dataDirectory: string | null + } +): StructuredAgentCommand { + const homePath = env.HOME ?? env.USERPROFILE ?? options.homePath ?? homedir() + const pathEnv = [env.PATH ?? env.Path, ...spec.installDirectories({ env, homePath })] + .filter((entry): entry is string => Boolean(entry)) + .join(delimiter) + const settings = spec.ignoreAgentCommandSetting ? {} : (options.commandSettings ?? {}) + const resolve = (searchPath: string) => + resolveStructuredAgentCommand( + spec.agent, + settings, + { pathEnv: searchPath, homePath }, + { + command: spec.command, + ...(options.resolveCommand ? { resolve: options.resolveCommand } : {}) + } + ) + const { managedRuntime } = spec + if (!managedRuntime || hasExplicitTuiLaunchCommand(settings, spec.agent)) { + return resolve(pathEnv) + } + const pin = managedRuntime.pin() + const root = options.dataDirectory && managedRuntime.root(options.dataDirectory) + const release = root ? resolveInstalledRuntimeRelease(root, pin).release : null + if (release) { + return resolve(release.folder) + } + const { command } = resolve(pathEnv) + const pinned = command !== spec.command && copyBesidePinnedMembers(command, pin) + return { command: pinned || spec.command, prefixArgs: [] } +} + +/** Chats whose account home a host backend pins launch with its spec. */ +export function acpLaunchSpecForAccount( + spec: AcpLaunchSpec, + home: AgentSessionAccountHome +): AcpLaunchSpec { + return spec.hostBackend?.pins(home) ? spec.hostBackend.spec : spec +} + +/** The account home pinning a new chat to the compatible host program `env` finds, or null. */ +export async function selectAcpHostAccountHome( + spec: AcpLaunchSpec, + shellEnv: Readonly>, + stateDirectory: string, + inherited: NodeJS.ProcessEnv = process.env +): Promise { + const backend = spec.hostBackend + if (!backend) { + return null + } + const env = { ...shellEnv } + const envToDelete = [ + ...STRUCTURED_CHILD_ENV_TO_DELETE, + ...(backend.spec.scrubEnvironment?.(env, inherited) ?? []) + ] + Object.assign(env, backend.spec.env) + const homePath = env.HOME ?? env.USERPROFILE ?? homedir() + const { command } = resolveAcpLaunchCommand(backend.spec, env, { homePath, dataDirectory: null }) + return isAbsolute(command) + ? backend.select({ command, env, envToDelete, homePath, stateDirectory }) + : null +} diff --git a/src/main/acp/acp-launch-specs.ts b/src/main/acp/acp-launch-specs.ts index d11376b2ba3f..80c39d4b3fb8 100644 --- a/src/main/acp/acp-launch-specs.ts +++ b/src/main/acp/acp-launch-specs.ts @@ -1,14 +1,10 @@ -import { - resolveAntigravityChatAuthConfig, - type AntigravityChatAuthConfig -} from '../../shared/antigravity-chat-auth-config' +import type { AntigravityChatAuthConfig } from '../../shared/antigravity-chat-auth-config' import type { AcpHistoryTurnIdentity } from './history/acp-history-replay' import { join } from 'node:path' import type { AcpDialect } from './acp-dialects/acp-dialect' import { GROK_ACP_DIALECT } from './acp-dialects/grok-dialect' import { OMP_ACP_DIALECT } from './acp-dialects/omp-dialect' import { OPENCODE_ACP_DIALECT } from './acp-dialects/opencode-dialect' -import { ANTIGRAVITY_ACP_DIALECT } from './acp-dialects/antigravity-dialect' import { directoryAccountBinding, type AcpAccountBinding } from './acp-account-binding' import { openCodeAcpAccountBinding } from '../opencode/opencode-structured-account-home' import { scrubOpenCodeAcpEnvironment } from '../opencode/opencode-acp-environment' @@ -41,22 +37,10 @@ import { OPENCODE_TRANSCRIPT_IMPORT } from '../opencode/opencode-transcript-impo import { assertOpenCodeCopyUsesLocalStore } from '../../shared/opencode-launch-command' import { OMP_SESSION_HISTORY } from '../omp/omp-session-history' import { OMP_TRANSCRIPT_IMPORT } from '../omp/omp-transcript-import' -import { - ANTIGRAVITY_ACP_COMMAND, - ANTIGRAVITY_ACP_RUNTIME -} from '../antigravity/antigravity-acp-runtime' -import { - ANTIGRAVITY_ACP_ENV, - scrubAntigravityAcpEnvironment -} from '../antigravity/antigravity-acp-environment' -import { - ANTIGRAVITY_LAUNCH_GATE, - answerAntigravityChatAuth, - antigravityChatAccount -} from '../antigravity/antigravity-chat-account' -import { readAntigravitySignInLine } from '../antigravity/antigravity-sign-in-url' import type { AcpSignInWatch } from './acp-agent-connection' import type { AcpLaunchGate } from './acp-launch-gate' +import { ANTIGRAVITY_LAUNCH_SPEC } from '../antigravity/antigravity-acp-launch-spec' +import type { AgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' /** Model discovery never authenticates interactively. */ export type AcpModelDiscovery = @@ -175,6 +159,24 @@ export type AcpLaunchSpec = { /** Prefer session/resume even when loading is supported. */ resumePreference?: 'resume' launchGate?: AcpLaunchGate + /** Writes sessions it cannot delete into the user's own history, so it runs no naming tasks. */ + keepsEverySession?: true + /** A program on the host preferred for new chats; chats whose account home it pins keep it. */ + hostBackend?: AcpHostBackend +} + +export type AcpHostBackend = { + spec: AcpLaunchSpec + pins(home: AgentSessionAccountHome): boolean + /** The account home pinning a new chat to `spec`, or null when the host should not run it. */ + select(input: { + command: string + env: Record + envToDelete: string[] + homePath: string + /** Orca's data folder on this host, where the agent's own account lives. */ + stateDirectory: string + }): Promise } const GROK_LAUNCH_SPEC: AcpLaunchSpec = { @@ -297,51 +299,6 @@ const OMP_LAUNCH_SPEC: AcpLaunchSpec = { sessionHistory: OMP_SESSION_HISTORY } -// agy conversations are separate from the ACP server's and cannot resume these sessions. -const ANTIGRAVITY_SESSION_HISTORY: StructuredAgentSessionHistory = { - rowAgents: ['antigravity'], - rowSessionId: (link) => link.handle.nativeId, - parseResumeArgs: () => null -} - -// The managed ACP server has its own sign-in; agy provides neither ACP nor its account. -export const ANTIGRAVITY_LAUNCH_SPEC = { - agent: 'antigravity', - command: ANTIGRAVITY_ACP_COMMAND, - ignoreAgentCommandSetting: true, - // Without --uid=, the Linux server drops root launches to nobody. - args: () => (process.platform === 'linux' ? ['--uid='] : []), - env: ANTIGRAVITY_ACP_ENV, - scrubEnvironment: scrubAntigravityAcpEnvironment, - dialect: ANTIGRAVITY_ACP_DIALECT, - loginCommand: agentSessionSignInFor('antigravity')?.loginCommand ?? [], - authMethod: ({ antigravityChatAuth }) => - resolveAntigravityChatAuthConfig(antigravityChatAuth).method, - authMethodUnavailableMessage: - 'Antigravity does not support the selected account type. Update Antigravity or change the account type in Settings.', - signIn: { - read: readAntigravitySignInLine, - answered: answerAntigravityChatAuth - }, - account: antigravityChatAccount, - installDirectories: () => [], - managedRuntime: ANTIGRAVITY_ACP_RUNTIME, - // Yolo still requests questions and administrative reviews. - permissionModeConfig: { - values: { ask: 'default', 'accept-edits': 'auto_edit', 'full-access': 'yolo' } - }, - modelDiscovery: { - kind: 'unavailable', - reason: 'the Antigravity server lists its models only in a signed-in session' - }, - transcriptImport: null, - sessionHistory: ANTIGRAVITY_SESSION_HISTORY, - privateTempDirectory: true, - // `session/load` replays the whole conversation, which the chat already holds. - resumePreference: 'resume', - launchGate: ANTIGRAVITY_LAUNCH_GATE -} satisfies AcpLaunchSpec - export const ACP_LAUNCH_SPECS: readonly AcpLaunchSpec[] = [ GROK_LAUNCH_SPEC, OPENCODE_LAUNCH_SPEC, diff --git a/src/main/acp/acp-structured-acquire.ts b/src/main/acp/acp-structured-acquire.ts index 4c2a09f6e9b2..0e339c3ce587 100644 --- a/src/main/acp/acp-structured-acquire.ts +++ b/src/main/acp/acp-structured-acquire.ts @@ -50,15 +50,14 @@ export async function acquireAcpStructuredSession(input: { session: AcpStructuredChild }> { const { acquire, deps, generation } = input - const { spec } = deps - const agentName = acpAgentName(spec.agent) + const agentName = acpAgentName(deps.spec.agent) const logger = deps.logger ?? createStructuredAgentSessionLogger() const sessionId = acquire.identity.sessionId const now = deps.now ?? Date.now const events = acquire.events const sink = events ? providerTimelineSink(events) : null if (!sink) { - throw new AgentSessionPreSpawnError(new Error(`${spec.agent} chats need a journal sink`)) + throw new AgentSessionPreSpawnError(new Error(`${deps.spec.agent} chats need a journal sink`)) } const closedBeforeSpawn = () => { if (input.abandoned()) { @@ -67,6 +66,8 @@ export async function acquireAcpStructuredSession(input: { } closedBeforeSpawn() const launch = await prepareAcpStructuredLaunch(deps, acquire, closedBeforeSpawn) + // The chat's account home pins its backend. + const { spec } = launch let session: AcpStructuredChild | null = null // Use a slot so closure writes do not conflict with control-flow narrowing. const slot: { @@ -74,7 +75,7 @@ export async function acquireAcpStructuredSession(input: { reattaching: boolean history: AcpLoadHistory | null } = { lane: null, reattaching: false, history: null } - const options = new AcpStructuredOptions(launch.spec.dialect) + const options = new AcpStructuredOptions(spec.dialect) const prompts = new AcpStructuredPrompts( () => slot.lane, () => isAcpReadySession(session) && session.turns?.acceptsRequests === true diff --git a/src/main/acp/acp-structured-agent-definitions.ts b/src/main/acp/acp-structured-agent-definitions.ts index 7fba806d18a7..39b8110ad6ad 100644 --- a/src/main/acp/acp-structured-agent-definitions.ts +++ b/src/main/acp/acp-structured-agent-definitions.ts @@ -16,7 +16,7 @@ export function isAcpStructuredOptionKey(key: string): boolean { } export function acpStructuredAgentDefinition(spec: AcpLaunchSpec): StructuredAgentDefinition { - const { managedRuntime } = spec + const { managedRuntime, hostBackend } = spec return { agent: spec.agent, handleTransport: ACP_HANDLE_TRANSPORT, @@ -38,6 +38,7 @@ export function acpStructuredAgentDefinition(spec: AcpLaunchSpec): StructuredAge approvalEnforcement: 'orca' }, ...(managedRuntime && { managedRuntime: () => managedRuntime.pin() !== null }), + ...(hostBackend && { runsHostProgram: (home) => hostBackend.pins(home) }), restingOptions: { acceptsKey: isAcpStructuredOptionKey, // Populate catalogs from live agents. diff --git a/src/main/acp/acp-structured-handshake.ts b/src/main/acp/acp-structured-handshake.ts index ff458f67aebe..4410a9ddc2ef 100644 --- a/src/main/acp/acp-structured-handshake.ts +++ b/src/main/acp/acp-structured-handshake.ts @@ -55,7 +55,7 @@ export async function initializeAcpStructuredSession( input: AcpHandshakeInput ): Promise { const { acquire, deps, launch, connection, options, prompts, child, onSettled } = input - const { spec } = deps + const { spec } = launch const sessionId = acquire.identity.sessionId const now = deps.now ?? Date.now const assertStarting = () => assertAcpStartingSession(child, input.abandoned) @@ -152,7 +152,11 @@ export async function initializeAcpStructuredSession( const mode = spec.permissionModeConfig if (mode && acquire.permissionMode !== 'own') { // Fail startup rather than silently use a different permission mode. - const requested = mode.values[acquire.permissionMode ?? 'ask'] ?? mode.values.ask + const wanted = acquire.permissionMode ?? 'ask' + const requested = mode.values[wanted] + if (requested === undefined) { + throw new Error(`${agentName} on this host cannot run in the ${wanted} permission mode`) + } const configId = options.modeConfigId() await connection.setConfigOption(configId, requested, undefined, ({ configOptions }) => { assertStarting() diff --git a/src/main/acp/acp-structured-host.test-support.ts b/src/main/acp/acp-structured-host.test-support.ts index d4f2fa4bc9f5..aaacbff196b4 100644 --- a/src/main/acp/acp-structured-host.test-support.ts +++ b/src/main/acp/acp-structured-host.test-support.ts @@ -217,7 +217,7 @@ export async function openAttachedHostRig( }) script?.(agent) }, - deps: { resolveLaunch: launch(() => resumed), ...adapterDeps } + deps: { resolveLaunch: launch(() => resumed, adapterDeps.spec), ...adapterDeps } }) expect(await rig.host.attach(CALLER, attachParams())).toMatchObject({ ok: true }) await rig.ready() diff --git a/src/main/acp/acp-structured-launch-preparation.ts b/src/main/acp/acp-structured-launch-preparation.ts index c394cafa74ca..9fba5d79a737 100644 --- a/src/main/acp/acp-structured-launch-preparation.ts +++ b/src/main/acp/acp-structured-launch-preparation.ts @@ -9,9 +9,10 @@ import type { StructuredAgentSessionAcquireInput } from '../native-chat/agent-se import type { AntigravityChatAuthConfig } from '../../shared/antigravity-chat-auth-config' import type { AcpStructuredLaunch } from './acp-structured-launch-resolution' import type { AcpStructuredSessionAdapterDeps } from './acp-structured-session-adapter-deps' +import type { AcpLaunchSpec } from './acp-launch-specs' export function prepareAcpStructuredLaunch( - deps: Pick, + deps: Pick, acquire: Pick, closedBeforeSpawn: () => void ): Promise { @@ -21,26 +22,24 @@ export function prepareAcpStructuredLaunch( spawnToken: acquire.spawnToken, ...(acquire.permissionMode ? { permissionMode: acquire.permissionMode } : {}) }) - return prepareAcpLaunch(deps, resolveLaunch, closedBeforeSpawn) + return prepareAcpLaunch(resolveLaunch, closedBeforeSpawn) } +/** Prepares the backend the launch resolved to, which the chat's account home pins. */ export async function prepareAcpLaunch< Launch extends { command: string env: Record + spec: AcpLaunchSpec antigravityChatAuth?: AntigravityChatAuthConfig } ->( - deps: Pick, - resolve: () => Promise, - closedBeforeSpawn: () => void -): Promise { - const { spec } = deps +>(resolve: () => Promise, closedBeforeSpawn: () => void): Promise { const preparationFailure = (error: unknown): never => { closedBeforeSpawn() throw launchPreparationFailure(error) } const launch = await resolve().catch(preparationFailure) + const { spec } = launch closedBeforeSpawn() // Only a missed lookup returns the bare command; explicit Command settings resolve or fail. if (spec.managedRuntime && launch.command === spec.command) { diff --git a/src/main/acp/acp-structured-launch-resolution.ts b/src/main/acp/acp-structured-launch-resolution.ts index 58f98d591e9f..1d4d835dbb7f 100644 --- a/src/main/acp/acp-structured-launch-resolution.ts +++ b/src/main/acp/acp-structured-launch-resolution.ts @@ -3,7 +3,6 @@ export { checkAcpLaunchVersion } from './acp-launch-version' import { assertStructuredAgentResolutionCurrent, resolveAgainAfterRefreshOnMissingProgram, - resolveStructuredAgentCommand, type StructuredAgentCommand, type StructuredAgentCommandSettings, type StructuredAgentResolutionOperation @@ -16,19 +15,12 @@ import { } from '../../shared/antigravity-chat-auth-config' import type { GlobalSettings } from '../../shared/global-settings-types' import { assertAntigravityChatAuthPublished } from '../antigravity/antigravity-chat-auth-publication' -import { delimiter } from 'node:path' -import { homedir } from 'node:os' import { agentSessionProviderHandleChainHead } from '../../shared/agent-session/lifecycle/agent-session-provider-handle' import { agentSessionProviderHandleKey } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' import type { AgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' import type { resolveCliCommand } from '../../shared/node-cli-command-resolution' import type { AgentCliVersionReader } from '../agent-launch/preflight/agent-cli-version-probe' import { AgentCliInstallationError } from '../native-chat/agent-cli-installation-error' -import { - copyBesidePinnedMembers, - resolveInstalledRuntimeRelease -} from '../node-runtime/managed-runtime-release' -import { hasExplicitTuiLaunchCommand } from '../../shared/agent-launch/startup/tui-agent-launch-command-override' import type { JournalLoad } from '../native-chat/agent-session-journal/replay/journal-open' import type { StructuredAgentLaunchPartResolver } from '../runtime/agent-session/launch/structured-agent-launch-composition' import { STRUCTURED_CHILD_ENV_TO_DELETE } from '../runtime/agent-session/environment/structured-session-child-env' @@ -38,6 +30,7 @@ import { withNativeChatVisualsEnv } from '../native-chat/native-chat-visuals-delivery' import type { AcpLaunchSpec } from './acp-launch-specs' +import { acpLaunchSpecForAccount, resolveAcpLaunchCommand } from './acp-launch-command' import { nothingExchangedOn } from './acp-structured-resume-history' import { acpUnannouncedLosses } from './acp-session-reopen-failure' import { loadAcpVisualsSkill, type AcpLaunchVisualsDeps } from './acp-structured-launch-visuals' @@ -92,53 +85,14 @@ export type AcpLaunchInvocationDeps = { 'resolveCommand' | 'homePath' | 'inheritedEnv' | 'dataDirectory' > +/** What a launch runs, and the spec of the backend the account home pins. */ export type AcpLaunchInvocation = StructuredAgentCommand & { env: Record envToDelete: string[] + spec: AcpLaunchSpec antigravityChatAuth?: AntigravityChatAuthConfig } -/** Prefer explicit commands, then managed releases, then complete pinned copies on PATH. */ -export function resolveAcpLaunchCommand( - spec: AcpLaunchSpec, - env: Readonly>, - options: { - commandSettings?: StructuredAgentCommandSettings - resolveCommand?: typeof resolveCliCommand - homePath?: string - dataDirectory: string | null - } -): StructuredAgentCommand { - const homePath = env.HOME ?? env.USERPROFILE ?? options.homePath ?? homedir() - const pathEnv = [env.PATH ?? env.Path, ...spec.installDirectories({ env, homePath })] - .filter((entry): entry is string => Boolean(entry)) - .join(delimiter) - const settings = spec.ignoreAgentCommandSetting ? {} : (options.commandSettings ?? {}) - const resolve = (searchPath: string) => - resolveStructuredAgentCommand( - spec.agent, - settings, - { pathEnv: searchPath, homePath }, - { - command: spec.command, - ...(options.resolveCommand ? { resolve: options.resolveCommand } : {}) - } - ) - const { managedRuntime } = spec - if (!managedRuntime || hasExplicitTuiLaunchCommand(settings, spec.agent)) { - return resolve(pathEnv) - } - const pin = managedRuntime.pin() - const root = options.dataDirectory && managedRuntime.root(options.dataDirectory) - const release = root ? resolveInstalledRuntimeRelease(root, pin).release : null - if (release) { - return resolve(release.folder) - } - const { command } = resolve(pathEnv) - const pinned = command !== spec.command && copyBesidePinnedMembers(command, pin) - return { command: pinned || spec.command, prefixArgs: [] } -} - /** Resolve chats and probes consistently; optionally refresh once after a missing-program lookup. */ export function resolveAcpLaunchInvocation( spec: AcpLaunchSpec, @@ -154,10 +108,11 @@ export function resolveAcpLaunchInvocation( } async function readAcpLaunchInvocation( - spec: AcpLaunchSpec, + agentSpec: AcpLaunchSpec, accountHome: AgentSessionAccountHome, deps: AcpLaunchInvocationDeps ): Promise { + const spec = acpLaunchSpecForAccount(agentSpec, accountHome) assertStructuredAgentResolutionCurrent(deps.operation) const base = await deps.resolveEnvironment() assertStructuredAgentResolutionCurrent(deps.operation) @@ -168,30 +123,32 @@ async function readAcpLaunchInvocation( const envToDelete = spec.scrubEnvironment?.(env, deps.inheritedEnv ?? process.env) ?? [] Object.assign(env, spec.env) const commandSettings = deps.resolveCommandSettings?.() - if (spec.agent === 'antigravity') { + // Orca's account-type setting selects only the managed server's sign-in. + const usesChatAuth = spec.agent === 'antigravity' && spec.authMethod !== undefined + if (usesChatAuth) { assertAntigravityChatAuthPublished(commandSettings?.antigravityChatAuth) } - const antigravityChatAuth = - spec.agent === 'antigravity' - ? resolveAntigravityChatAuthConfig(commandSettings?.antigravityChatAuth) - : undefined + const antigravityChatAuth = usesChatAuth + ? resolveAntigravityChatAuthConfig(commandSettings?.antigravityChatAuth) + : undefined const invocation = resolveAcpLaunchCommand(spec, env, { ...deps, commandSettings }) return { ...invocation, env, envToDelete, + spec, ...(antigravityChatAuth ? { antigravityChatAuth } : {}) } } export function acpStructuredLaunchPart( - spec: AcpLaunchSpec, + agentSpec: AcpLaunchSpec, deps: AcpStructuredLaunchPartDeps ): StructuredAgentLaunchPartResolver { return async (basis, identity) => { const { record } = basis - const { env, envToDelete, command, prefixArgs, antigravityChatAuth } = - await resolveAcpLaunchInvocation(spec, record.accountHome, { + const { env, envToDelete, command, prefixArgs, spec, antigravityChatAuth } = + await resolveAcpLaunchInvocation(agentSpec, record.accountHome, { resolveEnvironment: basis.baseEnvironment, resolveLaunchEnv: () => basis.launchEnv(), resolveCommandSettings: basis.commandSettings, diff --git a/src/main/acp/acp-structured-session-adapter.ts b/src/main/acp/acp-structured-session-adapter.ts index bca99f3897b5..c424a1a62a3e 100644 --- a/src/main/acp/acp-structured-session-adapter.ts +++ b/src/main/acp/acp-structured-session-adapter.ts @@ -272,8 +272,10 @@ export class AcpStructuredSessionAdapter implements SessionAdapter { canSetOptionWhileIdle = (input: SetOptionInput): boolean => childState.canSetAcpOptionWhileIdle(this.children.sessions.get(input.sessionId), input) - readOptions = async (input: { sessionId: string; fence: number }) => - readAcpLiveOptions(this.live(input.sessionId), this.deps.spec.permissionModeConfig?.values) + readOptions = async (input: { sessionId: string; fence: number }) => { + const session = this.live(input.sessionId) + return readAcpLiveOptions(session, session.spec.permissionModeConfig?.values) + } readCommands = (sessionId: string) => { const session = this.children.sessions.get(sessionId) diff --git a/src/main/acp/acp-structured-start-open.ts b/src/main/acp/acp-structured-start-open.ts index 480d5d2db02d..af277cb5ee01 100644 --- a/src/main/acp/acp-structured-start-open.ts +++ b/src/main/acp/acp-structured-start-open.ts @@ -34,7 +34,8 @@ export async function openAcpStart( } const refusal = new AgentSessionAcquisitionRefusal( `${acpAgentName(child.spec.agent)} requires sign-in`, - 'notSignedIn' + 'notSignedIn', + failure.account ) throw failure.detail ? withProviderDiagnostic(refusal, failure.detail) : refusal }) diff --git a/src/main/acp/acp-text-task.ts b/src/main/acp/acp-text-task.ts index 064a82ebeb39..48cdf2939f17 100644 --- a/src/main/acp/acp-text-task.ts +++ b/src/main/acp/acp-text-task.ts @@ -9,6 +9,7 @@ import { ProviderAcquisitionStarts } from '../provider-process/provider-acquisit import { removeAntigravitySignInSessionFiles } from '../antigravity/antigravity-sign-in-session-files' import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from '../text-generation/source-control-generation-limits' import { resolveAcpLaunchInvocation } from './acp-structured-launch-resolution' +import { acpLaunchSpecForAccount } from './acp-launch-command' import { prepareAcpLaunch } from './acp-structured-launch-preparation' import { acpPrivateTempConnect } from './acp-private-temp' import { @@ -117,9 +118,12 @@ export class AcpTextTasks { if (!invocation) { throw new Error('Native text task launch is unavailable') } + // A naming session would stay in the user's own agent history. + if (acpLaunchSpecForAccount(spec, input.accountHome).keepsEverySession) { + return null + } const launch = await waitForPromiseWithSignal( prepareAcpLaunch( - this.deps, () => resolveAcpLaunchInvocation(spec, input.accountHome, invocation), () => signal.throwIfAborted() ), @@ -154,12 +158,8 @@ export class AcpTextTasks { { clientInfo: { name: 'orca-chat-naming', version: '1' }, signIn: spec.signIn, - onPermission: (request) => { - if (spec.agent !== 'antigravity') { - return reject() - } - return denyAcpTextTaskPermission(request) - }, + onPermission: (request) => + spec.agent === 'antigravity' ? denyAcpTextTaskPermission(request) : reject(), onRequest: reject, onExtensionNotification: notification } diff --git a/src/main/acp/acp-turn-failures.ts b/src/main/acp/acp-turn-failures.ts index 30cbf3bfcdff..a9402166aa3b 100644 --- a/src/main/acp/acp-turn-failures.ts +++ b/src/main/acp/acp-turn-failures.ts @@ -124,7 +124,10 @@ export function acpSignInRequiredFailure( error: AcpAgentError ): SubmissionRejectionFact { const detail = providerDiagnostic(acpPromptErrorDetail(dialect, error), 'person') - return agentSessionFailureFact('notSignedIn', detail ? { detail } : {}) + return agentSessionFailureFact('notSignedIn', { + ...(detail ? { detail } : {}), + ...(dialect.signInAccount ? { account: dialect.signInAccount } : {}) + }) } /** Why the agent refused a prompt, as the person is told; a missing model outranks its sign-in wording. */ @@ -206,7 +209,10 @@ export class AcpTurnFailures { } this.rows.set(turn, evidence) const failure = authenticationRequired - ? agentSessionFailureFact('notSignedIn', { detail: diagnostic }) + ? agentSessionFailureFact('notSignedIn', { + detail: diagnostic, + ...(this.dialect.signInAccount ? { account: this.dialect.signInAccount } : {}) + }) : evidence.modelNotSelected ? agentSessionFailureFact('modelNotSelected') : usageLimited diff --git a/src/main/antigravity/antigravity-acp-launch-spec.ts b/src/main/antigravity/antigravity-acp-launch-spec.ts new file mode 100644 index 000000000000..e265aaaabc78 --- /dev/null +++ b/src/main/antigravity/antigravity-acp-launch-spec.ts @@ -0,0 +1,129 @@ +// Antigravity chats run Orca's managed ACP server, or the host's own `agy acp` when compatible. + +import { join } from 'node:path' +import { homedir } from 'node:os' +import type { AcpLaunchSpec } from '../acp/acp-launch-specs' +import { ANTIGRAVITY_ACP_DIALECT } from '../acp/acp-dialects/antigravity-dialect' +import type { StructuredAgentSessionHistory } from '../native-chat/structured-agent-cli-conversations' +import { resolveAntigravityChatAuthConfig } from '../../shared/antigravity-chat-auth-config' +import { agentSessionSignInFor } from '../../shared/agent-session/lifecycle/agent-session-sign-in' +import { ANTIGRAVITY_ACP_COMMAND, ANTIGRAVITY_ACP_RUNTIME } from './antigravity-acp-runtime' +import { ANTIGRAVITY_ACP_ENV, scrubAntigravityAcpEnvironment } from './antigravity-acp-environment' +import { + ANTIGRAVITY_LAUNCH_GATE, + answerAntigravityChatAuth, + antigravityChatAccount, + antigravityChatSignIn +} from './antigravity-chat-account' +import { ANTIGRAVITY_CHAT_HOME_FOLDER } from './antigravity-chat-home' +import { readAntigravitySignInLine } from './antigravity-sign-in-url' +import { + ANTIGRAVITY_HOST_ACP_MINIMUM_VERSION, + antigravityHostAccountHome, + antigravityHostAcpAnswers, + hasAgyCredential, + hasManagedAntigravityChatSignIn, + isAntigravityHostAccountHome +} from './antigravity-host-acp' + +// Chats cannot adopt agy's terminal conversations. +const ANTIGRAVITY_SESSION_HISTORY: StructuredAgentSessionHistory = { + rowAgents: ['antigravity'], + rowSessionId: (link) => link.handle.nativeId, + parseResumeArgs: () => null +} + +// Orca's managed ACP server keeps its own sign-in under /antigravity-chat. +const ANTIGRAVITY_MANAGED_LAUNCH_SPEC = { + agent: 'antigravity', + command: ANTIGRAVITY_ACP_COMMAND, + ignoreAgentCommandSetting: true, + // Without --uid=, the Linux server drops root launches to nobody. + args: () => (process.platform === 'linux' ? ['--uid='] : []), + env: ANTIGRAVITY_ACP_ENV, + scrubEnvironment: scrubAntigravityAcpEnvironment, + dialect: ANTIGRAVITY_ACP_DIALECT, + loginCommand: agentSessionSignInFor('antigravity')?.loginCommand ?? [], + authMethod: ({ antigravityChatAuth }) => + resolveAntigravityChatAuthConfig(antigravityChatAuth).method, + authMethodUnavailableMessage: + 'Antigravity does not support the selected account type. Update Antigravity or change the account type in Settings.', + signIn: { + read: readAntigravitySignInLine, + answered: answerAntigravityChatAuth + }, + account: antigravityChatAccount, + installDirectories: () => [], + managedRuntime: ANTIGRAVITY_ACP_RUNTIME, + // Yolo still requests questions and administrative reviews. + permissionModeConfig: { + values: { ask: 'default', 'accept-edits': 'auto_edit', 'full-access': 'yolo' } + }, + modelDiscovery: { + kind: 'unavailable', + reason: 'the Antigravity server lists its models only in a signed-in session' + }, + transcriptImport: null, + sessionHistory: ANTIGRAVITY_SESSION_HISTORY, + privateTempDirectory: true, + // `session/load` replays the whole conversation, which the chat already holds. + resumePreference: 'resume', + launchGate: ANTIGRAVITY_LAUNCH_GATE +} satisfies AcpLaunchSpec + +// An inherited Gemini API key switches agy to key auth, which its models reject (401). +function scrubAgyHostApiKeys(env: Record): string[] { + const removed = ['GEMINI_API_KEY', 'GOOGLE_API_KEY'] + for (const key of removed) { + delete env[key] + } + return removed +} + +// The host's `agy acp` uses agy's own sign-in and history; Orca neither signs it in nor out. +const ANTIGRAVITY_HOST_LAUNCH_SPEC: AcpLaunchSpec = { + ...ANTIGRAVITY_MANAGED_LAUNCH_SPEC, + command: 'agy', + args: () => ['acp'], + env: {}, + scrubEnvironment: scrubAgyHostApiKeys, + authMethod: undefined, + authMethodUnavailableMessage: undefined, + signIn: undefined, + dialect: { ...ANTIGRAVITY_ACP_DIALECT, signInAccount: 'system' }, + account: { + pin: antigravityChatAccount.pin, + resolve: async ({ launchEnv }) => + antigravityHostAccountHome(launchEnv.HOME ?? launchEnv.USERPROFILE ?? homedir()), + environment: (home, env) => { + if (!isAntigravityHostAccountHome(home)) { + throw new Error("this chat runs on the host's agy") + } + return env + } + }, + minimumVersions: [ANTIGRAVITY_HOST_ACP_MINIMUM_VERSION], + installDirectories: ({ homePath }) => [join(homePath, '.local', 'bin')], + managedRuntime: undefined, + // agy has no full-access mode: such chats start on Orca's runtime, and a switch fails the start. + permissionModeConfig: { values: { ask: 'default', 'accept-edits': 'accept-edits' } }, + keepsEverySession: true +} + +export const ANTIGRAVITY_LAUNCH_SPEC = { + ...ANTIGRAVITY_MANAGED_LAUNCH_SPEC, + hostBackend: { + spec: ANTIGRAVITY_HOST_LAUNCH_SPEC, + pins: isAntigravityHostAccountHome, + // Someone signed in to Orca's own Chat keeps it; the host's agy needs its own sign-in. + select: async ({ command, env, envToDelete, homePath, stateDirectory }) => + antigravityChatSignIn.get().value.auth !== 'signedIn' && + !(await hasManagedAntigravityChatSignIn( + join(stateDirectory, ANTIGRAVITY_CHAT_HOME_FOLDER) + )) && + (await hasAgyCredential(homePath)) && + (await antigravityHostAcpAnswers(command, env, envToDelete)) + ? antigravityHostAccountHome(homePath) + : null + } +} satisfies AcpLaunchSpec diff --git a/src/main/antigravity/antigravity-acp-runtime-probe.ts b/src/main/antigravity/antigravity-acp-runtime-probe.ts index 1d0b7a4071eb..41755ba4208a 100644 --- a/src/main/antigravity/antigravity-acp-runtime-probe.ts +++ b/src/main/antigravity/antigravity-acp-runtime-probe.ts @@ -23,42 +23,70 @@ function isPinnedServer(initialized: InitializeResponse, version: string): boole ) } +type ProbeLaunch = { + command: string + args: string[] + env: Record + envToDelete: string[] +} + +/** Initializes from a disposable folder; rejects unless the server's exit is proven afterwards. */ +export async function initializeAntigravityAcp( + launch: (folder: string) => ProbeLaunch, + timeoutMs: number, + signal?: AbortSignal +): Promise { + // Keep the server's working folder, and any home inside it, together for cleanup. + const folder = await mkdtemp(join(tmpdir(), 'orca-antigravity-probe-')) + const probe: { connection?: AcpAgentConnection } = {} + let initialized: InitializeResponse | null = null + let failure: unknown = null + try { + initialized = await runAgentModelCatalogSession( + () => { + probe.connection = createAcpAgentConnection({ ...launch(folder), cwd: folder }) + return probe.connection + }, + (started) => started.initialize(), + { label: 'Antigravity', timeoutMs, ...(signal ? { signal } : {}) } + ) + } catch (error) { + failure = error + } + if (probe.connection && !probe.connection.exited) { + failure = new Error('Its exit was not proven after the check') + } + await rm(folder, { recursive: true, force: true }) + if (failure !== null || !initialized) { + throw failure + } + return initialized +} + /** Require the pinned initialize response and proven exit before accepting an installation. */ export async function probeAntigravityAcpServer( command: string, version: string, signal: AbortSignal ): Promise { - // Keep the server’s home and extracted runtime together for cleanup. - const home = await mkdtemp(join(tmpdir(), 'orca-antigravity-probe-')) - const probe: { connection?: AcpAgentConnection } = {} - let answer: unknown = null + let failure: unknown = null try { - const initialized = await runAgentModelCatalogSession( - () => { - probe.connection = createAcpAgentConnection({ - command, - args: process.platform === 'linux' ? ['--uid='] : [], - cwd: home, - env: { ...ANTIGRAVITY_ACP_ENV, GEMINI_HOME: home, TMPDIR: home, TEMP: home, TMP: home }, - envToDelete: scrubAntigravityAcpEnvironment({}, process.env) - }) - return probe.connection - }, - (started) => started.initialize(), - { label: 'Antigravity', timeoutMs: PROBE_TIMEOUT_MS, signal } + const initialized = await initializeAntigravityAcp( + (home) => ({ + command, + args: process.platform === 'linux' ? ['--uid='] : [], + env: { ...ANTIGRAVITY_ACP_ENV, GEMINI_HOME: home, TMPDIR: home, TEMP: home, TMP: home }, + envToDelete: scrubAntigravityAcpEnvironment({}, process.env) + }), + PROBE_TIMEOUT_MS, + signal ) if (!isPinnedServer(initialized, version)) { - answer = new Error(`It did not answer as Antigravity ${version}`) + failure = new Error(`It did not answer as Antigravity ${version}`) } } catch (error) { - answer = error + failure = error } - const failure = - probe.connection && !probe.connection.exited - ? new Error('Its exit was not proven after the check') - : answer - await rm(home, { recursive: true, force: true }) if (failure !== null) { throw new Error('Antigravity could not start on this host.', { cause: failure }) } diff --git a/src/main/antigravity/antigravity-chat-auth-publication.test.ts b/src/main/antigravity/antigravity-chat-auth-publication.test.ts index 74db8a4e5877..6638ff4e4f9c 100644 --- a/src/main/antigravity/antigravity-chat-auth-publication.test.ts +++ b/src/main/antigravity/antigravity-chat-auth-publication.test.ts @@ -7,7 +7,7 @@ import { ProfileStateWriterError } from '../persistence/profile-state/profile-st import { structuredAgentHostLaunchSources } from '../runtime/agent-session/launch/structured-agent-launch-support' import * as profileStorage from '../orca-profiles/profile-storage-paths' import { resolveAcpLaunchInvocation } from '../acp/acp-structured-launch-resolution' -import { ANTIGRAVITY_LAUNCH_SPEC } from '../acp/acp-launch-specs' +import { ANTIGRAVITY_LAUNCH_SPEC } from './antigravity-acp-launch-spec' import { applyAntigravityChatAuthConfig, readAntigravityChatAuthConfig diff --git a/src/main/antigravity/antigravity-chat-auth-settings.test.ts b/src/main/antigravity/antigravity-chat-auth-settings.test.ts index 7d361ee55de5..7c875e4c718b 100644 --- a/src/main/antigravity/antigravity-chat-auth-settings.test.ts +++ b/src/main/antigravity/antigravity-chat-auth-settings.test.ts @@ -6,7 +6,7 @@ import { afterEach, expect, it, vi } from 'vitest' import { getDefaultSettings } from '../../shared/constants' import { resolveAntigravityChatAuthConfig } from '../../shared/antigravity-chat-auth-config' import { resolveAcpLaunchInvocation } from '../acp/acp-structured-launch-resolution' -import { ANTIGRAVITY_LAUNCH_SPEC } from '../acp/acp-launch-specs' +import { ANTIGRAVITY_LAUNCH_SPEC } from './antigravity-acp-launch-spec' import { agentModelCatalogStore } from '../native-chat/agent-model-catalog/agent-model-catalog-store' import { ANTIGRAVITY_LAUNCH_GATE, diff --git a/src/main/antigravity/antigravity-chat-sign-in.test.ts b/src/main/antigravity/antigravity-chat-sign-in.test.ts index f1c51e46653e..45e578e5e533 100644 --- a/src/main/antigravity/antigravity-chat-sign-in.test.ts +++ b/src/main/antigravity/antigravity-chat-sign-in.test.ts @@ -13,7 +13,7 @@ import { z } from 'zod' import { createFakePipedChild } from '../../shared/__fixtures__/fake-spawned-child' import type { terminateProviderProcessTree } from '../provider-process/provider-process-teardown' import { createAcpAgentConnection, type AcpAgentConnection } from '../acp/acp-agent-connection' -import { ANTIGRAVITY_LAUNCH_SPEC } from '../acp/acp-launch-specs' +import { ANTIGRAVITY_LAUNCH_SPEC } from './antigravity-acp-launch-spec' import { agentModelCatalogFingerprint } from '../native-chat/agent-model-catalog/agent-model-catalog-fingerprint' import { agentModelCatalogStore } from '../native-chat/agent-model-catalog/agent-model-catalog-store' import { prepareAcpStructuredLaunch } from '../acp/acp-structured-launch-preparation' @@ -418,7 +418,6 @@ it('retains an unclosed sign-in child for both launch entry points until its exi const prepareChat = async () => prepareAcpStructuredLaunch( { - spec: ANTIGRAVITY_LAUNCH_SPEC, resolveLaunch: async () => ({ ...launch, prefixArgs: [], diff --git a/src/main/antigravity/antigravity-chat-sign-in.ts b/src/main/antigravity/antigravity-chat-sign-in.ts index 124c0b81605b..b6857ffa6189 100644 --- a/src/main/antigravity/antigravity-chat-sign-in.ts +++ b/src/main/antigravity/antigravity-chat-sign-in.ts @@ -7,7 +7,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as accountTypes from '../../shared/antigravity-account-types' import { createAcpAgentConnection, type AcpAgentConnection } from '../acp/acp-agent-connection' -import { ANTIGRAVITY_LAUNCH_SPEC, type AcpLaunchSpec } from '../acp/acp-launch-specs' +import { ANTIGRAVITY_LAUNCH_SPEC } from './antigravity-acp-launch-spec' import { acpPrivateTempConnect } from '../acp/acp-private-temp' import type { ConnectAcpAgent } from '../acp/acp-structured-connection' import { @@ -158,7 +158,7 @@ async function runFlow(current: Flow, host: AntigravityChatSignInHost): Promise< } async function signIn(current: Flow, host: AntigravityChatSignInHost): Promise { - const spec: AcpLaunchSpec = ANTIGRAVITY_LAUNCH_SPEC + const spec = ANTIGRAVITY_LAUNCH_SPEC const { signal } = current.ended const closed = (): void => signal.throwIfAborted() const publishModels = captureSignInModelPublisher( @@ -174,7 +174,7 @@ async function signIn(current: Flow, host: AntigravityChatSignInHost): Promise receiveLink(current, link) } diff --git a/src/main/antigravity/antigravity-host-acp.test.ts b/src/main/antigravity/antigravity-host-acp.test.ts new file mode 100644 index 000000000000..58aeb4fcd433 --- /dev/null +++ b/src/main/antigravity/antigravity-host-acp.test.ts @@ -0,0 +1,125 @@ +import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { selectAcpHostAccountHome } from '../acp/acp-launch-command' +import { resolveAcpLaunchInvocation } from '../acp/acp-structured-launch-resolution' +import { ANTIGRAVITY_LAUNCH_SPEC } from './antigravity-acp-launch-spec' + +// agy's own sign-in, read from the host's keyring or token file. +const agyCredential = vi.hoisted(() => ({ present: true })) +vi.mock('./native-credential-backend', () => ({ + createAntigravityHostCredentialBackend: () => ({ + read: async () => (agyCredential.present ? { contents: '{}' } : null), + write: async () => {} + }), + isAntigravityFileStorageHost: () => false +})) +vi.mock('./native-macos-credentials', () => ({ + hasAntigravityMacOSCredential: async () => agyCredential.present +})) + +// Trimmed from `agy acp` 1.5.2's initialize response. +const HOST_INITIALIZE = { + protocolVersion: 1, + agentCapabilities: { + loadSession: true, + sessionCapabilities: { resume: {}, close: {}, load: {}, list: {} }, + auth: { logout: {} } + }, + agentInfo: { name: 'Antigravity ACP Server', version: '1.5.2' }, + authMethods: [{ id: 'oauth-personal', name: 'Log in with Google' }] +} + +const folders: string[] = [] +afterEach(async () => { + vi.unstubAllEnvs() + await Promise.all(folders.splice(0).map((f) => rm(f, { recursive: true, force: true }))) +}) + +/** A PATH folder whose `agy acp` answers initialize with `result`. */ +async function fakeAgy(result: unknown): Promise { + const folder = await mkdtemp(join(tmpdir(), 'orca-agy-host-test-')) + folders.push(folder) + const agy = join(folder, 'agy') + await writeFile( + agy, + `#!${process.execPath} +if (process.argv[2] !== 'acp') process.exit(2) +const result = ${JSON.stringify(result)} +require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => { + const { id, method } = JSON.parse(line) + if (method === 'initialize') process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\\n') +}) +` + ) + await chmod(agy, 0o755) + return folder +} + +it.skipIf(process.platform === 'win32')( + "new chats pin the host's agy only when it is compatible, signed in, and Orca's Chat is not", + async () => { + vi.stubEnv('ELECTRON_RUN_AS_NODE', '1') + const stateDirectory = await mkdtemp(join(tmpdir(), 'orca-agy-state-test-')) + folders.push(stateDirectory) + const select = async (result: unknown) => + selectAcpHostAccountHome( + ANTIGRAVITY_LAUNCH_SPEC, + { PATH: await fakeAgy(result), HOME: '/home/user' }, + stateDirectory + ) + await expect(select(HOST_INITIALIZE)).resolves.toEqual({ + variable: 'GEMINI_HOME', + path: '/home/user/.gemini' + }) + const older = { + ...HOST_INITIALIZE, + agentInfo: { ...HOST_INITIALIZE.agentInfo, version: '1.5.1' } + } + await expect(select(older)).resolves.toBeNull() + const managed = { ...HOST_INITIALIZE, agentInfo: { name: 'antigravity-acp', version: '1.5.2' } } + await expect(select(managed)).resolves.toBeNull() + await expect( + selectAcpHostAccountHome( + ANTIGRAVITY_LAUNCH_SPEC, + { PATH: '', HOME: '/nowhere' }, + stateDirectory + ) + ).resolves.toBeNull() + + agyCredential.present = false + await expect(select(HOST_INITIALIZE)).resolves.toBeNull() + agyCredential.present = true + + // Someone already signed in to Orca's own Chat keeps it. + const managedAcp = join(stateDirectory, 'antigravity-chat', 'antigravity-acp') + await mkdir(managedAcp, { recursive: true }) + await expect(select(HOST_INITIALIZE)).resolves.not.toBeNull() + await writeFile(join(managedAcp, 'antigravity-oauth-token'), '{}') + await expect(select(HOST_INITIALIZE)).resolves.toBeNull() + } +) + +it('a chat launches on the backend its account home pins', async () => { + const resolve = (path: string) => + resolveAcpLaunchInvocation( + ANTIGRAVITY_LAUNCH_SPEC, + { variable: 'GEMINI_HOME', path }, + { + resolveEnvironment: async () => ({ PATH: '/usr/bin', HOME: '/home/user' }), + resolveCommand: (command) => `/resolved/${command}`, + dataDirectory: '/orca-data' + } + ) + const host = await resolve('/home/user/.gemini') + expect(host.command).toBe('/resolved/agy') + expect(host.spec.args({ fullAccess: false, pluginDir: null })).toEqual(['acp']) + expect(host.env.GEMINI_HOME).toBeUndefined() + expect(host.env.AGY_ACP_FORCE_FILE_STORAGE).toBeUndefined() + + const managed = await resolve('/orca-data/antigravity-chat') + expect(managed.spec.managedRuntime).toBeDefined() + expect(managed.env.GEMINI_HOME).toBe('/orca-data/antigravity-chat') + expect(managed.env.AGY_ACP_FORCE_FILE_STORAGE).toBe('1') +}) diff --git a/src/main/antigravity/antigravity-host-acp.ts b/src/main/antigravity/antigravity-host-acp.ts new file mode 100644 index 000000000000..5ddfb6fb2c15 --- /dev/null +++ b/src/main/antigravity/antigravity-host-acp.ts @@ -0,0 +1,118 @@ +// The execution host's own `agy acp`: preferred for new chats when it answers as a compatible server. + +import { existsSync } from 'node:fs' +import { readdir, stat } from 'node:fs/promises' +import { join } from 'node:path' +import type { InitializeResponse } from '../acp/generated/acp-protocol.generated' +import { + isLegacyAgentSessionAccountHome, + type AgentSessionAccountHome +} from '../../shared/agent-session/lifecycle/agent-session-account-home' +import { compareAppVersions, isValidAppVersion } from '../../shared/app-version' +import { initializeAntigravityAcp } from './antigravity-acp-runtime-probe' +import { + createAntigravityHostCredentialBackend, + isAntigravityFileStorageHost +} from './native-credential-backend' +import { hasAntigravityMacOSCredential } from './native-macos-credentials' + +/** First release verified with Orca chats; it also leaves the chat's folder untouched. */ +export const ANTIGRAVITY_HOST_ACP_MINIMUM_VERSION = '1.5.2' +/** agy keeps its sign-in and conversations here and ignores GEMINI_HOME, so this only pins the chat. */ +const AGY_HOME_FOLDER = '.gemini' +const PROBE_TIMEOUT_MS = 5_000 +const FAILED_CHECK_RETRY_MS = 5 * 60_000 + +export function isCompatibleAntigravityHostAcp(initialized: InitializeResponse): boolean { + const capabilities = initialized.agentCapabilities + const version = initialized.agentInfo?.version ?? '' + return ( + initialized.agentInfo?.name === 'Antigravity ACP Server' && + isValidAppVersion(version) && + compareAppVersions(version, ANTIGRAVITY_HOST_ACP_MINIMUM_VERSION) >= 0 && + initialized.protocolVersion === 1 && + capabilities?.loadSession === true && + Boolean(capabilities.sessionCapabilities?.resume) + ) +} + +/** The account home of chats pinned to the host's agy and its own sign-in. */ +export function antigravityHostAccountHome(homePath: string): AgentSessionAccountHome { + return { variable: 'GEMINI_HOME', path: join(homePath, AGY_HOME_FOLDER) } +} + +/** Managed chats pin `/antigravity-chat`, so only this folder name selects the host's agy. */ +export function isAntigravityHostAccountHome(home: AgentSessionAccountHome): boolean { + return ( + isLegacyAgentSessionAccountHome(home) && + home.variable === 'GEMINI_HOME' && + home.path.split(/[\\/]+/).findLast(Boolean) === AGY_HOME_FOLDER + ) +} + +// Keyed by the binary's identity so an upgrade or reinstall is checked again. +type HostCheck = { identity: string; answer: Promise; retryAt?: number } +const checks = new Map() + +/** Whether `command acp` initializes as a compatible server; a failed check waits before retrying. */ +export async function antigravityHostAcpAnswers( + command: string, + env: Record, + envToDelete: string[], + now = Date.now +): Promise { + const stats = await stat(command).catch(() => null) + if (!stats?.isFile()) { + return false + } + const identity = `${stats.size}:${stats.mtimeMs}` + const cached = checks.get(command) + if (cached?.identity === identity && (cached.retryAt === undefined || now() < cached.retryAt)) { + return cached.answer + } + const check: HostCheck = { + identity, + answer: initializeAntigravityAcp( + () => ({ command, args: ['acp'], env, envToDelete }), + PROBE_TIMEOUT_MS + ).then(isCompatibleAntigravityHostAcp, () => { + // A hung or crashing agy must not delay every chat start and availability read. + check.retryAt = now() + FAILED_CHECK_RETRY_MS + return false + }) + } + checks.set(command, check) + return check.answer +} + +/** Whether Orca's own Chat sign-in has left credentials in its managed home or a folder inside it. */ +export async function hasManagedAntigravityChatSignIn(managedHome: string): Promise { + const entries = await readdir(managedHome, { withFileTypes: true }).catch(() => []) + const folders = [ + managedHome, + ...entries.filter((entry) => entry.isDirectory()).map((entry) => join(managedHome, entry.name)) + ] + for (const folder of folders) { + const names = await readdir(folder).catch(() => []) + if (names.some((name) => name.endsWith('oauth-token'))) { + return true + } + } + return false +} + +/** Whether agy itself is signed in on this host; an unreadable store counts as signed out. */ +export async function hasAgyCredential(homePath: string): Promise { + try { + // Reading the macOS secret would ask the person for keychain access; its attributes do not. + if (process.platform === 'darwin' && !isAntigravityFileStorageHost(process.env)) { + return ( + (await hasAntigravityMacOSCredential()) || + existsSync(join(homePath, '.gemini', 'antigravity-cli', 'antigravity-oauth-token')) + ) + } + return (await createAntigravityHostCredentialBackend(homePath).read()) !== null + } catch { + return false + } +} diff --git a/src/main/antigravity/native-macos-credentials.ts b/src/main/antigravity/native-macos-credentials.ts index 5f81722cb9cb..a28cae6ea505 100644 --- a/src/main/antigravity/native-macos-credentials.ts +++ b/src/main/antigravity/native-macos-credentials.ts @@ -34,6 +34,23 @@ export type AntigravityMacOSCredentialTarget = { } const nativeTarget: AntigravityMacOSCredentialTarget = { service: 'gemini', account: 'antigravity' } +/** Whether agy's keychain item exists, read from its attributes so macOS asks for no access. */ +export async function hasAntigravityMacOSCredential(target = nativeTarget): Promise { + requireMacOS() + const result = await runSecurity([ + 'find-generic-password', + '-s', + target.service, + '-a', + target.account, + ...(target.keychainPath ? [target.keychainPath] : []) + ]) + if (!result.timedOut && !result.signal && (result.code === 0 || result.code === 44)) { + return result.code === 0 + } + throw new Error('The Antigravity macOS credential store could not be read.') +} + export async function readAntigravityMacOSCredential( target = nativeTarget ): Promise { diff --git a/src/main/codex-accounts/runtime-home-catalog-account-key.test.ts b/src/main/codex-accounts/runtime-home-catalog-account-key.test.ts index 8da1e607c22e..20d43a30c9ed 100644 --- a/src/main/codex-accounts/runtime-home-catalog-account-key.test.ts +++ b/src/main/codex-accounts/runtime-home-catalog-account-key.test.ts @@ -63,7 +63,8 @@ async function wireCodexAccountKey(settings: ReturnType) readCodexLaunchHome: codexStructuredLaunchHomeResolvers.resolveCodexStructuredLaunchHome, workspaceTrustSettings: () => settings, workspaceTrustRepoDecision: () => undefined, - stateDirectory: '/orca-data' + stateDirectory: '/orca-data', + hostLaunchEnvironment: async () => ({}) } const resolve = (purpose: 'launch' | 'read') => codex.resolveAccountHome( diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-saved-status.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-saved-status.ts index 66223e463f46..6f0fdf9f71b2 100644 --- a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-saved-status.ts +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-saved-status.ts @@ -16,7 +16,10 @@ import type { AgentSessionStatusSummary } from '../../../../shared/agent-session/agent-session-wire' import type { StructuredAgentSessionHostDeps } from '../host/structured-agent-session-host-types' -import { structuredSummaryConversationNaming } from './structured-agent-session-status-summary' +import { + structuredSummaryConversationNaming, + structuredSummaryHostProgram +} from './structured-agent-session-status-summary' import { agentSessionPinnedLaunchDirectory } from '../../../runtime/agent-session/records/agent-session-record-launch-directory' import { normalizeOptionalField, @@ -52,6 +55,7 @@ export function savedStructuredAgentSessionStatus( ? { permissionMode: record.permissionMode } : {}), ...(launchDirectory ? { launchDirectory } : {}), + ...structuredSummaryHostProgram(record), ...structuredSummaryConversationNaming(record, undefined), ...(typeof record.sleptAt === 'number' ? { sleptAt: record.sleptAt } : {}), updatedAt: at ?? record.createdAt diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary-equality.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary-equality.ts index 76c480f83f5a..30bccc61f11e 100644 --- a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary-equality.ts +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary-equality.ts @@ -40,6 +40,7 @@ export function structuredStatusSummariesEqual( a.toolInput === b.toolInput && a.lastAssistantMessage === b.lastAssistantMessage && a.launchDirectory === b.launchDirectory && + a.hostProgram === b.hostProgram && a.conversationName === b.conversationName && a.sleptAt === b.sleptAt && a.namingError?.message === b.namingError?.message && diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary.ts index edb8af2a931b..5534c7ec608a 100644 --- a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary.ts +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary.ts @@ -24,6 +24,7 @@ import type { StatusPublication } from './structured-agent-session-status-feed-deps' import { structuredStatusSummariesEqual } from './structured-agent-session-status-summary-equality' +import { structuredAgentRuntimeMetadata } from '../../../runtime/agent-session/installation/structured-agent-runtime-metadata' export function structuredAgentSessionStatusSummary({ sessionId, @@ -99,12 +100,25 @@ export function structuredAgentSessionStatusSummary({ ...childWork, ...(providerSession ? { providerSession } : {}), ...(launchDirectory ? { launchDirectory } : {}), + ...structuredSummaryHostProgram(record), ...structuredSummaryConversationNaming(record, namingFailure), ...(typeof record?.sleptAt === 'number' ? { sleptAt: record.sleptAt } : {}), updatedAt: journal.lastActivityAt() || now() } } +/** Marks chats whose pinned account runs a host program, which need no managed install. */ +export function structuredSummaryHostProgram( + record: Pick | null +): Pick { + return record && + structuredAgentRuntimeMetadata(record.provider)?.definition.runsHostProgram?.( + record.accountHome + ) + ? { hostProgram: true } + : {} +} + /** The record's name, and the failure to replace it only while that is still the name. */ export function structuredSummaryConversationNaming( record: AgentSessionConversationView | null, diff --git a/src/main/native-chat/agent-session-wire/providers/structured-agent-definition.ts b/src/main/native-chat/agent-session-wire/providers/structured-agent-definition.ts index d5fe6d2b2071..450d9b769cd0 100644 --- a/src/main/native-chat/agent-session-wire/providers/structured-agent-definition.ts +++ b/src/main/native-chat/agent-session-wire/providers/structured-agent-definition.ts @@ -3,11 +3,14 @@ import type { AgentSessionCapabilities } from '../../../../shared/agent-session/agent-session-capabilities' import type { AgentSessionStoredAgent } from '../../../../shared/agent-session/lifecycle/agent-session-stored-agent' import type { AgentSessionModelOption } from '../../../../shared/agent-session/agent-session-wire' +import type { AgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' export type StructuredAgentDefinition = AgentSessionStoredAgent & { capabilities: AgentSessionCapabilities /** Absent means Orca never supplies this agent’s managed runtime. */ managedRuntime?: () => boolean + /** Whether a chat pinned to `home` runs a program the host has rather than the managed runtime. */ + runsHostProgram?: (home: AgentSessionAccountHome) => boolean restingOptions: { acceptsKey: (key: string) => boolean /** Null means no fallback catalog. */ diff --git a/src/main/runtime/agent-session/installation/structured-agent-runtime-metadata.ts b/src/main/runtime/agent-session/installation/structured-agent-runtime-metadata.ts index 4476483a254c..82f3dfc34eda 100644 --- a/src/main/runtime/agent-session/installation/structured-agent-runtime-metadata.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-runtime-metadata.ts @@ -2,7 +2,7 @@ import { agentSessionAccountHome } from '../../../../shared/agent-session/lifecy import { applyStructuredCodexWorkspaceTrust } from '../../../agent-launch/trust/agent-workspace-trust-spawn' import { ACP_LAUNCH_SPECS, type AcpLaunchSpec } from '../../../acp/acp-launch-specs' import { acpStructuredAgentDefinition } from '../../../acp/acp-structured-agent-definitions' -import { resolveAcpLaunchCommand } from '../../../acp/acp-structured-launch-resolution' +import { resolveAcpLaunchCommand, selectAcpHostAccountHome } from '../../../acp/acp-launch-command' import { CODEX_STRUCTURED_AGENT } from '../../../codex/structured/launch/codex-structured-agent-definition' import { CLAUDE_STRUCTURED_AGENT } from '../../../claude/structured/claude-structured-agent-definition' import { CLAUDE_CLI_CONVERSATIONS } from '../../../claude/claude-cli-conversations' @@ -43,7 +43,13 @@ function acpChatProgram(spec: AcpLaunchSpec): StructuredAgentChatProgram { const options = { commandSettings, dataDirectory: getProfileUserDataPath() } return { ...resolveAcpLaunchCommand(spec, env, options), env } }, - ...(managedRuntime ? { installable: () => managedRuntime.pin() !== null } : {}) + ...(managedRuntime ? { installable: () => managedRuntime.pin() !== null } : {}), + ...(spec.hostBackend + ? { + hostAlternative: async (shellEnv) => + (await selectAcpHostAccountHome(spec, shellEnv, getProfileUserDataPath())) !== null + } + : {}) } } @@ -79,8 +85,25 @@ function acpMetadata(spec: AcpLaunchSpec): StructuredAgentRuntimeMetadata { } } : {}), - resolveAccountHome: ({ launchEnv }, { stateDirectory }) => - spec.account.resolve({ launchEnv, stateDirectory }), + // New chats prefer a compatible host program, which their account home then pins; reads such + // as Orca's own sign-in keep the agent's account. + resolveAccountHome: async ( + { launchEnv, purpose, permissionMode }, + { stateDirectory, hostLaunchEnvironment } + ) => { + // A host program without the chat's permission mode never takes it; `own` sets none. + const host = + spec.hostBackend && + purpose === 'launch' && + (permissionMode === undefined || + permissionMode === 'own' || + spec.hostBackend.spec.permissionModeConfig?.values[permissionMode] !== undefined) + ? await hostLaunchEnvironment(spec.agent) + .then((env) => selectAcpHostAccountHome(spec, env, stateDirectory)) + .catch(() => null) + : null + return host ?? spec.account.resolve({ launchEnv, stateDirectory }) + }, modelCatalog: (context) => acpModelCatalogDiscovery(spec, context), transcriptImport: spec.transcriptImport, sessionHistory: spec.sessionHistory diff --git a/src/main/runtime/agent-session/installation/structured-agent-runtime-registration-types.ts b/src/main/runtime/agent-session/installation/structured-agent-runtime-registration-types.ts index d549f6af0129..8a86f0d861b5 100644 --- a/src/main/runtime/agent-session/installation/structured-agent-runtime-registration-types.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-runtime-registration-types.ts @@ -49,6 +49,8 @@ export type StructuredAgentAccountHomeRequest = { purpose: 'launch' | 'read' | 'identity' /** The launch's workspace directory on this host; a read has none. */ workspacePath: (() => Promise) | null + /** The permission mode a new chat starts in, when it names one. */ + permissionMode?: string } /** What resolving an account may ask of the runtime around it. */ @@ -64,6 +66,8 @@ export type StructuredAgentAccountHomeServices = { ) => Parameters[0]['repoDecision'] /** Orca's data folder on this host, where an agent's chats may keep an account of their own. */ stateDirectory: string + /** The environment a chat start of `agent` on this host would launch from. */ + hostLaunchEnvironment: (agent: string) => Promise> } /** What a catalog probe is built from: the same runtime resolvers its sessions launch through. */ @@ -104,6 +108,8 @@ export type StructuredAgentChatProgram = { resolve: StructuredAgentLaunchCheck['resolveLaunch'] /** Whether Orca can download this program on this host when none is found. */ installable?: () => boolean + /** Whether a new chat would run a compatible program the host already has instead. */ + hostAlternative?: (env: Record) => Promise } export type StructuredAgentRuntimeMetadata = StructuredAgentCliConversations & { diff --git a/src/main/runtime/agent-session/launch/structured-agent-availability.ts b/src/main/runtime/agent-session/launch/structured-agent-availability.ts index e34668948b82..fd7e2ebd4e9d 100644 --- a/src/main/runtime/agent-session/launch/structured-agent-availability.ts +++ b/src/main/runtime/agent-session/launch/structured-agent-availability.ts @@ -73,15 +73,16 @@ async function observeHostAgent( /** Resolve chat program without spawn; bare names miss unless relative PATH entries require workspace resolution. */ async function observeChatProgram( - { definition: { agent }, chatProgram }: StructuredAgentRuntimeMetadata, + { definition: { agent }, chatProgram, supportsLocation }: StructuredAgentRuntimeMetadata, runtime: HealthRuntime ): Promise> { if (!chatProgram) { return 'unknown' } + let shellEnv: Record try { const settings = runtime.requireStore().getSettings() - const shellEnv = await resolveHostStructuredAgentLaunchEnvironment(agent, settings) + shellEnv = await resolveHostStructuredAgentLaunchEnvironment(agent, settings) const { command, env } = chatProgram.resolve(shellEnv, settings) if (isAbsolute(command)) { return 'available' @@ -93,6 +94,9 @@ async function observeChatProgram( } catch { return 'unknown' } + if (supportsLocation(HOST_LOCATION) && (await chatProgram.hostAlternative?.(shellEnv))) { + return 'available' + } return chatProgram.installable?.() ? 'installable' : 'missing' } diff --git a/src/main/runtime/rpc/methods/host-management/managed-runtime-install.ts b/src/main/runtime/rpc/methods/host-management/managed-runtime-install.ts index 8c0455392866..4deda9a5909f 100644 --- a/src/main/runtime/rpc/methods/host-management/managed-runtime-install.ts +++ b/src/main/runtime/rpc/methods/host-management/managed-runtime-install.ts @@ -6,7 +6,7 @@ import { ManagedRuntimeCancelParams } from '../../../../../shared/rpc-contract/managed-runtime-install-params' import { acpLaunchSpecFor } from '../../../../acp/acp-launch-specs' -import { resolveAcpLaunchCommand } from '../../../../acp/acp-structured-launch-resolution' +import { resolveAcpLaunchCommand } from '../../../../acp/acp-launch-command' import { ManagedRuntimeInstallation } from '../../../../node-runtime/managed-runtime-installation' import '../../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import { isAgentSessionPreSpawnError } from '../../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' diff --git a/src/main/runtime/session-tabs/structured-session-account-home.ts b/src/main/runtime/session-tabs/structured-session-account-home.ts index ad5adef09dfa..4e38852cf9e6 100644 --- a/src/main/runtime/session-tabs/structured-session-account-home.ts +++ b/src/main/runtime/session-tabs/structured-session-account-home.ts @@ -1,6 +1,7 @@ import type { StructuredAgentId } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle' import { structuredAgentRuntimeMetadata } from '../agent-session/installation/structured-agent-runtime-metadata' import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' +import { resolveHostStructuredAgentLaunchEnvironment } from '../agent-session/launch/structured-agent-launch-support' import { agentWorkspaceTrustDecisionForWorkspace } from '../../agent-launch/trust/agent-workspace-trust-spawn' import { OrcaRuntimeWithStructuredSessionCliWriterHost } from './structured-session-cli-writer-host' import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' @@ -18,12 +19,13 @@ export abstract class OrcaRuntimeWithStructuredSessionAccountHome extends OrcaRu if (!registration) { return null } - return async ({ launchEnv, location }) => + return async ({ launchEnv, location }, permissionMode?: string) => registration.resolveAccountHome( { launchEnv, location: location ?? null, purpose, + ...(permissionMode ? { permissionMode } : {}), workspacePath: purpose === 'launch' ? async () => @@ -44,7 +46,9 @@ export abstract class OrcaRuntimeWithStructuredSessionAccountHome extends OrcaRu this.requireStore() ), // The chat host's own state root (ensureStructuredAgentSessionHost). - stateDirectory: getProfileUserDataPath() + stateDirectory: getProfileUserDataPath(), + hostLaunchEnvironment: (agent) => + resolveHostStructuredAgentLaunchEnvironment(agent, this.requireStore().getSettings()) } ) } diff --git a/src/main/runtime/session-tabs/structured-session-create-support.ts b/src/main/runtime/session-tabs/structured-session-create-support.ts index 47b8fdc2508a..a904aa5a05e9 100644 --- a/src/main/runtime/session-tabs/structured-session-create-support.ts +++ b/src/main/runtime/session-tabs/structured-session-create-support.ts @@ -1,3 +1,4 @@ +import { AGENT_CHAT_PERMISSION_MODE_OPTION_ID } from '../../../shared/agent-launch/permissions/agent-chat-permission-mode' import { resolveStructuredAgentSessionForkIntent } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-fork' import { captureStructuredAgentCliSource, @@ -154,15 +155,18 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte protected async resolveStructuredAgentSessionIntent( input: StructuredAgentSessionCreateIntentInput, - resolveAccountHome: (context: { - launchEnv: NodeJS.ProcessEnv - location: { - executionHostId: string - wslDistro: string | null - workspaceId: string - workspaceKind: 'folder' | 'git-worktree' - } - }) => AgentSessionAccountHome | Promise + resolveAccountHome: ( + context: { + launchEnv: NodeJS.ProcessEnv + location: { + executionHostId: string + wslDistro: string | null + workspaceId: string + workspaceKind: 'folder' | 'git-worktree' + } + }, + permissionMode?: string + ) => AgentSessionAccountHome | Promise ): Promise { const support = await this.getStructuredAgentSessionCreateSupport(input.worktree, input.agent) // Adopting a conversation reads the agent's own transcript, so only an agent registered with an @@ -205,7 +209,8 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte const workspaceCwd = resumeFrom ? (await this.resolveRuntimeFileTarget(input.worktree)).worktree.path : '' - const selectedAccountHome = await resolveAccountHome({ launchEnv, location }) + const permissionMode = options?.[AGENT_CHAT_PERMISSION_MODE_OPTION_ID] + const selectedAccountHome = await resolveAccountHome({ launchEnv, location }, permissionMode) // Adoption pins the transcript's actual account home; fresh-create defaults may open a blank conversation under the old name. const adoption = resumeFrom && transcriptImport diff --git a/src/renderer/src/components/native-chat/NativeChatInstallSlot.tsx b/src/renderer/src/components/native-chat/NativeChatInstallSlot.tsx index 3da2c6d04c4b..97134e3d6c78 100644 --- a/src/renderer/src/components/native-chat/NativeChatInstallSlot.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInstallSlot.tsx @@ -9,6 +9,7 @@ import { } from '@/runtime/use-managed-runtime-install' import type { ManagedRuntimeInstallState } from '../../../../shared/managed-runtime-install' import { NativeChatInstallStrip } from './NativeChatInstallStrip' +import { useStructuredAgentSessionHostProgram } from './structured-agent-session-status-hooks' import type { NativeChatStructuredViewProps } from './native-chat-view-types' export type NativeChatInstallSlotState = @@ -29,7 +30,7 @@ const RESERVED: NativeChatInstallSlotState = { kind: 'reserved' } /** Reserve unknown readiness with an editable composer and held sends; missing runtimes show installation, while read failures leave it alone. */ export function useNativeChatInstallSlot( - props: Pick, + props: Pick, agentLabel: string, layout: ManagedRuntimeInstallLayout ): { @@ -37,9 +38,11 @@ export function useNativeChatInstallSlot( sendBlockedReason: string | null unavailableHint: string | undefined } { - const slot = installSlotState( - useManagedRuntimeInstall(props.target, props.agent, props.isVisible), - layout + const hostProgram = useStructuredAgentSessionHostProgram(props.sessionId, props.target) + const slot = nativeChatInstallSlotState( + useManagedRuntimeInstall(props.target, props.agent, props.isVisible && !hostProgram), + layout, + hostProgram ) const unavailableHint = slot.kind === 'install' @@ -52,11 +55,13 @@ export function useNativeChatInstallSlot( } } -function installSlotState( +/** A chat running the host's own program needs no managed install, whatever its state. */ +export function nativeChatInstallSlotState( observation: ManagedRuntimeInstallObservation, - layout: ManagedRuntimeInstallLayout + layout: ManagedRuntimeInstallLayout, + hostProgram: boolean ): NativeChatInstallSlotState { - if (observation.kind === 'inactive') { + if (hostProgram || observation.kind === 'inactive') { return NONE } if (observation.kind === 'pending') { diff --git a/src/renderer/src/components/native-chat/NativeChatNoticeRow.tsx b/src/renderer/src/components/native-chat/NativeChatNoticeRow.tsx index 7217428bde30..b0cda619f1da 100644 --- a/src/renderer/src/components/native-chat/NativeChatNoticeRow.tsx +++ b/src/renderer/src/components/native-chat/NativeChatNoticeRow.tsx @@ -214,7 +214,11 @@ export function NativeChatNoticeRow({ const continueOffered = orcaStop?.turnItemId !== undefined && orcaStop.turnItemId === orcaStopView.offeredTurnItemId const failure = readWholeAgentSessionFailureFact(block.failure) - const antigravitySignInContent = nativeChatAntigravitySignInContent(failure?.kind, agentName) + const antigravitySignInContent = nativeChatAntigravitySignInContent( + failure?.kind, + agentName, + failure?.account + ) const usageLimitContinue = block.usageLimitTurnItemId !== undefined && block.usageLimitTurnItemId === orcaStopView.usageLimitTurnItemId diff --git a/src/renderer/src/components/native-chat/agent-session-availability-words-text.ts b/src/renderer/src/components/native-chat/agent-session-availability-words-text.ts index 50df24379af2..01aa7fc07a2b 100644 --- a/src/renderer/src/components/native-chat/agent-session-availability-words-text.ts +++ b/src/renderer/src/components/native-chat/agent-session-availability-words-text.ts @@ -12,6 +12,7 @@ type AvailabilityCopyId = Extract< | 'codexSystemNotSignedIn' | 'codexManagedNotSignedIn' | 'antigravityNotSignedIn' + | 'antigravitySystemNotSignedIn' | 'agentCommandNotSignedIn' | 'interactiveAgentNotSignedIn' | 'agentNotSignedIn' @@ -78,6 +79,12 @@ export const AVAILABILITY_PIECES: Record< COPY.antigravityNotSignedIn, values ), + antigravitySystemNotSignedIn: (values) => + translate( + 'components.native-chat.failureWords.antigravitySystemNotSignedIn', + COPY.antigravitySystemNotSignedIn, + values + ), modelUnavailable: (values) => translate( 'components.native-chat.failureWords.modelUnavailable', diff --git a/src/renderer/src/components/native-chat/native-chat-antigravity-settings.tsx b/src/renderer/src/components/native-chat/native-chat-antigravity-settings.tsx index 183da9346efa..138d7e955b13 100644 --- a/src/renderer/src/components/native-chat/native-chat-antigravity-settings.tsx +++ b/src/renderer/src/components/native-chat/native-chat-antigravity-settings.tsx @@ -4,11 +4,17 @@ import { useAppStore } from '@/store' import { agentSessionSignInFor } from '../../../../shared/agent-session/lifecycle/agent-session-sign-in' import { NativeChatActionButton } from './NativeChatActionButton' +/** Links Orca's own Antigravity sign-in; chats on the host's agy (`system`) use agy's instead. */ export function nativeChatAntigravitySignInContent( failureKind: string | undefined, - agentName: string | undefined + agentName: string | undefined, + account?: string ): React.JSX.Element | undefined { - if (failureKind !== 'notSignedIn' || agentSessionSignInFor(agentName)?.agent !== 'antigravity') { + if ( + failureKind !== 'notSignedIn' || + account === 'system' || + agentSessionSignInFor(agentName)?.agent !== 'antigravity' + ) { return undefined } return ( diff --git a/src/renderer/src/components/native-chat/native-chat-install-slot.test.ts b/src/renderer/src/components/native-chat/native-chat-install-slot.test.ts new file mode 100644 index 000000000000..3779caa1f3f5 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-install-slot.test.ts @@ -0,0 +1,25 @@ +import { expect, it } from 'vitest' +import { nativeChatInstallSlotState } from './NativeChatInstallSlot' + +it("offers Orca's install only to chats that run the managed runtime", () => { + const notInstalled = { + kind: 'active' as const, + subject: { target: { kind: 'local' as const }, runtimeId: null, agent: 'antigravity' }, + removable: false, + snapshot: { + kind: 'known' as const, + state: { + agent: 'antigravity', + revision: 1, + available: true, + version: '1.4.1', + installedVersion: null, + installedCurrent: false, + source: null, + operation: null + } + } + } + expect(nativeChatInstallSlotState(notInstalled, 'strip', false).kind).toBe('install') + expect(nativeChatInstallSlotState(notInstalled, 'strip', true)).toEqual({ kind: 'none' }) +}) diff --git a/src/renderer/src/components/native-chat/native-chat-structured-session-notices.ts b/src/renderer/src/components/native-chat/native-chat-structured-session-notices.ts index 2d88ba08a40e..04588e6c0ede 100644 --- a/src/renderer/src/components/native-chat/native-chat-structured-session-notices.ts +++ b/src/renderer/src/components/native-chat/native-chat-structured-session-notices.ts @@ -52,7 +52,12 @@ function nativeChatLaunchNotice({ // An argument problem already says the start failed; the generic lead would repeat it. const saysStartFailure = failure?.code === 'agent_session_operation_invalid' && failure.details?.argumentProblem - const signInContent = nativeChatAntigravitySignInContent(failure?.details?.reason, agentLabel) + const details = failure?.details + const signInContent = nativeChatAntigravitySignInContent( + details?.reason, + agentLabel, + details && 'account' in details ? details.account : undefined + ) return { content: signInContent, key: 'launch', diff --git a/src/renderer/src/components/native-chat/structured-agent-session-status-hooks.ts b/src/renderer/src/components/native-chat/structured-agent-session-status-hooks.ts index b262f55b6947..1048611c21ed 100644 --- a/src/renderer/src/components/native-chat/structured-agent-session-status-hooks.ts +++ b/src/renderer/src/components/native-chat/structured-agent-session-status-hooks.ts @@ -73,6 +73,19 @@ export function useStructuredAgentSessionHostExecutionPhase( ) } +/** Whether the host says this chat runs a program the host already has; an older host never does. */ +export function useStructuredAgentSessionHostProgram( + sessionId: string, + target: RuntimeClientTarget +): boolean { + const { feed, subscribe } = useSessionFeed(sessionId, target) + return useSyncExternalStore( + subscribe, + () => feed.getSnapshot().get(sessionId)?.hostProgram === true, + () => false + ) +} + /** Whether the host says a person's Stop is still ending the work; an older host never does. */ export function useStructuredAgentSessionHostStopping( sessionId: string, diff --git a/src/renderer/src/components/native-chat/use-native-chat-availability-notice.ts b/src/renderer/src/components/native-chat/use-native-chat-availability-notice.ts index ef373cf67bd5..8e21ee74f451 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-availability-notice.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-availability-notice.ts @@ -130,7 +130,11 @@ export function useNativeChatAvailabilityNotice(input: { { kind: 'notSignedIn', account: unavailable.account }, sayAgentSessionFailureTranslated ), - content: nativeChatAntigravitySignInContent(unavailable.reason, input.agent), + content: nativeChatAntigravitySignInContent( + unavailable.reason, + input.agent, + unavailable.reason === 'notSignedIn' ? unavailable.account : undefined + ), onDismiss: () => setDismissal({ key, dismissed: true }) } } diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index db9fb5b8757e..4f90c2be4b04 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -1548,6 +1548,7 @@ "agentNotSignedIn": "Sign in to {{agent}}.", "answerUnconfirmed": "Your answer was recorded but the agent did not confirm it.", "antigravityNotSignedIn": "Antigravity isn't signed in. Sign in under Settings → Accounts → Antigravity. Then send your message again.", + "antigravitySystemNotSignedIn": "Antigravity isn't signed in. Sign in by running `agy` on the computer running this chat, then send your message again.", "argumentsMissingValue": "Saved Arguments need a value for {{option}}.", "argumentsMultipleValues": "Saved Arguments give {{option}} more than one value.", "argumentsPositionalPrompt": "Saved Arguments include a prompt.", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index c358d631025d..f97470e4e61a 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -19736,6 +19736,7 @@ "codexSystemNotSignedIn": "Codex isn't signed in. Run `{{loginCommand}}`.", "codexManagedNotSignedIn": "This Codex account isn't signed in. Sign in again in Codex Accounts settings.", "antigravityNotSignedIn": "Antigravity isn't signed in. Sign in under Settings → Accounts → Antigravity. Then send your message again.", + "antigravitySystemNotSignedIn": "Antigravity isn't signed in. Sign in by running `agy` on the computer running this chat, then send your message again.", "cliMissing": "{{agent}} wasn't found on the computer running this chat. Install it, or check its Command in Settings → Agents.", "cliMissingInWslDistro": "{{agent}} isn't installed in the WSL distro {{distro}}. Install it inside {{distro}}, or check its Command in Settings → Agents.", "signInFirst": "Sign in first.", diff --git a/src/shared/agent-session/agent-session-availability.ts b/src/shared/agent-session/agent-session-availability.ts index 208be92db17d..d8143b3edf39 100644 --- a/src/shared/agent-session/agent-session-availability.ts +++ b/src/shared/agent-session/agent-session-availability.ts @@ -36,7 +36,9 @@ export function agentSessionSignInCopyId(provider: string, account?: AgentSessio ? 'codexManagedNotSignedIn' : 'codexSystemNotSignedIn' : signIn?.agent === 'antigravity' - ? 'antigravityNotSignedIn' + ? account === 'system' + ? 'antigravitySystemNotSignedIn' + : 'antigravityNotSignedIn' : signIn && 'slashCommand' in signIn ? 'interactiveAgentNotSignedIn' : signIn?.loginCommand.length diff --git a/src/shared/agent-session/agent-session-wire.ts b/src/shared/agent-session/agent-session-wire.ts index a8c564b32168..07276806d8fb 100644 --- a/src/shared/agent-session/agent-session-wire.ts +++ b/src/shared/agent-session/agent-session-wire.ts @@ -249,6 +249,9 @@ export type AgentSessionStatusSummary = { /** The record's Sleep mark: the user's Sleep stopped this chat and nothing has been sent since. * Absent from older hosts. */ sleptAt?: number + /** The chat runs a program the host already has, so it needs no Orca-installed runtime. + * Absent from older hosts. */ + hostProgram?: true /** Host-path directory the session is held to regardless of its workspace's current directory * (a floating chat's pinned folder). Absent means resolve the workspace id; older hosts omit it. */ launchDirectory?: string diff --git a/src/shared/agent-session/failures/agent-session-failure-copy.ts b/src/shared/agent-session/failures/agent-session-failure-copy.ts index 9bd1f0a15e99..c59a106dd5bf 100644 --- a/src/shared/agent-session/failures/agent-session-failure-copy.ts +++ b/src/shared/agent-session/failures/agent-session-failure-copy.ts @@ -51,6 +51,8 @@ export const AGENT_SESSION_FAILURE_COPY = { "This Codex account isn't signed in. Sign in again in Codex Accounts settings.", antigravityNotSignedIn: "Antigravity isn't signed in. Sign in under Settings → Accounts → Antigravity. Then send your message again.", + antigravitySystemNotSignedIn: + "Antigravity isn't signed in. Sign in by running `agy` on the computer running this chat, then send your message again.", agentCommandNotSignedIn: 'Sign in to {{agent}} with `{{loginCommand}}` on the computer running this chat.', interactiveAgentNotSignedIn: