mirror of
https://github.com/stablyai/orca.git
synced 2026-11-17 11:24:37 +00:00
* Fork Codex replies from the current history after rewind * Strengthen Codex fork preparation failure coverage * Preserve Codex fork compatibility and original chat guidance * Explain when Codex cannot start for a fork
215 lines
8.0 KiB
TypeScript
215 lines
8.0 KiB
TypeScript
import { agentSessionForkSourceFailureWords } from '../../../src/shared/agent-session/failures/agent-session-failure-copy'
|
|
import { sayMobileAgentSessionFailure } from './agent-session-failure-copy'
|
|
import type { TuiAgent } from '../../../src/shared/agent-launch/catalog/tui-agent'
|
|
import type {
|
|
AgentSessionAttachResult,
|
|
AgentSessionMutationResult
|
|
} from '../../../src/shared/agent-session/agent-session-wire'
|
|
import {
|
|
isDefinitiveAgentSessionCreateRefusal,
|
|
isAgentSessionForkSourceAdmissionRefusal,
|
|
isAgentSessionCreateAdmissionRefusal
|
|
} from '../../../src/shared/agent-session/failures/agent-session-definitive-refusal'
|
|
import {
|
|
createStructuredAgentSessionId,
|
|
structuredAgentSessionCreateParams,
|
|
type StructuredAgentSessionCreateParams,
|
|
type StructuredAgentSessionForkSource
|
|
} from '../../../src/shared/agent-session/structured-agent-session-create'
|
|
import type { StructuredAgentCreateSupportReply } from '../../../src/shared/agent-session/structured-agent-create-support-reply'
|
|
import { TUI_AGENT_DISPLAY_NAMES } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names'
|
|
import { hasRuntimeRpcErrorCode } from '../../../src/shared/runtime-rpc-error-code'
|
|
import type { RpcClient } from '../transport/rpc/rpc-client-contract'
|
|
import {
|
|
structuredAgentSessionCreate,
|
|
structuredAgentSupportProbe
|
|
} from './native-chat/agent-session/mobile-structured-create-operations'
|
|
import { randomV4Uuid } from '../platform/random-v4-uuid'
|
|
import { rememberMobileCreatedStructuredSession } from './mobile-created-structured-sessions'
|
|
|
|
// Partial: the reply is read before it is checked.
|
|
type StructuredCreateSupport = Partial<StructuredAgentCreateSupportReply>
|
|
|
|
const SELECTOR_NOT_RESOLVABLE_CODE = 'selector_not_found'
|
|
const CREATE_SUPPORT_RETRY_DELAYS_MS: readonly number[] = [50, 150, 300]
|
|
|
|
function delay(ms: number): Promise<void> {
|
|
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
}
|
|
|
|
export type MobileStructuredAgentLaunchResult =
|
|
| { kind: 'created'; sessionId: string }
|
|
| { kind: 'unsupported'; reason?: StructuredCreateSupport['reason'] }
|
|
| { kind: 'failed'; message: string }
|
|
| { kind: 'unknown'; message: string }
|
|
|
|
function createParamsFor(
|
|
agent: TuiAgent,
|
|
worktree: string,
|
|
forkFrom: StructuredAgentSessionForkSource | undefined,
|
|
tabPlacement: StructuredAgentSessionCreateParams['tabPlacement']
|
|
): StructuredAgentSessionCreateParams {
|
|
return structuredAgentSessionCreateParams({
|
|
sessionId: createStructuredAgentSessionId(agent, randomV4Uuid),
|
|
worktree,
|
|
agent,
|
|
...(forkFrom ? { forkFrom } : {}),
|
|
...(tabPlacement ? { tabPlacement } : {}),
|
|
randomUuid: randomV4Uuid
|
|
})
|
|
}
|
|
|
|
function unknownCreateResult(agent: TuiAgent, error: unknown): MobileStructuredAgentLaunchResult {
|
|
const message = error instanceof Error ? error.message.trim() : ''
|
|
return { kind: 'unknown', message: message || unconfirmedMessage(agent) }
|
|
}
|
|
|
|
function unconfirmedMessage(agent: TuiAgent): string {
|
|
return `The ${TUI_AGENT_DISPLAY_NAMES[agent]} chat result could not be confirmed.`
|
|
}
|
|
|
|
function failedMessage(agent: TuiAgent): string {
|
|
return `Could not open ${TUI_AGENT_DISPLAY_NAMES[agent]} chat.`
|
|
}
|
|
|
|
// Only definitive refusal permits failure/fallback; uncertain creates may already own a session and must not create a sibling.
|
|
function classifyCreateRefusal(
|
|
agent: TuiAgent,
|
|
code: string,
|
|
message: string
|
|
): MobileStructuredAgentLaunchResult {
|
|
if (!isDefinitiveAgentSessionCreateRefusal(code)) {
|
|
return unknownCreateResult(agent, new Error(message))
|
|
}
|
|
return { kind: 'failed', message: message || failedMessage(agent) }
|
|
}
|
|
|
|
export async function createMobileStructuredAgentSession(
|
|
client: RpcClient,
|
|
worktreeId: string,
|
|
agent: TuiAgent,
|
|
/** Sent only to a host advertising forks. */
|
|
forkFrom?: StructuredAgentSessionForkSource,
|
|
/** Sent only to a host advertising create placement; the replay keeps it. */
|
|
tabPlacement?: StructuredAgentSessionCreateParams['tabPlacement']
|
|
): Promise<MobileStructuredAgentLaunchResult> {
|
|
const worktree = `id:${worktreeId}`
|
|
let supportResponse
|
|
for (let attempt = 0; ; attempt += 1) {
|
|
try {
|
|
supportResponse = await structuredAgentSupportProbe.request(client, { worktree, agent })
|
|
} catch (error) {
|
|
const retryDelayMs = CREATE_SUPPORT_RETRY_DELAYS_MS[attempt]
|
|
if (
|
|
retryDelayMs === undefined ||
|
|
!hasRuntimeRpcErrorCode(error, SELECTOR_NOT_RESOLVABLE_CODE)
|
|
) {
|
|
return { kind: 'unsupported' }
|
|
}
|
|
await delay(retryDelayMs)
|
|
continue
|
|
}
|
|
const retryDelayMs = CREATE_SUPPORT_RETRY_DELAYS_MS[attempt]
|
|
if (
|
|
retryDelayMs !== undefined &&
|
|
hasRuntimeRpcErrorCode(supportResponse, SELECTOR_NOT_RESOLVABLE_CODE)
|
|
) {
|
|
await delay(retryDelayMs)
|
|
continue
|
|
}
|
|
break
|
|
}
|
|
if (
|
|
!supportResponse ||
|
|
typeof supportResponse !== 'object' ||
|
|
typeof supportResponse.ok !== 'boolean' ||
|
|
!supportResponse.ok
|
|
) {
|
|
return { kind: 'unsupported' }
|
|
}
|
|
const support = supportResponse.result as StructuredCreateSupport | null
|
|
if (!support || typeof support !== 'object' || support.supported !== true) {
|
|
return { kind: 'unsupported', reason: support?.reason }
|
|
}
|
|
|
|
const params = createParamsFor(agent, worktree, forkFrom, tabPlacement)
|
|
rememberMobileCreatedStructuredSession(params.envelope.sessionId, worktree)
|
|
let response
|
|
let priorCreateOutcomeUnknown = false
|
|
try {
|
|
response = await structuredAgentSessionCreate.request(client, params, {
|
|
timeoutMs: 15_000,
|
|
budgetSpansConnect: true
|
|
})
|
|
} catch {
|
|
priorCreateOutcomeUnknown = true
|
|
// Replay the durable envelope once so a lost acknowledgement cannot create a sibling.
|
|
try {
|
|
response = await structuredAgentSessionCreate.request(client, params, {
|
|
timeoutMs: 15_000,
|
|
budgetSpansConnect: true
|
|
})
|
|
} catch (retryError) {
|
|
// A second transport error cannot disprove the first attempt committed.
|
|
return unknownCreateResult(agent, retryError)
|
|
}
|
|
}
|
|
|
|
// Inspect malformed replies as unconfirmed rather than classifying them as refusals.
|
|
if (!response || typeof response !== 'object' || typeof response.ok !== 'boolean') {
|
|
return unknownCreateResult(agent, new Error(unconfirmedMessage(agent)))
|
|
}
|
|
if (!response.ok) {
|
|
const error = response.error as { code?: unknown; message?: unknown } | null | undefined
|
|
if (
|
|
!error ||
|
|
typeof error !== 'object' ||
|
|
typeof error.code !== 'string' ||
|
|
typeof error.message !== 'string'
|
|
) {
|
|
return unknownCreateResult(agent, new Error(unconfirmedMessage(agent)))
|
|
}
|
|
return classifyCreateRefusal(agent, error.code, error.message)
|
|
}
|
|
const result = response.result as AgentSessionMutationResult<AgentSessionAttachResult>
|
|
if (!result || typeof result !== 'object' || typeof result.ok !== 'boolean') {
|
|
return unknownCreateResult(agent, new Error(unconfirmedMessage(agent)))
|
|
}
|
|
if (!result.ok) {
|
|
if (
|
|
!result.refusal ||
|
|
typeof result.refusal !== 'object' ||
|
|
typeof result.refusal.code !== 'string' ||
|
|
typeof result.refusal.message !== 'string'
|
|
) {
|
|
return unknownCreateResult(agent, new Error(unconfirmedMessage(agent)))
|
|
}
|
|
if (
|
|
forkFrom &&
|
|
!priorCreateOutcomeUnknown &&
|
|
result.refusal.createAttemptRefusedBeforeCommit === true &&
|
|
(isAgentSessionForkSourceAdmissionRefusal(result.refusal) ||
|
|
isAgentSessionCreateAdmissionRefusal(result.refusal))
|
|
) {
|
|
return {
|
|
kind: 'failed',
|
|
message:
|
|
agentSessionForkSourceFailureWords(
|
|
result.refusal.message,
|
|
TUI_AGENT_DISPLAY_NAMES[agent],
|
|
sayMobileAgentSessionFailure
|
|
) ?? result.refusal.message
|
|
}
|
|
}
|
|
return classifyCreateRefusal(agent, result.refusal.code, result.refusal.message)
|
|
}
|
|
if (
|
|
!result.value ||
|
|
typeof result.value.sessionId !== 'string' ||
|
|
!result.value.sessionId.trim()
|
|
) {
|
|
return unknownCreateResult(agent, new Error(unconfirmedMessage(agent)))
|
|
}
|
|
return { kind: 'created', sessionId: result.value.sessionId }
|
|
}
|