mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
Decide a person's Stop for Claude results at the write position
A result whose reading a Stop changes writes both readings as one stop-decided resolution; the writer checks the saved Stop at its position, keeps one and reports which. The result and plugin-input failure paths share it, and the producer no longer reads persisted Stop state.
This commit is contained in:
@@ -14,7 +14,7 @@ import {
|
||||
claudeTokenUsage,
|
||||
type ClaudeMainThreadModel
|
||||
} from './claude-context-usage'
|
||||
import type { ClaudeOpenTurn } from './claude-open-turn'
|
||||
import type { ClaudeOpenTurn, ClaudeStoppedTurnEnd } from './claude-open-turn'
|
||||
import { claudeRecord, claudeText } from './structured/journal/claude-structured-item-translation'
|
||||
import type { ClaudeTurnEnd } from './claude-turn-lifecycle-item'
|
||||
import { isRootClaudeFrame } from './claude-turn-opening'
|
||||
@@ -145,7 +145,11 @@ export class ClaudeContextFacts {
|
||||
)
|
||||
}
|
||||
|
||||
settle(message: Record<string, unknown>, end: ClaudeTurnEnd): void {
|
||||
settle(
|
||||
message: Record<string, unknown>,
|
||||
end: ClaudeTurnEnd,
|
||||
stopped?: ClaudeStoppedTurnEnd
|
||||
): void {
|
||||
const tokens = this.windowReported
|
||||
? null
|
||||
: claudeContextWindowFromResult(message, this.mainModel)
|
||||
@@ -156,12 +160,12 @@ export class ClaudeContextFacts {
|
||||
}
|
||||
const settled = this.turn.identity
|
||||
if (settled === null) {
|
||||
this.turn.settle(end)
|
||||
this.turn.settle(end, undefined, stopped)
|
||||
if (facts) {
|
||||
this.write(facts)
|
||||
}
|
||||
} else {
|
||||
this.turn.settle(end, facts)
|
||||
this.turn.settle(end, facts, stopped)
|
||||
}
|
||||
this.requestReport(settled)
|
||||
}
|
||||
|
||||
@@ -77,7 +77,6 @@ export function journal({ deferred = false } = {}) {
|
||||
}
|
||||
})
|
||||
const sink: StructuredAgentSessionEventSink = {
|
||||
journalStopDecidesTurn: (turnId, at) => personStopDecidesTurn(stopState, turnId, at),
|
||||
appendItem: (...args) => run(() => appendItem(...args)),
|
||||
tryReviseResolvedItem: revise,
|
||||
tryReviseResolvedItemAndPublish: revise,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
|
||||
import { estimateStructuredAgentSessionItemBytes } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-estimate'
|
||||
import { writeClaudeStopReadings } from './claude-stop-readings'
|
||||
import type { ClaudeGoalSettlement } from './claude-thread-goal'
|
||||
|
||||
/** A goal a person's Stop could keep from completing is decided at the write position. */
|
||||
export function journalClaudeGoal(
|
||||
sink: StructuredAgentSessionEventSink,
|
||||
goal: ClaudeGoalSettlement,
|
||||
turnId: string | null,
|
||||
endedAt: number,
|
||||
turnScope: AgentJournalTurnScope
|
||||
): void {
|
||||
const { ran, stopped, adopt } = goal
|
||||
if (stopped !== undefined && turnId !== null) {
|
||||
const literal = (row: typeof ran) => row && { kind: 'literal' as const, ...row }
|
||||
const bytes = (row: typeof ran) =>
|
||||
row ? estimateStructuredAgentSessionItemBytes(row.identity, row.body) : 0
|
||||
const written = writeClaudeStopReadings(
|
||||
sink,
|
||||
{ turnId, endedAt },
|
||||
{
|
||||
ran: literal(ran),
|
||||
stopped: literal(stopped),
|
||||
reservedBytes: Math.max(bytes(ran), bytes(stopped))
|
||||
},
|
||||
{ turnScope },
|
||||
{ publish: true, ...(adopt ? { onDecided: adopt } : {}) }
|
||||
)
|
||||
if (written) {
|
||||
return
|
||||
}
|
||||
}
|
||||
adopt?.(false)
|
||||
if (ran) {
|
||||
sink.appendItem(ran.identity, ran.body, { turnScope })
|
||||
sink.publish()
|
||||
}
|
||||
}
|
||||
@@ -10,13 +10,38 @@ import {
|
||||
type ClaudeCurrentTurn,
|
||||
type ClaudeTurnEnd
|
||||
} from './claude-turn-lifecycle-item'
|
||||
import { writeAgentJournalTurnRow } from '../native-chat/agent-session-timeline/agent-journal-turn-row-revision'
|
||||
import type { ClaudeCommandTurn } from './claude-command-turn'
|
||||
import { createClaudeTurnOpener, type ClaudeTurnSource } from './claude-turn-opening'
|
||||
import { refineClaudeQuotaTurnEnd } from './claude-terminal-failure'
|
||||
import { claudeQuotaTurnEndResolution, refineClaudeQuotaTurnEnd } from './claude-terminal-failure'
|
||||
import { writeClaudeStopReadings, type ClaudeStopCheck } from './claude-stop-readings'
|
||||
import {
|
||||
agentJournalTurnRowReservedBytes,
|
||||
writeAgentJournalTurnRow
|
||||
} from '../native-chat/agent-session-timeline/agent-journal-turn-row-revision'
|
||||
import type { JournalTimelineItemResolution } from '../native-chat/agent-session-journal/writing/journal-timeline-resolution'
|
||||
import type { ClaudeUsageLimitEvidence } from './claude-usage-limits'
|
||||
import type { ClaudeStartedSend } from './structured/claude-structured-session-state'
|
||||
|
||||
/** The ending a person's Stop at the write position would record instead. */
|
||||
export type ClaudeStoppedTurnEnd = { check: ClaudeStopCheck; end: ClaudeTurnEnd }
|
||||
|
||||
function claudeTurnEndResolution(
|
||||
turn: ClaudeCurrentTurn,
|
||||
end: ClaudeTurnEnd,
|
||||
contextUsage: AgentSessionContextUsage | undefined,
|
||||
quotaEnd: boolean
|
||||
): { resolution: JournalTimelineItemResolution; reservedBytes: number } {
|
||||
const item = claudeTurnLifecycleItem(turn, end)
|
||||
const write = { lifecycle: item.body, ...(contextUsage ? { contextUsage } : {}) }
|
||||
const target = { identity: item.identity }
|
||||
return {
|
||||
resolution: quotaEnd
|
||||
? claudeQuotaTurnEndResolution(item.identity, write)
|
||||
: { kind: 'turn-row', target, write },
|
||||
reservedBytes: agentJournalTurnRowReservedBytes(target, write)
|
||||
}
|
||||
}
|
||||
|
||||
export type ClaudeOpenTurnDeps = {
|
||||
sink: StructuredAgentSessionEventSink
|
||||
/** The superseded turn's spawn calls get no announcement now. */
|
||||
@@ -167,19 +192,36 @@ export class ClaudeOpenTurn {
|
||||
}
|
||||
|
||||
/** Settle activity and context facts in the same turn revision. */
|
||||
settle(end: ClaudeTurnEnd, contextUsage?: AgentSessionContextUsage): void {
|
||||
const quotaEnd =
|
||||
settle(
|
||||
end: ClaudeTurnEnd,
|
||||
contextUsage?: AgentSessionContextUsage,
|
||||
stopped?: ClaudeStoppedTurnEnd
|
||||
): void {
|
||||
const quotaEnd = (ending: ClaudeTurnEnd) =>
|
||||
this.current !== null &&
|
||||
end.outcome === undefined &&
|
||||
ending.outcome === undefined &&
|
||||
this.usageLimitEvidence?.cause === 'quota'
|
||||
this.suppressReopenOnFailure(quotaEnd)
|
||||
const readings = {
|
||||
ran: quotaEnd(end),
|
||||
stopped: stopped !== undefined && quotaEnd(stopped.end)
|
||||
}
|
||||
this.suppressReopenOnFailure(readings.ran || readings.stopped)
|
||||
this.cycleWorkObserved = false
|
||||
this.inputChoiceWorkObserved = false
|
||||
this.usageLimitEvidence = null
|
||||
// End suppressed work even when no turn is open.
|
||||
this.deps.endOpenWork(end.completedAt)
|
||||
if (this.current) {
|
||||
this.publish(this.current, end, contextUsage, quotaEnd)
|
||||
this.publish(
|
||||
this.current,
|
||||
end,
|
||||
contextUsage,
|
||||
readings.ran,
|
||||
stopped && {
|
||||
...stopped,
|
||||
quotaEnd: readings.stopped
|
||||
}
|
||||
)
|
||||
this.current = null
|
||||
}
|
||||
this.deps.sink.setActivity?.(null)
|
||||
@@ -202,10 +244,29 @@ export class ClaudeOpenTurn {
|
||||
turn: ClaudeCurrentTurn,
|
||||
end?: ClaudeTurnEnd,
|
||||
contextUsage?: AgentSessionContextUsage,
|
||||
quotaEnd = false
|
||||
quotaEnd = false,
|
||||
stopped?: ClaudeStoppedTurnEnd & { quotaEnd: boolean }
|
||||
): void {
|
||||
const item = claudeTurnLifecycleItem(turn, end)
|
||||
const write = { lifecycle: item.body, ...(contextUsage ? { contextUsage } : {}) }
|
||||
if (end && stopped) {
|
||||
const ran = claudeTurnEndResolution(turn, end, contextUsage, quotaEnd)
|
||||
const other = claudeTurnEndResolution(turn, stopped.end, contextUsage, stopped.quotaEnd)
|
||||
const readings = {
|
||||
ran: ran.resolution,
|
||||
stopped: other.resolution,
|
||||
reservedBytes: Math.max(ran.reservedBytes, other.reservedBytes)
|
||||
}
|
||||
const options = { ...item.options, lifecycle: true, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
if (
|
||||
writeClaudeStopReadings(this.deps.sink, stopped.check, readings, options, {
|
||||
publish: false
|
||||
})
|
||||
) {
|
||||
this.deps.sink.publish({ coalescingKey: item.publishCoalescingKey })
|
||||
return
|
||||
}
|
||||
}
|
||||
if (quotaEnd && refineClaudeQuotaTurnEnd(this.deps.sink, item.identity, write)) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ import { PROVIDER_EXIT_ROW_PREFIX } from '../../shared/agent-session/lifecycle/a
|
||||
import { agentSessionFailureWords } from '../../shared/agent-session/failures/agent-session-failure-words'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
|
||||
import type { ClaudeOpenTurn } from './claude-open-turn'
|
||||
import { writeClaudeStopReadings, type ClaudeStopCheck } from './claude-stop-readings'
|
||||
import { estimateStructuredAgentSessionItemBytes } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-estimate'
|
||||
import type { ClaudeStructuredSessionEvent } from './structured/claude-structured-session-state'
|
||||
|
||||
export function journalClaudePluginInputFailure({
|
||||
@@ -14,7 +16,7 @@ export function journalClaudePluginInputFailure({
|
||||
event: Extract<ClaudeStructuredSessionEvent, { type: 'retiring' }>
|
||||
turn: ClaudeOpenTurn
|
||||
sink: StructuredAgentSessionEventSink
|
||||
finish: (observedAt: number, failed: boolean) => void
|
||||
finish: (observedAt: number, failed: boolean, stopCheck: ClaudeStopCheck | null) => void
|
||||
}): void {
|
||||
if (!turn.isOpen && event.unopenedSend) {
|
||||
// A failed dispatched action needs a turn outcome without claiming a provider echo or acceptance.
|
||||
@@ -34,36 +36,45 @@ export function journalClaudePluginInputFailure({
|
||||
)
|
||||
}
|
||||
const scope = turn.turnScope
|
||||
const stopped = turn.id !== null && sink.journalStopDecidesTurn?.(turn.id, event.observedAt)
|
||||
finish(event.observedAt, !stopped)
|
||||
if (stopped) {
|
||||
return
|
||||
}
|
||||
// A person's Stop at the write position keeps a plain ending and no failure notice.
|
||||
const stopCheck = turn.id !== null ? { turnId: turn.id, endedAt: event.observedAt } : null
|
||||
finish(event.observedAt, true, stopCheck)
|
||||
// Physical-exit settlement revises this same row after proof; it must not add another notice.
|
||||
sink.appendItem(
|
||||
{
|
||||
provider: 'orca',
|
||||
clientMessageId: `${PROVIDER_EXIT_ROW_PREFIX}${event.sessionId}:${event.fence}:${event.acquisitionGeneration}`
|
||||
},
|
||||
{
|
||||
kind: 'status',
|
||||
tone: 'error',
|
||||
...agentSessionFailureWords(event.failure, { surface: 'row', agentName: 'Claude' })
|
||||
},
|
||||
{ turnScope: scope, lifecycle: true, observedAt: event.observedAt }
|
||||
)
|
||||
const identity = {
|
||||
provider: 'orca' as const,
|
||||
clientMessageId: `${PROVIDER_EXIT_ROW_PREFIX}${event.sessionId}:${event.fence}:${event.acquisitionGeneration}`
|
||||
}
|
||||
const body = {
|
||||
kind: 'status' as const,
|
||||
tone: 'error' as const,
|
||||
...agentSessionFailureWords(event.failure, { surface: 'row', agentName: 'Claude' })
|
||||
}
|
||||
const options = { turnScope: scope, lifecycle: true, observedAt: event.observedAt }
|
||||
const readings = {
|
||||
ran: { kind: 'literal' as const, identity, body },
|
||||
stopped: null,
|
||||
reservedBytes: estimateStructuredAgentSessionItemBytes(identity, body)
|
||||
}
|
||||
if (
|
||||
!stopCheck ||
|
||||
!writeClaudeStopReadings(sink, stopCheck, readings, options, { publish: false })
|
||||
) {
|
||||
sink.appendItem(identity, body, options)
|
||||
}
|
||||
sink.publish({ lifecycle: true })
|
||||
}
|
||||
|
||||
export function settleClaudeInterruptedTurn(
|
||||
turn: ClaudeOpenTurn,
|
||||
observedAt: number,
|
||||
failed: boolean
|
||||
failed: boolean,
|
||||
stopCheck: ClaudeStopCheck | null = null
|
||||
): void {
|
||||
turn.settle({
|
||||
state: 'interrupted',
|
||||
...(failed ? { outcome: 'failure' as const } : {}),
|
||||
completedAt: observedAt
|
||||
})
|
||||
const plain = { state: 'interrupted' as const, completedAt: observedAt }
|
||||
turn.settle(
|
||||
failed ? { ...plain, outcome: 'failure' } : plain,
|
||||
undefined,
|
||||
failed && stopCheck ? { check: stopCheck, end: plain } : undefined
|
||||
)
|
||||
turn.suppressReopen()
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { writeClaudeTerminalFailure } from './claude-terminal-failure'
|
||||
import { claudeResultOutcome } from './claude-result-outcome'
|
||||
import { writeClaudeStopReadings } from './claude-stop-readings'
|
||||
import { journalClaudeGoal } from './claude-goal-journaling'
|
||||
import { estimateStructuredAgentSessionItemBytes } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-estimate'
|
||||
import type { ClaudeContextFacts } from './claude-context-facts'
|
||||
import { claudeCommandEnd } from './claude-command-turn'
|
||||
import type { ClaudeMessageJournalContext } from './claude-message-journaling'
|
||||
@@ -70,7 +74,11 @@ export function journalClaudeResult(
|
||||
const usageEvidence = turn.usageLimitEvidence
|
||||
const endedTurnStartedAt = turn.startedAt
|
||||
const turnId = settlesTurn ? turn.id : null
|
||||
const leftToStop = turnId !== null && sink.journalStopDecidesTurn?.(turnId, observedAt) === true
|
||||
// A Stop changes only an unaborted error's reading; the writer decides it at its position.
|
||||
const stopCheck =
|
||||
turnId !== null && claudeResultOutcome(message) !== claudeResultOutcome(message, true)
|
||||
? { turnId, endedAt: observedAt }
|
||||
: null
|
||||
// Retry owed prompt cancellations before a command result can return.
|
||||
if (settlesTurn) {
|
||||
prompts.retryPendingCancellations()
|
||||
@@ -80,12 +88,11 @@ export function journalClaudeResult(
|
||||
if (command && !commandResult) {
|
||||
return
|
||||
}
|
||||
const failure = claudeResultFailure(message, leftToStop)
|
||||
const failure = claudeResultFailure(message)
|
||||
// A command's quota cause needs its own failed verdict, not only a failed envelope.
|
||||
const compactionFailure =
|
||||
command &&
|
||||
commandResult?.end.outcome === 'failure' &&
|
||||
!leftToStop &&
|
||||
(command.failed !== null || failure !== null)
|
||||
? { ...command.failed, rejections: command.rejections }
|
||||
: undefined
|
||||
@@ -98,9 +105,24 @@ export function journalClaudeResult(
|
||||
const terminalFailure = notice || usageLimit
|
||||
if (command && commandResult?.row && !terminalFailure) {
|
||||
sink.appendItem(command.resultIdentity, commandResult.row, { turnScope: endedTurnScope })
|
||||
} else if (command && commandResult?.row && stopCheck) {
|
||||
// Stopped, the command's own result row stands in for the failure.
|
||||
const { resultIdentity: identity } = command
|
||||
const body = commandResult.row
|
||||
writeClaudeStopReadings(
|
||||
sink,
|
||||
stopCheck,
|
||||
{
|
||||
ran: null,
|
||||
stopped: { kind: 'literal', identity, body },
|
||||
reservedBytes: estimateStructuredAgentSessionItemBytes(identity, body)
|
||||
},
|
||||
{ turnScope: endedTurnScope },
|
||||
{ publish: false }
|
||||
)
|
||||
}
|
||||
if (terminalFailure && endedTurnIdentity) {
|
||||
writeClaudeTerminalFailure(sink, endedTurnIdentity, terminalFailure)
|
||||
writeClaudeTerminalFailure(sink, endedTurnIdentity, terminalFailure, stopCheck)
|
||||
}
|
||||
if (settlesTurn) {
|
||||
turn.suppressReopenOnFailure(message.is_error === true)
|
||||
@@ -108,7 +130,10 @@ export function journalClaudeResult(
|
||||
streamedText.finish({ completedAt: observedAt })
|
||||
context.settle(
|
||||
message,
|
||||
commandResult?.end ?? claudeTurnEndForResult(message, observedAt, leftToStop)
|
||||
commandResult?.end ?? claudeTurnEndForResult(message, observedAt),
|
||||
stopCheck && !commandResult
|
||||
? { check: stopCheck, end: claudeTurnEndForResult(message, observedAt, true) }
|
||||
: undefined
|
||||
)
|
||||
streamedBlocks.clear()
|
||||
streamedText.settle()
|
||||
@@ -117,14 +142,13 @@ export function journalClaudeResult(
|
||||
message,
|
||||
{
|
||||
backgroundWork: goalBackgroundWork(),
|
||||
stoppedByPerson: leftToStop,
|
||||
stoppable: turnId !== null,
|
||||
turnStartedAt: endedTurnStartedAt
|
||||
},
|
||||
observedAt
|
||||
)
|
||||
if (goal) {
|
||||
sink.appendItem(goal.identity, goal.body, { turnScope: endedTurnScope })
|
||||
sink.publish()
|
||||
journalClaudeGoal(sink, goal, turnId, observedAt, endedTurnScope)
|
||||
}
|
||||
const kind = claudeProviderFrameKind(message)
|
||||
if (terminalFailure && endedTurnIdentity) {
|
||||
@@ -152,7 +176,14 @@ export function journalClaudeResult(
|
||||
{ reportsFailure: failure !== null },
|
||||
settlesTurn
|
||||
? () => ({ turnScope: endedTurnScope })
|
||||
: corrections.stampFor(claudeFrameParentRef(message))
|
||||
: corrections.stampFor(claudeFrameParentRef(message)),
|
||||
// Stopped, a known result kind needs no row; an unknown one keeps its plain disclosure.
|
||||
stopCheck && failure
|
||||
? {
|
||||
check: stopCheck,
|
||||
stopped: isSettledClaudeResultKind(kind) ? null : { options: { reportsFailure: false } }
|
||||
}
|
||||
: undefined
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { JournalTimelineItemResolution } from '../native-chat/agent-session-journal/writing/journal-timeline-resolution'
|
||||
import type {
|
||||
StructuredAgentSessionEventSink,
|
||||
StructuredAgentSessionRevisionOptions
|
||||
} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
|
||||
|
||||
/** The turn a person's Stop may have decided, and when the provider ended it. */
|
||||
export type ClaudeStopCheck = { turnId: string; endedAt: number }
|
||||
|
||||
export type ClaudeStopReadings = {
|
||||
ran: JournalTimelineItemResolution | null
|
||||
stopped: JournalTimelineItemResolution | null
|
||||
reservedBytes: number
|
||||
}
|
||||
|
||||
/** Submit a row's two readings; the writer keeps the one a Stop at its position selects. */
|
||||
export function writeClaudeStopReadings(
|
||||
sink: StructuredAgentSessionEventSink,
|
||||
check: ClaudeStopCheck,
|
||||
readings: ClaudeStopReadings,
|
||||
options: StructuredAgentSessionRevisionOptions,
|
||||
{ publish, onDecided }: { publish: boolean; onDecided?: (stopped: boolean) => void }
|
||||
): boolean {
|
||||
const revise = publish ? sink.tryReviseResolvedItemAndPublish : sink.tryReviseResolvedItem
|
||||
if (!revise) {
|
||||
return false
|
||||
}
|
||||
revise.call(
|
||||
sink,
|
||||
readings.reservedBytes,
|
||||
{ kind: 'stop-decided', ...check, ran: readings.ran, stopped: readings.stopped },
|
||||
options,
|
||||
onDecided && ((outcome) => onDecided(outcome.stopped === true))
|
||||
)
|
||||
return true
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
agentJournalTurnRowReservedBytes,
|
||||
type AgentJournalTurnRowWrite
|
||||
} from '../native-chat/agent-session-timeline/agent-journal-turn-row-revision'
|
||||
import type { JournalTimelineItemResolution } from '../native-chat/agent-session-journal/writing/journal-timeline-resolution'
|
||||
import { writeClaudeStopReadings, type ClaudeStopCheck } from './claude-stop-readings'
|
||||
|
||||
function claudeTerminalFailureIdentity(turnItemId: string): AgentJournalItemIdentity {
|
||||
return { provider: 'orca', clientMessageId: `terminal-failure:claude:${turnItemId}` }
|
||||
@@ -16,7 +18,8 @@ const CLAUDE_VOICE = { agentName: 'Claude', provider: 'claude' } as const
|
||||
export function writeClaudeTerminalFailure(
|
||||
sink: StructuredAgentSessionEventSink,
|
||||
identity: AgentJournalItemIdentity,
|
||||
body: AgentJournalItemBody
|
||||
body: AgentJournalItemBody,
|
||||
stopCheck: ClaudeStopCheck | null = null
|
||||
): void {
|
||||
const turnItemId = agentJournalItemKey(identity)
|
||||
const failureIdentity = claudeTerminalFailureIdentity(turnItemId)
|
||||
@@ -28,12 +31,41 @@ export function writeClaudeTerminalFailure(
|
||||
return
|
||||
}
|
||||
const reservedBytes = Buffer.byteLength(JSON.stringify({ failureIdentity, body }), 'utf8') + 8192
|
||||
revise.call(
|
||||
sink,
|
||||
reservedBytes,
|
||||
{ kind: 'turn-failure', identity: failureIdentity, body, voice: CLAUDE_VOICE },
|
||||
options
|
||||
)
|
||||
const failure = {
|
||||
kind: 'turn-failure',
|
||||
identity: failureIdentity,
|
||||
body,
|
||||
voice: CLAUDE_VOICE
|
||||
} as const
|
||||
// A person's Stop leaves no failure notice.
|
||||
if (
|
||||
stopCheck &&
|
||||
writeClaudeStopReadings(
|
||||
sink,
|
||||
stopCheck,
|
||||
{ ran: failure, stopped: null, reservedBytes },
|
||||
options,
|
||||
{ publish: true }
|
||||
)
|
||||
) {
|
||||
return
|
||||
}
|
||||
revise.call(sink, reservedBytes, failure, options)
|
||||
}
|
||||
|
||||
/** The writer chooses the quota ending's outcome after its failure row and any Stop. */
|
||||
export function claudeQuotaTurnEndResolution(
|
||||
identity: AgentJournalItemIdentity,
|
||||
write: AgentJournalTurnRowWrite
|
||||
): Extract<JournalTimelineItemResolution, { kind: 'quota-turn-end' }> {
|
||||
return {
|
||||
kind: 'quota-turn-end',
|
||||
identity,
|
||||
failureItemId: agentJournalItemKey(
|
||||
claudeTerminalFailureIdentity(agentJournalItemKey(identity))
|
||||
),
|
||||
write
|
||||
}
|
||||
}
|
||||
|
||||
// Refine only the ending row after its quota and any person Stop have landed.
|
||||
@@ -49,14 +81,7 @@ export function refineClaudeQuotaTurnEnd(
|
||||
revise.call(
|
||||
sink,
|
||||
agentJournalTurnRowReservedBytes({ identity }, write),
|
||||
{
|
||||
kind: 'quota-turn-end',
|
||||
identity,
|
||||
failureItemId: agentJournalItemKey(
|
||||
claudeTerminalFailureIdentity(agentJournalItemKey(identity))
|
||||
),
|
||||
write
|
||||
},
|
||||
claudeQuotaTurnEndResolution(identity, write),
|
||||
{ turnScope: { kind: 'thread' }, lifecycle: true }
|
||||
)
|
||||
return true
|
||||
|
||||
@@ -56,6 +56,13 @@ function goalRow(text: string, goal: AgentJournalThreadGoal | null): GoalStatusB
|
||||
}
|
||||
|
||||
type GoalRowWrite = { identity: AgentJournalItemIdentity; body: GoalStatusBody }
|
||||
|
||||
/** A settled goal's row; with `stopped`, the writer picks and `adopt` records its reading. */
|
||||
export type ClaudeGoalSettlement = {
|
||||
ran: GoalRowWrite | null
|
||||
stopped?: GoalRowWrite | null
|
||||
adopt?: (stopped: boolean) => void
|
||||
}
|
||||
type SavedGoal = {
|
||||
goal: AgentJournalThreadGoal | null
|
||||
row: { identity: AgentJournalItemIdentity; text: string } | null
|
||||
@@ -128,11 +135,12 @@ export class ClaudeThreadGoal {
|
||||
result: Record<string, unknown>,
|
||||
end: {
|
||||
backgroundWork: ClaudeGoalBackgroundWork
|
||||
stoppedByPerson: boolean
|
||||
/** Whether a person's Stop could have decided the ending turn. */
|
||||
stoppable: boolean
|
||||
turnStartedAt: number | null
|
||||
},
|
||||
observedAt: number
|
||||
): GoalRowWrite | null {
|
||||
): ClaudeGoalSettlement | null {
|
||||
if (!isRootClaudeFrame(result)) {
|
||||
return null
|
||||
}
|
||||
@@ -151,25 +159,40 @@ export class ClaudeThreadGoal {
|
||||
result.subtype === 'success' &&
|
||||
result.is_error !== true &&
|
||||
(result.terminal_reason === undefined || result.terminal_reason === 'completed') &&
|
||||
end.backgroundWork === 'exited' &&
|
||||
!end.stoppedByPerson
|
||||
const next: AgentJournalThreadGoal = {
|
||||
end.backgroundWork === 'exited'
|
||||
const reading = (status: 'complete' | 'active'): AgentJournalThreadGoal => ({
|
||||
...goal,
|
||||
status: met ? 'complete' : 'active',
|
||||
status,
|
||||
timeUsedSeconds: goal.timeUsedSeconds + Math.max(0, Math.floor((observedAt - since) / 1000)),
|
||||
updatedAt: observedAt
|
||||
})
|
||||
const active = reading('active')
|
||||
// Reuse the persisted row identity across restarts.
|
||||
const activeRow = this.row
|
||||
? { identity: this.row.identity, body: goalRow(this.row.text, active) }
|
||||
: null
|
||||
this.known = active
|
||||
if (!met) {
|
||||
return { ran: activeRow }
|
||||
}
|
||||
this.known = next
|
||||
if (met) {
|
||||
this.row = null
|
||||
return sessionId && uuid
|
||||
const complete = reading('complete')
|
||||
const completeRow =
|
||||
sessionId && uuid
|
||||
? {
|
||||
identity: { provider: 'claude', sessionId, uuid: `${uuid}:goal` },
|
||||
body: goalRow(`Goal complete: ${goal.objective}`, next)
|
||||
identity: { provider: 'claude' as const, sessionId, uuid: `${uuid}:goal` },
|
||||
body: goalRow(`Goal complete: ${goal.objective}`, complete)
|
||||
}
|
||||
: null
|
||||
const adopt = (stopped: boolean) => {
|
||||
if (!stopped && this.known === active) {
|
||||
this.known = complete
|
||||
this.row = null
|
||||
}
|
||||
}
|
||||
// Reuse the persisted row identity across restarts.
|
||||
return this.row ? { identity: this.row.identity, body: goalRow(this.row.text, next) } : null
|
||||
if (!end.stoppable) {
|
||||
adopt(false)
|
||||
return { ran: completeRow }
|
||||
}
|
||||
return { ran: completeRow, stopped: activeRow, adopt }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/ag
|
||||
import { personStopDecidesTurn } from '../../native-chat/agent-session-journal/context-epochs/journal-stop-turn-end'
|
||||
import { createJournalReducerState } from '../../native-chat/agent-session-journal/projection/journal-reducer'
|
||||
import { ClaudeControlRequestError } from '../claude-agent-sdk-control-requests'
|
||||
import { journalTimelineItemsView } from '../../native-chat/agent-session-journal/writing/journal-timeline-view'
|
||||
import { resolveJournalTimelineItem } from '../../native-chat/agent-session-journal/writing/journal-timeline-resolution'
|
||||
import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
|
||||
import {
|
||||
PROVIDER_SESSION_ID,
|
||||
USER_MESSAGE,
|
||||
@@ -33,6 +36,32 @@ async function runningChat(claude: ReturnType<typeof fakeClaude>): Promise<{
|
||||
const bodies = new Map<string, AgentJournalItemBody>()
|
||||
const journal = createJournalReducerState('session-1', 'epoch-1')
|
||||
const adapter = adapterFor(claude)
|
||||
const view = journalTimelineItemsView(
|
||||
(itemId) => {
|
||||
const body = bodies.get(itemId)
|
||||
return body ? { itemId, revision: 1, body, sequence: 1, observedAt: 1 } : null
|
||||
},
|
||||
() => [],
|
||||
(turnId, endedAt) => personStopDecidesTurn(journal, turnId, endedAt)
|
||||
)
|
||||
const revise: NonNullable<StructuredAgentSessionEventSink['tryReviseResolvedItem']> = (
|
||||
reservedBytes,
|
||||
resolution,
|
||||
options,
|
||||
onOutcome
|
||||
) => {
|
||||
const result = resolveJournalTimelineItem(view, resolution, options.turnScope, reservedBytes)
|
||||
const stopped = result.stopped ? { stopped: true as const } : {}
|
||||
if (result.kind === 'resolved') {
|
||||
bodies.set(agentJournalItemKey(result.item.identity), result.item.body)
|
||||
}
|
||||
onOutcome?.(
|
||||
result.kind === 'resolved'
|
||||
? { kind: 'committed', wrote: true, ...stopped }
|
||||
: { kind: 'dropped', ...stopped }
|
||||
)
|
||||
return { accepted: true }
|
||||
}
|
||||
await adapter.acquire({
|
||||
identity: identityFor(),
|
||||
fence: 7,
|
||||
@@ -41,7 +70,9 @@ async function runningChat(claude: ReturnType<typeof fakeClaude>): Promise<{
|
||||
appendItem: (identity, body) => bodies.set(agentJournalItemKey(identity), body),
|
||||
appendTombstone: (identity) => bodies.delete(agentJournalItemKey(identity)),
|
||||
publish: vi.fn(),
|
||||
journalStopDecidesTurn: (turnId, endedAt) => personStopDecidesTurn(journal, turnId, endedAt)
|
||||
// Resolve revisions as the writer would, against this chat's recorded Stop.
|
||||
tryReviseResolvedItem: revise,
|
||||
tryReviseResolvedItemAndPublish: revise
|
||||
}
|
||||
})
|
||||
await adapter.dispatch({
|
||||
|
||||
@@ -18,6 +18,7 @@ import { ClaudeProvisionalRowCorrections } from '../../claude-provisional-row-co
|
||||
import { createClaudeStreamedThinking } from '../../claude-streamed-thinking'
|
||||
import { ClaudeSubagentIdentities } from '../../claude-subagent-identities'
|
||||
import { ClaudeJournaledSubagents } from '../../claude-subagent-journaled-identities'
|
||||
import type { ClaudeStopCheck } from '../../claude-stop-readings'
|
||||
import { createClaudeStreamedBlockRegistry } from '../../claude-streamed-block-identity'
|
||||
import { createClaudeStreamedTextCheckpoints } from '../../claude-streamed-text-checkpoints'
|
||||
import {
|
||||
@@ -151,12 +152,16 @@ export function createClaudeJournalTranslator(
|
||||
acceptStartupFailure: deps.acceptStartupFailure
|
||||
}
|
||||
|
||||
const finish = (observedAt: number, failed: boolean): void => {
|
||||
const finish = (
|
||||
observedAt: number,
|
||||
failed: boolean,
|
||||
stopCheck: ClaudeStopCheck | null = null
|
||||
): void => {
|
||||
prompts.retryPendingCancellations()
|
||||
flush()
|
||||
corrections.abandon()
|
||||
backgroundTasks.settleSession()
|
||||
settleClaudeInterruptedTurn(turn, observedAt, failed)
|
||||
settleClaudeInterruptedTurn(turn, observedAt, failed, stopCheck)
|
||||
}
|
||||
return {
|
||||
handle: withClaudeConversationContent((event) => {
|
||||
|
||||
@@ -29,6 +29,8 @@ import {
|
||||
isClaudeToolResultContent
|
||||
} from '../../../../shared/claude-tool-content'
|
||||
import type { ClaudeRowStamp } from '../../claude-provisional-row-corrections'
|
||||
import { writeClaudeStopReadings, type ClaudeStopCheck } from '../../claude-stop-readings'
|
||||
import { estimateStructuredAgentSessionItemBytes } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-estimate'
|
||||
import {
|
||||
CLAUDE_API_RETRY_FRAME_KIND,
|
||||
claudeApiRetryRowBody,
|
||||
@@ -138,13 +140,18 @@ export function createClaudeProviderFrameFallback(
|
||||
beforeAppend?: () => void,
|
||||
options?: UnhandledProviderFrameJournalItemOptions,
|
||||
/** Attribute child output; omit for the session's own agent. */
|
||||
stamp?: ClaudeRowStamp
|
||||
stamp?: ClaudeRowStamp,
|
||||
/** A Stop at the write position records `stopped` instead; null writes nothing. */
|
||||
stopReading?: {
|
||||
check: ClaudeStopCheck
|
||||
stopped: { options?: UnhandledProviderFrameJournalItemOptions } | null
|
||||
}
|
||||
) => boolean
|
||||
} {
|
||||
let sequence = 0
|
||||
const retryRun = createClaudeApiRetryRuns()
|
||||
return {
|
||||
append: (kind, payload, display, beforeAppend, options, stamp) => {
|
||||
append: (kind, payload, display, beforeAppend, options, stamp, stopReading) => {
|
||||
sequence += 1
|
||||
const retrying = kind === CLAUDE_API_RETRY_FRAME_KIND ? claudeRecord(payload) : null
|
||||
if (retrying) {
|
||||
@@ -188,13 +195,37 @@ export function createClaudeProviderFrameFallback(
|
||||
provider: 'orca',
|
||||
clientMessageId: `provider-frame:claude:${acquisitionId}:${sequence}`
|
||||
} as const
|
||||
const body: AgentJournalStatusItem =
|
||||
const shown = (translatedBody: typeof translated.body): AgentJournalStatusItem =>
|
||||
display && typeof display === 'object'
|
||||
? { ...translated.body, ...display }
|
||||
? { ...translatedBody, ...display }
|
||||
: typeof display === 'string' && display
|
||||
? { ...translated.body, text: display }
|
||||
: translated.body
|
||||
sink.appendItem(identity, body, stamp?.(identity, body) ?? { turnScope: turnScope() })
|
||||
? { ...translatedBody, text: display }
|
||||
: translatedBody
|
||||
const body = shown(translated.body)
|
||||
const rowOptions = stamp?.(identity, body) ?? { turnScope: turnScope() }
|
||||
if (stopReading) {
|
||||
const plain =
|
||||
stopReading.stopped &&
|
||||
unhandledProviderFrameJournalItem(
|
||||
'claude',
|
||||
kind,
|
||||
payload,
|
||||
PROVIDER_FRAME_PAYLOAD_LIMITS,
|
||||
stopReading.stopped.options
|
||||
)
|
||||
const stopped = plain ? { identity, body: plain.body } : null
|
||||
const readings = {
|
||||
ran: { kind: 'literal' as const, identity, body },
|
||||
stopped: stopped && { kind: 'literal' as const, ...stopped },
|
||||
reservedBytes: estimateStructuredAgentSessionItemBytes(identity, body) * 2
|
||||
}
|
||||
if (
|
||||
writeClaudeStopReadings(sink, stopReading.check, readings, rowOptions, { publish: true })
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
sink.appendItem(identity, body, rowOptions)
|
||||
sink.publish()
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -66,6 +66,9 @@ export class JournalStepWriter {
|
||||
dropped = plan === null
|
||||
return plan ?? []
|
||||
})
|
||||
if (outcome?.kind === 'committed') {
|
||||
return { ...outcome, wrote: rows.length > 0 }
|
||||
}
|
||||
return (
|
||||
outcome ?? (dropped ? { kind: 'dropped' } : { kind: 'committed', wrote: rows.length > 0 })
|
||||
)
|
||||
|
||||
@@ -75,12 +75,21 @@ export type JournalTimelineItemResolution =
|
||||
failureItemId: string
|
||||
write: AgentJournalTurnRowWrite
|
||||
}
|
||||
/** A person's Stop at the write position picks one of a provider result's two readings. */
|
||||
| {
|
||||
kind: 'stop-decided'
|
||||
turnId: string
|
||||
endedAt: number
|
||||
ran: JournalTimelineItemResolution | null
|
||||
stopped: JournalTimelineItemResolution | null
|
||||
}
|
||||
|
||||
export type JournalTimelineItemResult =
|
||||
export type JournalTimelineItemResult = (
|
||||
| { kind: 'resolved'; item: JournalResolvedItem }
|
||||
| { kind: 'dropped'; reason: 'turn-settled'; turnItemId: string }
|
||||
| { kind: 'dropped'; reason: 'item-settled' }
|
||||
| { kind: 'dropped' }
|
||||
) & { stopped?: true }
|
||||
|
||||
const nothing = { kind: 'dropped' } as const
|
||||
|
||||
@@ -146,6 +155,14 @@ export function resolveJournalTimelineItem(
|
||||
resolution.write
|
||||
)
|
||||
)
|
||||
case 'stop-decided': {
|
||||
const stopped = view.stopDecidesTurn(resolution.turnId, resolution.endedAt)
|
||||
const chosen = stopped ? resolution.stopped : resolution.ran
|
||||
const result = chosen
|
||||
? resolveJournalTimelineItem(view, chosen, placement, reservedBytes)
|
||||
: nothing
|
||||
return stopped ? { ...result, stopped: true } : result
|
||||
}
|
||||
case 'text-snapshot':
|
||||
case 'guarded-item':
|
||||
return resolveGuardedItem(view, resolution, placement)
|
||||
|
||||
@@ -37,6 +37,9 @@ export function planJournalWriterStep(
|
||||
onResolved(resolved)
|
||||
return null
|
||||
}
|
||||
if (resolved.stopped) {
|
||||
onResolved({ kind: 'committed', wrote: true, stopped: true })
|
||||
}
|
||||
return planJournalWriterStep(
|
||||
state,
|
||||
{ kind: 'item', ...resolved.item, options: step.options, reservedBytes: step.reservedBytes },
|
||||
|
||||
@@ -37,8 +37,13 @@ export type JournalWriterStep =
|
||||
}
|
||||
|
||||
export type JournalStepOutcome =
|
||||
| { kind: 'committed'; wrote: boolean }
|
||||
| { kind: 'dropped'; reason?: 'turn-settled' | 'item-settled'; turnItemId?: string }
|
||||
| { kind: 'committed'; wrote: boolean; stopped?: true }
|
||||
| {
|
||||
kind: 'dropped'
|
||||
reason?: 'turn-settled' | 'item-settled'
|
||||
turnItemId?: string
|
||||
stopped?: true
|
||||
}
|
||||
|
||||
export type JournalStepsResult = {
|
||||
outcomes: JournalStepOutcome[]
|
||||
|
||||
-3
@@ -88,9 +88,6 @@ export class StructuredAgentSessionSinkQueue {
|
||||
}
|
||||
}
|
||||
|
||||
journalStopDecidesTurn = (turnId: string, endedAt: number): boolean =>
|
||||
this.target?.journal.stopMarks.personStopDecides(turnId, endedAt) ?? false
|
||||
|
||||
bindReadingControl(control: StructuredAgentSessionReadingControl): () => void {
|
||||
this.readingControl = control
|
||||
this.hasBoundReadingControl = true
|
||||
|
||||
+5
-5
@@ -10,6 +10,7 @@ import type { AgentSessionTurnActivity } from '../../../../shared/agent-session/
|
||||
import type { AgentSessionJournal } from '../../agent-session-journal/journal-store'
|
||||
import type { JournalLifecycleIdentityMutationInput } from '../../agent-session-journal/writing/journal-lifecycle-mutation'
|
||||
import type { JournalTimelineItemResolution } from '../../agent-session-journal/writing/journal-timeline-resolution'
|
||||
import type { JournalStepOutcome } from '../../agent-session-journal/writing/journal-writer-step'
|
||||
import { estimateStructuredAgentSessionItemBytes } from './structured-agent-session-event-sink-estimate'
|
||||
import { StructuredAgentSessionSinkQueue } from './structured-agent-session-event-sink-queue'
|
||||
import type { StructuredAgentSessionSnapshotSource } from './structured-agent-session-sink-snapshots'
|
||||
@@ -106,12 +107,14 @@ export type StructuredAgentSessionEventSink = StructuredAgentSessionTransitionSi
|
||||
tryReviseResolvedItem?(
|
||||
reservedBytes: number,
|
||||
resolution: JournalTimelineItemResolution,
|
||||
options: StructuredAgentSessionRevisionOptions
|
||||
options: StructuredAgentSessionRevisionOptions,
|
||||
onOutcome?: (outcome: JournalStepOutcome) => void
|
||||
): StructuredAgentSessionSinkAdmission
|
||||
tryReviseResolvedItemAndPublish?(
|
||||
reservedBytes: number,
|
||||
resolution: JournalTimelineItemResolution,
|
||||
options: StructuredAgentSessionRevisionOptions
|
||||
options: StructuredAgentSessionRevisionOptions,
|
||||
onOutcome?: (outcome: JournalStepOutcome) => void
|
||||
): StructuredAgentSessionSinkAdmission
|
||||
/** The writer chooses the row's identity at its position and may write nothing. */
|
||||
tryAppendLifecycleTransition?(
|
||||
@@ -126,8 +129,6 @@ export type StructuredAgentSessionEventSink = StructuredAgentSessionTransitionSi
|
||||
journalSnapshot?(): ClaudeJournalSnapshot | null
|
||||
snapshotCurrent?(): Promise<void>
|
||||
journalHistory?(): StructuredAgentSessionHistoryJournal | null
|
||||
/** Apply the journal’s personal-Stop cancellation rule; false until bound. */
|
||||
journalStopDecidesTurn?(turnId: string, endedAt: number): boolean
|
||||
appendLifecycleBatch?(
|
||||
settlementId: string,
|
||||
mutations: readonly JournalLifecycleIdentityMutationInput[],
|
||||
@@ -274,7 +275,6 @@ export function createDeferredStructuredAgentSessionEventSink(deps: {
|
||||
journalSnapshot: queue.snapshots.current,
|
||||
snapshotCurrent: queue.snapshots.settled,
|
||||
journalHistory: queue.journalHistory,
|
||||
journalStopDecidesTurn: queue.journalStopDecidesTurn,
|
||||
appendLifecycleBatch: (settlementId, mutations) => {
|
||||
const admission = appendLifecycleBatch(settlementId, mutations)
|
||||
if (!admission.accepted) {
|
||||
|
||||
+10
-5
@@ -7,6 +7,7 @@ import { structuredAgentSessionJournalAppendOptions } from './structured-agent-s
|
||||
import type { StructuredAgentSessionSinkQueue } from './structured-agent-session-event-sink-queue'
|
||||
import type { JournalTimelineItemResolution } from '../../agent-session-journal/writing/journal-timeline-resolution'
|
||||
import { restoreJournalSqlFailure } from '../../agent-session-journal/journal-sql-failure'
|
||||
import type { JournalStepOutcome } from '../../agent-session-journal/writing/journal-writer-step'
|
||||
|
||||
/** The writer resolves each item at its queue position, seeing prior writes and no later ones. */
|
||||
export function createStructuredAgentSessionResolvedAppend(
|
||||
@@ -25,7 +26,8 @@ export function createStructuredAgentSessionResolvedAppend(
|
||||
reservedBytes: number,
|
||||
resolution: JournalTimelineItemResolution,
|
||||
options: StructuredAgentSessionItemAppendOptions,
|
||||
publish: boolean
|
||||
publish: boolean,
|
||||
onOutcome?: (outcome: JournalStepOutcome) => void
|
||||
) =>
|
||||
queue.submit({
|
||||
bytes: reservedBytes + (publish ? 1 : 0),
|
||||
@@ -48,6 +50,9 @@ export function createStructuredAgentSessionResolvedAppend(
|
||||
if (publish && outcome?.kind === 'committed' && outcome.wrote) {
|
||||
bound.publish()
|
||||
}
|
||||
if (outcome) {
|
||||
onOutcome?.(outcome)
|
||||
}
|
||||
}
|
||||
})
|
||||
const identityOnly =
|
||||
@@ -62,10 +67,10 @@ export function createStructuredAgentSessionResolvedAppend(
|
||||
return {
|
||||
tryAppendResolvedItem: identityOnly(false),
|
||||
tryAppendResolvedItemAndPublish: identityOnly(true),
|
||||
tryReviseResolvedItem: (reservedBytes, resolution, options) =>
|
||||
revise(reservedBytes, resolution, options, false),
|
||||
tryReviseResolvedItemAndPublish: (reservedBytes, resolution, options) =>
|
||||
revise(reservedBytes, resolution, options, true),
|
||||
tryReviseResolvedItem: (reservedBytes, resolution, options, onOutcome) =>
|
||||
revise(reservedBytes, resolution, options, false, onOutcome),
|
||||
tryReviseResolvedItemAndPublish: (reservedBytes, resolution, options, onOutcome) =>
|
||||
revise(reservedBytes, resolution, options, true, onOutcome),
|
||||
tryAppendLifecycleTransition: (identitySizeBound, resolution, options) =>
|
||||
revise(
|
||||
estimateStructuredAgentSessionItemBytes(identitySizeBound, resolution.choice.body),
|
||||
|
||||
Reference in New Issue
Block a user