Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/main/acp/acp-dialects/acp-dialect.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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
}
Expand Down
91 changes: 91 additions & 0 deletions src/main/acp/acp-launch-command.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, string>>,
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<Record<string, string>>,
stateDirectory: string,
inherited: NodeJS.ProcessEnv = process.env
): Promise<AgentSessionAccountHome | null> {
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
}
85 changes: 21 additions & 64 deletions src/main/acp/acp-launch-specs.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -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<string, string>
envToDelete: string[]
homePath: string
/** Orca's data folder on this host, where the agent's own account lives. */
stateDirectory: string
}): Promise<AgentSessionAccountHome | null>
}

const GROK_LAUNCH_SPEC: AcpLaunchSpec = {
Expand Down Expand Up @@ -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,
Expand Down
9 changes: 5 additions & 4 deletions src/main/acp/acp-structured-acquire.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand All @@ -67,14 +66,16 @@ 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: {
lane: AcpStructuredLane | null
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
Expand Down
3 changes: 2 additions & 1 deletion src/main/acp/acp-structured-agent-definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand Down
8 changes: 6 additions & 2 deletions src/main/acp/acp-structured-handshake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export async function initializeAcpStructuredSession(
input: AcpHandshakeInput
): Promise<StructuredAgentSessionProviderOpenResult> {
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)
Expand Down Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion src/main/acp/acp-structured-host.test-support.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
15 changes: 7 additions & 8 deletions src/main/acp/acp-structured-launch-preparation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<AcpStructuredSessionAdapterDeps, 'spec' | 'resolveLaunch'>,
deps: Pick<AcpStructuredSessionAdapterDeps, 'resolveLaunch'>,
acquire: Pick<StructuredAgentSessionAcquireInput, 'identity' | 'spawnToken' | 'permissionMode'>,
closedBeforeSpawn: () => void
): Promise<AcpStructuredLaunch> {
Expand All @@ -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<string, string>
spec: AcpLaunchSpec
antigravityChatAuth?: AntigravityChatAuthConfig
}
>(
deps: Pick<AcpStructuredSessionAdapterDeps, 'spec'>,
resolve: () => Promise<Launch>,
closedBeforeSpawn: () => void
): Promise<Launch> {
const { spec } = deps
>(resolve: () => Promise<Launch>, closedBeforeSpawn: () => void): Promise<Launch> {
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) {
Expand Down
Loading
Loading