Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion src/main/acp/acp-private-temp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { mkdir, mkdtemp, rm } from 'node:fs/promises'
import { join } from 'node:path'
import { unixSocketPathFits } from '../../shared/unix-socket-path-limit'
import { ensureOwnedPrivateDir } from '../daemon/endpoint/publication/daemon-socket-endpoint-path'
import { launchPreparationFailure } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter'
import { launchPreparationFailure } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors'
import type { AcpStructuredConnection, ConnectAcpAgent } from './acp-structured-connection'
import type { AcpStructuredSessionAdapterDeps } from './acp-structured-session-adapter-deps'
import type { StructuredAgentSessionLogger } from '../native-chat/agent-session-wire/host/structured-agent-session-logger'
Expand Down
126 changes: 21 additions & 105 deletions src/main/acp/acp-structured-session-adapter.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
import { randomUUID } from 'node:crypto'
import { startAcpStructuredSession } from './acp-structured-start'

import type { AgentSessionExecutionLocation } from '../../shared/agent-session/lifecycle/agent-session-record'
import {
AgentSessionAcquisitionExitProvenError,
AgentSessionAcquisitionExitUnprovenError,
AgentSessionAcquisitionRootExitObservedError,
AgentSessionPreSpawnError,
isAgentSessionPreSpawnError,
type AgentSessionAcquisition,
type AgentSessionDispatchOutcome as DispatchOutcome,
type StructuredAgentSessionAcquireInput,
type StructuredAgentSessionAdapter as SessionAdapter,
type StructuredAgentSessionSetOptionInput as SetOptionInput
import { AgentSessionAcquisitionExitUnprovenError } from '../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors'

import type {
AgentSessionAcquisition,
AgentSessionDispatchOutcome as DispatchOutcome,
StructuredAgentSessionAcquireInput,
StructuredAgentSessionAdapter as SessionAdapter,
StructuredAgentSessionSetOptionInput as SetOptionInput
} from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter'
import { withObservedProviderExit } from '../native-chat/agent-session-wire/startup/structured-agent-session-failure-text'
import { acpAgentName } from './acp-structured-agent-definitions'
import { acquireAcpStructuredSession } from './acp-structured-acquire'

import { rejectedAcpDispatch, type AcpStructuredSession } from './acp-structured-session'
import type { ProviderStartAttempt } from '../provider-process/provider-acquisition-starts'
import { waitForAcpExit, type AcpStructuredConnection } from './acp-structured-connection'
import { AcpConnectionClosedError } from './acp-errors'
import { withProviderSpawnAbsence } from '../provider-process/provider-executable-missing'

import { applyAcpMessageOptions } from './acp-message-execution-options'
import { AgentSessionOptionRejectedError } from '../native-chat/agent-session-wire/options/structured-agent-session-option-error'
import * as stop from './acp-structured-stop'
Expand All @@ -37,7 +30,7 @@ import { AcpStructuredChildren } from './acp-structured-child-lifecycle'
import { AcpConversationCopies } from './acp-conversation-copies'
import { AcpTextTasks } from './acp-text-task'
import { supportsAcpStructuredLocation } from './acp-structured-location-support'
import { acpAcquireFailure, acpRefusedStart } from './acp-startup-outcome'
import { acpAcquireFailure } from './acp-startup-outcome'
import { openAcpStart } from './acp-structured-start-open'
import { admitStructuredAgentSessionInput } from '../native-chat/agent-session-wire/delivery/structured-agent-session-input-admission'

Expand Down Expand Up @@ -76,7 +69,14 @@ export class AcpStructuredSessionAdapter implements SessionAdapter {
)
)
}
return await this.start({ ...input, signal: attempt.signal }, attempt)
return await startAcpStructuredSession(
this.deps,
this.children,
{ ...input, signal: attempt.signal },
attempt,
this.now,
this.graceMs
)
} catch (error) {
throw acpAcquireFailure(error)
} finally {
Expand All @@ -85,90 +85,6 @@ export class AcpStructuredSessionAdapter implements SessionAdapter {
}
}

private async start(
input: StructuredAgentSessionAcquireInput,
attempt: ProviderStartAttempt<AcpStructuredConnection>
): Promise<AgentSessionAcquisition> {
const sessionId = input.identity.sessionId
const generation = this.deps.mintGeneration?.() ?? randomUUID()
this.children.endings.admit(sessionId, generation)
try {
const { acquisition, session } = await acquireAcpStructuredSession({
acquire: input,
deps: this.deps,
generation,
abandoned: () => attempt.signal.aborted,
track: (connection) => {
connection.onExit((_exit, requested, lost) => {
if (!requested) {
input.events?.observeRootExit?.()
this.children.recordExit(sessionId, generation, connection, lost)
}
})
this.children.starts.track(attempt, connection)
this.deps.spec.launchGate?.retain(connection)
},
onExit: (session) => {
if (session && this.children.sessions.get(sessionId) === session) {
this.children.finish(session, this.now())
}
},
onConnectionLost: (session, error) => this.children.connectionLost(session, error),
onSettled: (settlement) => this.deps.onDispatchSettledLate?.({ sessionId, ...settlement }),
forceClose: (id) => this.children.stopAfterFailure(id)
})
if (attempt.signal.aborted) {
session.dispose()
throw new Error('closed while starting')
}
this.children.sessions.set(sessionId, session)
return acquisition
} catch (error) {
this.children.endings.retire(sessionId, generation)
const { connection } = attempt
if (connection && error instanceof AcpConnectionClosedError) {
// Wait briefly for process exit so startup failures include final diagnostics.
await waitForAcpExit(connection, this.graceMs(), attempt.signal)
}
// Orca closing the connection first, such as on a sign-in line it cannot read, is the start's
// cause; the exit its cleanup then causes is not the agent ending unanswered. Capture
// spontaneous exit before close can classify it as requested.
const exitedOnItsOwn =
connection?.exited === true && !attempt.signal.aborted && !connection.lostBeforeExit
const cleaned = connection && (await connection.close().catch(() => false))
// Read after cleanup, which may be what observes the refusal; it outranks generic errors.
const refused = connection?.lostBeforeExit
const cause = refused ? acpRefusedStart(refused) : error
if (connection && !cleaned) {
// Retain failed cleanup for retry before another child can spawn.
this.children.starts.retainFailed(sessionId, connection)
throw new AgentSessionAcquisitionExitUnprovenError(cause)
}
if (connection?.lastCloseResult?.killDelivered && !connection.exited) {
throw new AgentSessionAcquisitionRootExitObservedError(cause, 'kill-delivered')
}
if (attempt.signal.aborted) {
const closed = new Error(
`${acpAgentName(this.deps.spec.agent)} was closed while starting`,
{ cause: error }
)
throw connection ? closed : new AgentSessionPreSpawnError(closed)
}
// Once the exit is proven, the start's error names a CLI or folder the spawn found missing.
if (cause instanceof Error && connection?.exited) {
withProviderSpawnAbsence(cause, connection.spawnAbsence)
}
if (connection && exitedOnItsOwn && !isAgentSessionPreSpawnError(error)) {
throw new AgentSessionAcquisitionExitProvenError(
withObservedProviderExit(
new Error(connection.stderrTail() || String(error), { cause: error })
)
)
}
throw cause
}
}

open: NonNullable<SessionAdapter['open']> = (input) => openAcpStart(this.children, input)

startupEnding: NonNullable<SessionAdapter['startupEnding']> = (sessionId, generation) =>
Expand Down
111 changes: 111 additions & 0 deletions src/main/acp/acp-structured-start.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { randomUUID } from 'node:crypto'
import {
AgentSessionAcquisitionExitProvenError,
AgentSessionAcquisitionExitUnprovenError,
AgentSessionAcquisitionRootExitObservedError
} from '../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors'
import {
AgentSessionPreSpawnError,
isAgentSessionPreSpawnError
} from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors'
import type {
AgentSessionAcquisition,
StructuredAgentSessionAcquireInput
} from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter'
import { withObservedProviderExit } from '../native-chat/agent-session-wire/startup/structured-agent-session-failure-text'
import { acpAgentName } from './acp-structured-agent-definitions'
import { acquireAcpStructuredSession } from './acp-structured-acquire'
import type { ProviderStartAttempt } from '../provider-process/provider-acquisition-starts'
import { waitForAcpExit, type AcpStructuredConnection } from './acp-structured-connection'
import { AcpConnectionClosedError } from './acp-errors'
import { withProviderSpawnAbsence } from '../provider-process/provider-executable-missing'
import { acpRefusedStart } from './acp-startup-outcome'
import type { AcpStructuredSessionAdapterDeps } from './acp-structured-session-adapter-deps'
import type { AcpStructuredChildren } from './acp-structured-child-lifecycle'

export async function startAcpStructuredSession(
deps: AcpStructuredSessionAdapterDeps,
children: AcpStructuredChildren,
input: StructuredAgentSessionAcquireInput,
attempt: ProviderStartAttempt<AcpStructuredConnection>,
now: () => number,
graceMs: () => number
): Promise<AgentSessionAcquisition> {
const sessionId = input.identity.sessionId
const generation = deps.mintGeneration?.() ?? randomUUID()
children.endings.admit(sessionId, generation)
try {
const { acquisition, session } = await acquireAcpStructuredSession({
acquire: input,
deps: deps,
generation,
abandoned: () => attempt.signal.aborted,
track: (connection) => {
connection.onExit((_exit, requested, lost) => {
if (!requested) {
input.events?.observeRootExit?.()
children.recordExit(sessionId, generation, connection, lost)
}
})
children.starts.track(attempt, connection)
deps.spec.launchGate?.retain(connection)
},
onExit: (session) => {
if (session && children.sessions.get(sessionId) === session) {
children.finish(session, now())
}
},
onConnectionLost: (session, error) => children.connectionLost(session, error),
onSettled: (settlement) => deps.onDispatchSettledLate?.({ sessionId, ...settlement }),
forceClose: (id) => children.stopAfterFailure(id)
})
if (attempt.signal.aborted) {
session.dispose()
throw new Error('closed while starting')
}
children.sessions.set(sessionId, session)
return acquisition
} catch (error) {
children.endings.retire(sessionId, generation)
const { connection } = attempt
if (connection && error instanceof AcpConnectionClosedError) {
// Wait briefly for process exit so startup failures include final diagnostics.
await waitForAcpExit(connection, graceMs(), attempt.signal)
}
// Orca closing the connection first, such as on a sign-in line it cannot read, is the start's
// cause; the exit its cleanup then causes is not the agent ending unanswered. Capture
// spontaneous exit before close can classify it as requested.
const exitedOnItsOwn =
connection?.exited === true && !attempt.signal.aborted && !connection.lostBeforeExit
const cleaned = connection && (await connection.close().catch(() => false))
// Read after cleanup, which may be what observes the refusal; it outranks generic errors.
const refused = connection?.lostBeforeExit
const cause = refused ? acpRefusedStart(refused) : error
if (connection && !cleaned) {
// Retain failed cleanup for retry before another child can spawn.
children.starts.retainFailed(sessionId, connection)
throw new AgentSessionAcquisitionExitUnprovenError(cause)
}
if (connection?.lastCloseResult?.killDelivered && !connection.exited) {
throw new AgentSessionAcquisitionRootExitObservedError(cause, 'kill-delivered')
}
if (attempt.signal.aborted) {
const closed = new Error(`${acpAgentName(deps.spec.agent)} was closed while starting`, {
cause: error
})
throw connection ? closed : new AgentSessionPreSpawnError(closed)
}
// Once the exit is proven, the start's error names a CLI or folder the spawn found missing.
if (cause instanceof Error && connection?.exited) {
withProviderSpawnAbsence(cause, connection.spawnAbsence)
}
if (connection && exitedOnItsOwn && !isAgentSessionPreSpawnError(error)) {
throw new AgentSessionAcquisitionExitProvenError(
withObservedProviderExit(
new Error(connection.stderrTail() || String(error), { cause: error })
)
)
}
throw cause
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
// Unknown delivery never authorizes redelivery under the same ID; only a new user send rotates it.
// Process facts end acknowledgement waits; elapsed time alone proves neither delivery nor rejection.

import { STRUCTURED_AGENT_SESSION_SUBMISSION_MISSING } from '../../../../shared/agent-session/requests/structured-agent-session-send-evidence'

export const DISPATCH_DOUBT_HOST_RESTARTED = 'host_restarted_before_acknowledgement'

export const DISPATCH_DOUBT_PROVIDER_EXITED = 'provider_exited_before_acknowledgement'

export const DISPATCH_DOUBT_PERSISTENCE_FAILED = 'dispatch_result_persistence_failed'

export const DISPATCH_DOUBT_SUBMISSION_MISSING = STRUCTURED_AGENT_SESSION_SUBMISSION_MISSING

// Provider idleness leaves no open turn that could acknowledge the send.
export const DISPATCH_DOUBT_PROVIDER_IDLE = 'provider_idle_before_acknowledgement'

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,3 @@ export const queuedEditHost: QueuedEditHostFixtureModule['queuedEditHost'] = (
)
}
}

export const queuedMessageUpdateDecision: QueuedEditHostFixtureModule['queuedMessageUpdateDecision'] =
decideUpdate
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
hostTestOperationId,
resetHostTestOperationIds
} from './structured-agent-session-host-test-data'
import { STRUCTURED_AGENT_SESSION_IDLE_MS } from '../../termination/structured-agent-session-idle-sweep'

import {
closeTestJournalHostDatabases,
openTestJournalHostDatabase
Expand All @@ -38,7 +38,7 @@ import { createStructuredAgentSessionLogger } from '../structured-agent-session-
import { codexProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'

export const REST_TEST_CALLER = { callerKey: 'client-1' }
export const IDLE_MS = STRUCTURED_AGENT_SESSION_IDLE_MS

export const SWEEP_INTERVAL_MS = 5

export type RestTestAdapter = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ import {
} from './structured-agent-session-send-preparation'
import {
cancelPlan,
promptPlan,
sendPlan,
setOptionPlan,
type MutationPlan
} from './structured-agent-session-mutation-plans'
import { promptPlan } from './structured-agent-session-prompt-plan'
import { agentSessionMutationAdmitsNow } from './structured-agent-session-mutation-admits-now'
import { runQueueableStructuredAgentSessionSend } from '../delivery/structured-agent-session-queued-send'
import { cancelStructuredAgentSessionPrompt } from './structured-agent-session-prompt-cancel'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,19 @@ import {
STRUCTURED_AGENT_SESSION_COMPACT_COMMAND,
structuredAgentSessionCompactBody
} from './structured-agent-session-command-turn'
import { performSend } from './structured-agent-session-turns'
import type {
AgentSessionTurnContext,
AgentSessionReplayContext,
TurnOutcome
import {
performSend,
type AgentSessionTurnContext,
type AgentSessionReplayContext,
type TurnOutcome
} from './structured-agent-session-turns'

import { queuedSendAnswer } from '../delivery/structured-agent-session-queued-send-answer'
import { STOP_COMMAND_RECEIPT } from './structured-agent-session-stop-acceptance'
import { runTargetedCancel } from './structured-agent-session-targeted-cancel'
import type { JournalOperationReceipt } from '../../agent-session-journal/writing/journal-row-writer'
import type { CommandReceiptResult } from '../../agent-session-journal/writing/command-receipt-schema'
import type { JournalRow } from '../../agent-session-journal/durable-rows/journal-row-schema'
export { promptPlan } from './structured-agent-session-prompt-plan'

export type MutationPlan<TValue> = {
method: string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,6 @@ import type {
/** `unknown` (no timely, correlated answer) skips this idle stop and asks again later. */
export type AgentSessionIdleConfirmation = 'idle' | 'busy' | 'unknown'

export type { AgentSessionCancelOutcome } from './structured-agent-session-adapter-stop'
export type {
StructuredAgentSessionChildEndCause,
StructuredAgentSessionStopCause
} from '../termination/structured-agent-session-stop-cause'
import type { AgentJournalDispatchRejection } from '../../../../shared/agent-session/failures/agent-session-failure-words'
import type { AgentSessionExecutionOptions } from '../../../../shared/agent-session/options/agent-session-execution-options'
import type { AgentSessionPromptResponse } from '../../../../shared/agent-session/agent-session-question-answer'
Expand All @@ -58,23 +53,6 @@ import type {
StructuredAgentSessionLiveOptions,
StructuredAgentSessionOptionProjection
} from '../options/structured-agent-session-option-models'
export type { StructuredAgentSessionLiveOptions } from '../options/structured-agent-session-option-models'

export {
AgentSessionAcquisitionRefusal,
AgentSessionPreSpawnError,
AgentSessionPromptAnswerRejectedError,
AgentSessionPromptUnavailableError,
isAgentSessionPreSpawnError,
launchPreparationFailure
} from './structured-agent-session-adapter-errors'
export type { AgentSessionPreSpawnReason } from './structured-agent-session-adapter-errors'

export {
AgentSessionAcquisitionExitProvenError,
AgentSessionAcquisitionExitUnprovenError,
AgentSessionAcquisitionRootExitObservedError
} from '../acquisition/structured-agent-session-acquisition-errors'

export type AgentSessionAcquisition = {
accountRecipe?: ClaudeAccountRecipe
Expand Down
Loading
Loading