Files
archived-orca/src/shared/agent-session/agent-session-message-source.ts
T
Neil c10881fa8c refactor(shared): organize execution and automation defining owners (#39776)
* refactor: import journal queue state from defining owners

* refactor(shared): organize execution and automation owners

* fix: retain type imports used by surviving test cases

* refactor: finish work item owners and refresh validation metadata

* test: infer reconnect status fixture type

* test(claude): resolve source files beside same-named directories

* test(runtime): group repository creation mock registrations
2026-11-08 06:46:09 -08:00

160 lines
6.1 KiB
TypeScript

// Agent-origin messages carry from outside fingerprints; absence identifies the person at the composer.
import * as z from 'zod'
import { normalizeAgentSessionConversationName } from './agent-session-conversation-name'
import { isOrcaSessionId, type OrcaSessionId } from '../orca-session-address'
import type { OrchestrationPartyIdentity } from '../orchestration/mailbox/orchestration-party-identity'
import type { AgentType } from '../agent-status/contracts/agent-status-types'
import { AGENT_TYPE_MAX_LENGTH } from '../agent-status/contracts/agent-status-field-normalization'
import { openEnum, salvagedField, salvagedOptional, salvagingArray } from '../zod-salvage'
/** Resolve senders through the storing host's orchestration mailbox address (dispatch:<id> for federation), never a pane key. */
export type AgentMessageSender = Readonly<{
party: Omit<OrchestrationPartyIdentity, 'paneKey'>
/** What Orca called the sender when it wrote, kept for when it is gone; null when it had none. */
name: string | null
/** Its agent when Orca wrote, so the card keeps its icon once the agent is gone; absent when unknown. */
agent?: AgentType
relation?: 'worker' | 'coordinator' | 'none'
}>
/** One orchestration message a notice points at: its record, and its sender's `senders` address. */
export type OrchestrationMailContent = Readonly<{
subject: readonly [number, number]
body?: readonly [number, number]
payload?: readonly [number, number]
}>
export type OrchestrationMailMessage = Readonly<{
messageId: string
runId: string
from: string
/** Exact field ranges in the canonical text; avoids duplicating large messages in bounded frames. */
content?: OrchestrationMailContent
}>
/** "You have N orchestration messages": the pointer a terminal agent is typed, for a mailbox's
* unread mail, which the agent reads with `check`. */
export type OrchestrationMailNotice = Readonly<{
message: 'mail-notice'
mailbox: string
dispatchId: string | null
messages: readonly OrchestrationMailMessage[]
}>
/** A Dispatch's task, sent as the assignee's turn: the records it joins back to while they exist. */
export type OrchestrationTaskMessage = Readonly<{
message: 'task'
runId: string
taskId: string
dispatchId: string
}>
/** What Orca delivers for other agents, one shape per message kind. */
export type OrchestrationAgentMessage = OrchestrationMailNotice | OrchestrationTaskMessage
export type AgentMessageSource = Readonly<{
kind: 'agent'
/** Every distinct sender of the messages it carries, in mail order. */
senders: readonly AgentMessageSender[]
/** Null when this build cannot read the kind a newer one wrote; the senders still stand. */
orchestration: OrchestrationAgentMessage | null
}>
/** The mail a message notices, if it is orchestration mail; a person's message, a Task, or a kind this
* build cannot read is not. */
export function orchestrationMailNotice(
from: AgentMessageSource | undefined
): OrchestrationMailNotice | null {
return from?.kind === 'agent' && from.orchestration?.message === 'mail-notice'
? from.orchestration
: null
}
/** Persist only the source kind so restart/close retains human unsent cards; sender identities stay on the message body. */
export type AgentSessionMessageSource = Readonly<{ kind: 'user' | 'agent' }>
export const USER_MESSAGE_SOURCE: AgentSessionMessageSource = { kind: 'user' }
export const AGENT_MESSAGE_SOURCE: AgentSessionMessageSource = { kind: 'agent' }
/** A sender name as stored: bounded and flattened like a conversation name, never raw. */
export function agentMessageSenderName(value: unknown): string | null {
return normalizeAgentSessionConversationName(value)
}
const orcaSessionIdSchema = z.custom<OrcaSessionId>(
(value) => typeof value === 'string' && isOrcaSessionId(value)
)
const contentRangeSchema = z.tuple([z.number().int().nonnegative(), z.number().int().nonnegative()])
const mailContentSchema = z.object({
subject: contentRangeSchema,
body: contentRangeSchema.optional(),
payload: contentRangeSchema.optional()
})
const mailNoticeSchema = z.object({
message: z.literal('mail-notice'),
mailbox: z.string(),
dispatchId: z.string().nullable(),
messages: z.array(
z.object({
messageId: z.string(),
runId: z.string(),
from: z.string(),
content: salvagedOptional('content', mailContentSchema)
})
)
})
const taskSchema = z.object({
message: z.literal('task'),
runId: z.string(),
taskId: z.string(),
dispatchId: z.string()
})
const senderSchema = z.object({
party: z.object({
address: z.string().min(1),
terminalHandle: z.string().nullable(),
orcaSessionId: orcaSessionIdSchema.nullable()
}),
// Any bounded string: a kind a newer build knows still draws as its first letter.
agent: salvagedOptional('agent', z.string().min(1).max(AGENT_TYPE_MAX_LENGTH)),
relation: salvagedOptional('relation', z.enum(['worker', 'coordinator', 'none'])),
name: z.unknown().transform(agentMessageSenderName)
})
// Parse separately so malformed senders or newer orchestration kinds never turn an agent message into a human message.
const sourceSchema = z.object({
kind: openEnum(['agent'], 'agent'),
senders: salvagedField('senders', salvagingArray(senderSchema), () => []),
orchestration: salvagedOptional(
'orchestration',
z.discriminatedUnion('message', [mailNoticeSchema, taskSchema])
).transform((orchestration) => orchestration ?? null)
})
/** The one reader of a stored or published `from`: undefined (the person's) when it is absent
* or not an agent's at all. */
export function readAgentMessageSource(value: unknown): AgentMessageSource | undefined {
if (value === undefined) {
return undefined
}
const parsed = sourceSchema.safeParse(value)
return parsed.success ? parsed.data : undefined
}
/** The senders a label names, and how many more it counts; one notice can carry many. */
export function agentMessageSendersShown(
source: AgentMessageSource,
limit = 3
): { shown: readonly AgentMessageSender[]; more: number } {
return {
shown: source.senders.slice(0, limit),
more: Math.max(0, source.senders.length - limit)
}
}