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
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ import {
journalStateScalars
} from './journal-state-layout'
import { readStoredQueuedMessageRow } from './queued-message-stored-row'
import { readAgentMessageSource } from '../../../shared/agent-session/agent-session-message-source'
import { projectStructuredAgentStartItem } from '../../../shared/structured-agent-start-projection'

// Admission keeps the in-memory chat within what this build declares on every path a saved value
// takes into it, so restating that chat on a new epoch never drops a newer build's key.
Expand Down Expand Up @@ -275,3 +277,59 @@ it('reads an open string such as an agent type as a value, and still refuses a k
// @ts-expect-error `host` is a key the stored provider handle does not declare
expect(declared<UndeclaredStorageKeys<Later, Stored>>()).toBeUndefined()
})

it.each(['codex', 'future-agent', undefined, 42])(
'admits actual start, message and queued sender kind %j without losing the sender',
async (agent) => {
const journal = await open(journals)
const sender = {
party: { address: 'term_worker', terminalHandle: 'term_worker', orcaSessionId: null },
name: 'Inspect parser',
agent: 'codex'
}
const body = {
kind: 'message' as const,
role: 'user' as const,
blocks: [{ type: 'text' as const, text: 'Mail' }],
from: { kind: 'agent' as const, senders: [sender], orchestration: null }
}
await journal.appendItem(
item(0),
{ kind: 'agent-start', dispatchId: 'dispatch-1', task: 'Inspect parser', worker: sender },
SCOPE
)
await journal.appendItem(item(1), body, SCOPE)
await journal.queuedMessages.insert({ messageId: 'queued-1', body })
await journals.closeAll()
// A later or damaged writer can change this declared optional value without adding any key.
const records = db()
.prepare(
"SELECT generation, seq, ordinal, value_json FROM journal_outcomes WHERE field IN ('items', 'queue.cards')"
)
.all()
expect(records.length).toBeGreaterThanOrEqual(3)
for (const row of records) {
const json = JSON.stringify(JSON.parse(String(row.value_json)), (key, value) =>
key === 'agent' ? agent : value
)
db()
.prepare(
'UPDATE journal_outcomes SET value_json = ? WHERE generation = ? AND seq = ? AND ordinal = ?'
)
.run(json, Number(row.generation), Number(row.seq), String(row.ordinal))
}
const reopened = await open(journals)
const restored = reopened.snapshot().items
expect(restored).toHaveLength(2)
const fromStart = projectStructuredAgentStartItem(restored[0])?.from
const fromMessage = readAgentMessageSource(
restored[1].body.kind === 'message' ? restored[1].body.from : undefined
)
const expected = typeof agent === 'string' ? agent : undefined
const queued = reopened.queuedMessages.list()[0]
for (const from of [fromStart, fromMessage, readAgentMessageSource(queued.body.from)]) {
expect(from?.senders[0]).toMatchObject({ party: sender.party, name: sender.name })
expect(from?.senders[0].agent).toBe(expected)
}
}
)
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ const sender = z.object({
.nullable()
.optional(),
name: salvaged,
agent: salvaged,
relation: salvaged
})
const orchestration = z.discriminatedUnion('message', [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export function createQueuedRigProvider(
link: {
linkId: `link-${fence}`,
handle:
options.agent === 'claude'
identity.agent === 'claude'
? claudeProviderHandle(thread, null)
: codexProviderHandle(thread),
origin: resumes ? ('resumed' as const) : ('created' as const),
Expand Down
4 changes: 2 additions & 2 deletions src/main/runtime/construction/runtime-service-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,8 +285,8 @@ export abstract class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWith
resolveStructuredTarget: (mailboxHandle) =>
this.resolveStructuredMailboxTarget(mailboxHandle),
getCliCommand: localOrchestrationCliCommand,
senderName: (party, reportedDispatchId) =>
this.orchestrationSenderNames.nameOf(party, reportedDispatchId),
senderSnapshot: (party, reportedDispatchId) =>
this.orchestrationSenderNames.snapshotOf(party, reportedDispatchId),
host: createStructuredMailboxPointerHost()
})

Expand Down
21 changes: 11 additions & 10 deletions src/main/runtime/orchestration/agent-facing-parity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,17 @@ function runtime(prompts: string[]): OrcaRuntimeService {
const fake: Pick<
OrcaRuntimeService,
'getNestedWorkerMaxDepth' | 'getTerminalOrchestrationCliCommand' | 'sendTerminalAgentPrompt'
> & { orchestrationSenderNames: Pick<OrcaRuntimeService['orchestrationSenderNames'], 'nameOf'> } =
{
orchestrationSenderNames: { nameOf: () => null },
getNestedWorkerMaxDepth: () => 2,
getTerminalOrchestrationCliCommand: () => 'orca',
sendTerminalAgentPrompt: async (handle, text) => {
prompts.push(text)
return { handle, accepted: true, bytesWritten: text.length }
}
> & {
orchestrationSenderNames: Pick<OrcaRuntimeService['orchestrationSenderNames'], 'snapshotOf'>
} = {
orchestrationSenderNames: { snapshotOf: () => ({ name: null, agent: null }) },
getNestedWorkerMaxDepth: () => 2,
getTerminalOrchestrationCliCommand: () => 'orca',
sendTerminalAgentPrompt: async (handle, text) => {
prompts.push(text)
return { handle, accepted: true, bytesWritten: text.length }
}
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: preamble delivery reads only the members the fake implements.
return fake as OrcaRuntimeService
}
Expand Down Expand Up @@ -116,7 +117,7 @@ async function renderChatPointer(mailbox: string): Promise<string> {
getMessageWaiters: () => undefined,
resolveStructuredTarget: () => ({ sessionId: CHAT_SESSION, dispatchId: null }),
getCliCommand: localOrchestrationCliCommand,
senderName: () => null,
senderSnapshot: () => ({ name: null, agent: null }),
host: {
readSessionFacts: async () => ({ submissions: [] }),
hasActionablePromptNow: () => false,
Expand Down
31 changes: 20 additions & 11 deletions src/main/runtime/orchestration/agent-message-sender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,33 @@ import {
agentMessageSenderName,
type AgentMessageSender
} from '../../../shared/agent-session/agent-session-message-source'
import type { AgentType } from '../../../shared/agent-status-types'
import type { OrchestrationDb } from './db'
import { resolveOrchestrationParty } from './orchestration-party'

/** Use recorded names, never agent-painted titles; reportedDispatchId comes from worker_done. */
export type SenderNameResolver = (
/** What a sender is now: its recorded name, never an agent-painted title, and its agent. */
export type SenderSnapshot = { name: string | null; agent: AgentType | null }

/** reportedDispatchId comes from worker_done. */
export type SenderSnapshotResolver = (
party: AgentMessageSender['party'],
reportedDispatchId?: string
) => string | null
) => SenderSnapshot

/** Snapshot the sender name before its party disappears. */
/** Snapshot the sender's name and agent before its party disappears. */
export function agentMessageSender(
address: string,
db: OrchestrationDb | null,
senderName: SenderNameResolver,
senderSnapshot: SenderSnapshotResolver,
reportedDispatchId?: string
): AgentMessageSender {
const party = senderParty(address, db)
return { party, name: snapshotName(senderName, party, reportedDispatchId) }
const snapshot = snapshotSender(senderSnapshot, party, reportedDispatchId)
return {
party,
name: agentMessageSenderName(snapshot.name),
...(snapshot.agent ? { agent: snapshot.agent } : {})
}
}

function senderParty(address: string, db: OrchestrationDb | null): AgentMessageSender['party'] {
Expand All @@ -33,15 +42,15 @@ function senderParty(address: string, db: OrchestrationDb | null): AgentMessageS
}
}

function snapshotName(
senderName: SenderNameResolver,
function snapshotSender(
senderSnapshot: SenderSnapshotResolver,
party: AgentMessageSender['party'],
reportedDispatchId: string | undefined
): string | null {
): SenderSnapshot {
try {
return agentMessageSenderName(senderName(party, reportedDispatchId))
return senderSnapshot(party, reportedDispatchId)
} catch {
// Failure to resolve a label must not block delivery.
return null
return { name: null, agent: null }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,28 @@ import type { OrchestrationDb } from '../orchestration-db'
import { transitionLifecycleWithDb } from '../lifecycle-transition'
import { recordFailedStartDispatchIdentity } from '../worker-terminal/failed-start-dispatch-identity'
import { DISPATCH_CIRCUIT_BREAK_FAILURES } from '../dispatch-context/dispatch-circuit-breaker'
import { mergeWorkerLaunchObservation } from '../../worker-launch-observation'

export function retainWorkerLaunchObservation(
this: OrchestrationDb,
dispatchId: string,
observation: unknown
): void {
this.db.exec('BEGIN IMMEDIATE')
try {
const worker = this.getWorkerDispatch(dispatchId)
const options = worker && mergeWorkerLaunchObservation(worker.start_options, observation)
if (worker && options !== undefined && options !== worker.start_options) {
this.db
.prepare('UPDATE worker_dispatches SET start_options = ? WHERE dispatch_id = ?')
.run(options, dispatchId)
}
this.db.exec('COMMIT')
} catch (error) {
this.db.exec('ROLLBACK')
throw error
}
}

export function markWorkerDispatchReady(
this: OrchestrationDb,
Expand Down Expand Up @@ -161,6 +183,7 @@ export function getWorkerDispatch(
}

export type WorkerDispatchOutcomeMethods = {
retainWorkerLaunchObservation: typeof retainWorkerLaunchObservation
markWorkerDispatchReady: typeof markWorkerDispatchReady
failWorkerStart: typeof failWorkerStart
markWorkerStartUnknown: typeof markWorkerStartUnknown
Expand All @@ -169,6 +192,7 @@ export type WorkerDispatchOutcomeMethods = {

export function attachWorkerDispatchOutcome(ctor: { prototype: object }): void {
Object.assign(ctor.prototype, {
retainWorkerLaunchObservation,
markWorkerDispatchReady,
failWorkerStart,
markWorkerStartUnknown,
Expand Down
11 changes: 8 additions & 3 deletions src/main/runtime/orchestration/dispatch-task-source.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { AgentMessageSource } from '../../../shared/agent-session/agent-session-message-source'
import { agentMessageSender, type SenderNameResolver } from './agent-message-sender'
import { agentMessageSender, type SenderSnapshotResolver } from './agent-message-sender'
import type { OrchestrationDb } from './db'
import type { DispatchContextRow } from './types'

Expand All @@ -9,13 +9,18 @@ export function dispatchTaskSource(args: {
dispatch: Pick<DispatchContextRow, 'id' | 'run_id' | 'task_id'>
/** The coordinator's address; a Dispatch with no declared caller names no sender. */
from: string | undefined
senderName: SenderNameResolver
senderSnapshot: SenderSnapshotResolver
}): AgentMessageSource {
const { dispatch } = args
return {
kind: 'agent',
senders: args.from
? [{ ...agentMessageSender(args.from, args.db, args.senderName), relation: 'coordinator' }]
? [
{
...agentMessageSender(args.from, args.db, args.senderSnapshot),
relation: 'coordinator'
}
]
: [],
orchestration: {
message: 'task',
Expand Down
Loading
Loading