diff --git a/.changeset/3617-live-personas.md b/.changeset/3617-live-personas.md new file mode 100644 index 0000000000..87cb7b7e14 --- /dev/null +++ b/.changeset/3617-live-personas.md @@ -0,0 +1,8 @@ +--- +"@schlessera/brain": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-react": minor +--- + +Live conversation gains personas (#3617). A persona is Markdown at `_voice/personas/.md` in the brain, with a name, one voice per live service and plain-text speaking-style instructions; Settings › Voice lists, edits and selects them, and the built-in Standard keeps today's exact behaviour. New owner-only routes `GET/POST /api/voice/personas`, `GET/PUT/DELETE /api/voice/personas/:id` and `GET/PUT /api/settings/voice` use sha-256 file revisions and a separately revisioned `voice.live.persona` setting. `LiveConversationProvider` gains optional `voices`, `defaultVoice` and `personaInstructionBytes` (mirrored on `ConversationProfile`, outside the Start disclosure echo), `LiveConversationOpenOptions` gains `persona`, `server_hello` gains `livePersona`, a new `live_persona` frame pushes changes, and `conversation_start` gains `personaRef` with an explicit one-time `voice: "default"`. Each conversation freezes its persona at Start; GPT-Live caps instructions at 2,000 UTF-8 bytes and Gemini Live at 6,000, refusing Start rather than truncating. Core now excludes `_voice` from the content index by default, so existing brains drop persona files from search on the next `brain index`. diff --git a/api-report/ui-react.txt b/api-report/ui-react.txt index e8d2e6e01d..08dc1f0261 100644 --- a/api-report/ui-react.txt +++ b/api-report/ui-react.txt @@ -358,6 +358,7 @@ signatures (every public export and the types it is made of) disclosureOpen: boolean; profile: ServerConversationOpened | null; conversationProfile: ConversationProfile | null; + livePersona: LivePersonaStatus | null; durableAvailable: boolean; sessionId: string | null; agentProviderId: string | null; @@ -1108,6 +1109,8 @@ signatures (every public export and the types it is made of) success: boolean; }>; checkWorkerHost: () => Promise; + createLivePersona: (request: LivePersonaCreateRequest) => Promise; + deleteLivePersona: (id: string, baseRevision: string) => Promise; dictationSettings: () => Promise; fileResolve: (path: string) => Promise<{ ancestors: string[]; @@ -1129,6 +1132,8 @@ signatures (every public export and the types it is made of) hygieneMediaUndo: (journalId: string) => Promise; hygienePreview: (request: HygienePreviewRequest, signal?: AbortSignal) => Promise; hygieneReview: () => Promise; + livePersona: (id: string) => Promise; + livePersonas: () => Promise; login: (password: string) => Promise<{ ok: true; }>; @@ -1231,6 +1236,7 @@ signatures (every public export and the types it is made of) }>; refreshModels: () => Promise; saveDictationSettings: (settings: DictationSettings) => Promise; + saveLivePersonaSelection: (value: string, revision: number) => Promise; sessionRecovery: (sessionId: string, opts?: { signal?: AbortSignal; }) => Promise; @@ -1332,12 +1338,14 @@ signatures (every public export and the types it is made of) }>; turnRevertPlan: (sessionId: string, turnId: string, action?: "restore" | "revert", signal?: AbortSignal) => Promise; turnRevertReceipt: (sessionId: string, turnId: string, operationId: string, signal?: AbortSignal) => Promise; + updateLivePersona: (id: string, request: LivePersonaUpdateRequest) => Promise; voiceKeyterms: () => Promise; voiceOverrides: (signal?: AbortSignal) => Promise<{ overrides: PronunciationOverride[]; }>; voiceProviders: () => Promise; voiceSession: (signal?: AbortSignal, selection?: VoiceSessionRequest) => Promise; + voiceSettings: () => Promise; voiceToken: () => Promise; vpnCheck: () => Promise<{ vpn: boolean; @@ -1612,6 +1620,8 @@ signatures (every public export and the types it is made of) success: boolean; }>; checkWorkerHost: () => Promise; + createLivePersona: (request: import("@schlessera/brain-ui-sdk").LivePersonaCreateRequest) => Promise; + deleteLivePersona: (id: string, baseRevision: string) => Promise; dictationSettings: () => Promise; fileResolve: (path: string) => Promise<{ ancestors: string[]; @@ -1633,6 +1643,8 @@ signatures (every public export and the types it is made of) hygieneMediaUndo: (journalId: string) => Promise; hygienePreview: (request: import("@schlessera/brain-ui-sdk").HygienePreviewRequest, signal?: AbortSignal) => Promise; hygieneReview: () => Promise; + livePersona: (id: string) => Promise; + livePersonas: () => Promise; login: (password: string) => Promise<{ ok: true; }>; @@ -1735,6 +1747,7 @@ signatures (every public export and the types it is made of) }>; refreshModels: () => Promise; saveDictationSettings: (settings: import("@schlessera/brain-ui-sdk").DictationSettings) => Promise; + saveLivePersonaSelection: (value: string, revision: number) => Promise; sessionRecovery: (sessionId: string, opts?: { signal?: AbortSignal; }) => Promise; @@ -1836,12 +1849,14 @@ signatures (every public export and the types it is made of) }>; turnRevertPlan: (sessionId: string, turnId: string, action?: "restore" | "revert", signal?: AbortSignal) => Promise; turnRevertReceipt: (sessionId: string, turnId: string, operationId: string, signal?: AbortSignal) => Promise; + updateLivePersona: (id: string, request: import("@schlessera/brain-ui-sdk").LivePersonaUpdateRequest) => Promise; voiceKeyterms: () => Promise; voiceOverrides: (signal?: AbortSignal) => Promise<{ overrides: import("@schlessera/brain-ui-sdk").PronunciationOverride[]; }>; voiceProviders: () => Promise; voiceSession: (signal?: AbortSignal, selection?: import("@schlessera/brain-ui-sdk").VoiceSessionRequest) => Promise; + voiceSettings: () => Promise; voiceToken: () => Promise; vpnCheck: () => Promise<{ vpn: boolean; diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index ff63a06a62..6d07a320e9 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -157,8 +157,10 @@ export "." (./src/index.ts) type ConversationInterval type ConversationLimits type ConversationOutputRecord + type ConversationPersonaRef type ConversationPlayback type ConversationProfile + type ConversationVoice type ConversationWireEvent type ConversationWorkReceipt type ConversationWorkState @@ -253,7 +255,16 @@ export "." (./src/index.ts) type JournalVersion type Keyterm LIVENESS_CAPABILITY + LIVE_PERSONA_LIMITS LOCAL_ANSWER_CLOSE + type LivePersona + type LivePersonaCreateRequest + type LivePersonaInvalidReason + type LivePersonaListResponse + type LivePersonaProviderStatus + type LivePersonaStatus + type LivePersonaSummary + type LivePersonaUpdateRequest type LocalAnswer type LocalExchange MAX_IMAGES_PER_MESSAGE @@ -314,6 +325,8 @@ export "." (./src/index.ts) SPAN_OP_EXECUTE_TOOL SPAN_OP_INVOKE_AGENT SPAN_TOOL_NAME_PREFIX + STANDARD_PERSONA_ID + STANDARD_PERSONA_REVISION SUBSCRIPTION_AUTH_INSTRUCTIONS SUBSCRIPTION_RELOGIN_PROCEDURE type SafetyCapabilities @@ -350,6 +363,7 @@ export "." (./src/index.ts) type ServerHandoffDraft type ServerHandoffReceipt type ServerHello + type ServerLivePersona type ServerLocalExchangeResult type ServerLocationRequest type ServerMaskRequest @@ -473,6 +487,8 @@ export "." (./src/index.ts) type VoiceProvidersResponse type VoiceSessionRequest type VoiceSessionResponse + type VoiceSettingsResponse + type VoiceSettingsUpdateRequest type VoiceTokenResponse type WikilinkMapResponse type WorkerHostCheck @@ -735,8 +751,10 @@ export "./client" (./src/client/index.ts) type ConversationInterval type ConversationLimits type ConversationOutputRecord + type ConversationPersonaRef type ConversationPlayback type ConversationProfile + type ConversationVoice type ConversationWireEvent type ConversationWorkReceipt type ConversationWorkState @@ -854,8 +872,17 @@ export "./client" (./src/client/index.ts) LIVENESS_CAPABILITY LIVENESS_IDLE_MS LIVENESS_RESPONSE_MS + LIVE_PERSONA_LIMITS LOCAL_ANSWER_CLOSE LOCATION_PAYLOAD_SCHEMA + type LivePersona + type LivePersonaCreateRequest + type LivePersonaInvalidReason + type LivePersonaListResponse + type LivePersonaProviderStatus + type LivePersonaStatus + type LivePersonaSummary + type LivePersonaUpdateRequest type LivenessEvent type LocalAnswer type LocalExchange @@ -969,6 +996,8 @@ export "./client" (./src/client/index.ts) SPAN_OP_INVOKE_AGENT SPAN_TOOL_NAME_PREFIX STALE_SOCKET_CLOSE_CODE + STANDARD_PERSONA_ID + STANDARD_PERSONA_REVISION SUBSCRIPTION_AUTH_INSTRUCTIONS SUBSCRIPTION_RELOGIN_PROCEDURE type SafetyCapabilities @@ -1006,6 +1035,7 @@ export "./client" (./src/client/index.ts) type ServerHandoffDraft type ServerHandoffReceipt type ServerHello + type ServerLivePersona type ServerLocalExchangeResult type ServerLocationRequest type ServerMaskRequest @@ -1148,6 +1178,8 @@ export "./client" (./src/client/index.ts) type VoiceProvidersResponse type VoiceSessionRequest type VoiceSessionResponse + type VoiceSettingsResponse + type VoiceSettingsUpdateRequest type VoiceTokenResponse WEB_SEARCH_INPUT_SCHEMA WEB_TOOL_CONTRACTS @@ -1632,8 +1664,10 @@ export "./protocol" (./src/protocol.ts) type ConversationInterval type ConversationLimits type ConversationOutputRecord + type ConversationPersonaRef type ConversationPlayback type ConversationProfile + type ConversationVoice type ConversationWireEvent type ConversationWorkReceipt type ConversationWorkState @@ -1727,7 +1761,16 @@ export "./protocol" (./src/protocol.ts) type JournalVersion type Keyterm LIVENESS_CAPABILITY + LIVE_PERSONA_LIMITS LOCAL_ANSWER_CLOSE + type LivePersona + type LivePersonaCreateRequest + type LivePersonaInvalidReason + type LivePersonaListResponse + type LivePersonaProviderStatus + type LivePersonaStatus + type LivePersonaSummary + type LivePersonaUpdateRequest type LocalAnswer type LocalExchange MAX_IMAGES_PER_MESSAGE @@ -1783,6 +1826,8 @@ export "./protocol" (./src/protocol.ts) SPAN_OP_EXECUTE_TOOL SPAN_OP_INVOKE_AGENT SPAN_TOOL_NAME_PREFIX + STANDARD_PERSONA_ID + STANDARD_PERSONA_REVISION SUBSCRIPTION_AUTH_INSTRUCTIONS SUBSCRIPTION_RELOGIN_PROCEDURE type SafetyCapabilities @@ -1819,6 +1864,7 @@ export "./protocol" (./src/protocol.ts) type ServerHandoffDraft type ServerHandoffReceipt type ServerHello + type ServerLivePersona type ServerLocalExchangeResult type ServerLocationRequest type ServerMaskRequest @@ -1942,6 +1988,8 @@ export "./protocol" (./src/protocol.ts) type VoiceProvidersResponse type VoiceSessionRequest type VoiceSessionResponse + type VoiceSettingsResponse + type VoiceSettingsUpdateRequest type VoiceTokenResponse type WikilinkMapResponse type WorkerHostCheck @@ -2027,8 +2075,10 @@ export "./schemas" (./src/schemas.ts) conversationEvidenceSchema conversationLimitsSchema conversationOutputRecordSchema + conversationPersonaRefSchema conversationProfileSchema conversationSampleRateSchema + conversationVoiceSchema conversationWireEventSchema conversationWorkReceiptSchema dialogueEvidenceSchema @@ -2073,6 +2123,11 @@ export "./schemas" (./src/schemas.ts) inboxThreadSchema inboxViewSchema inboxWorkPayloadSchema + livePersonaListResponseSchema + livePersonaProviderStatusSchema + livePersonaSchema + livePersonaStatusSchema + livePersonaSummarySchema localExchangeSchema messageBlockSchema messageSourceSchema @@ -2110,6 +2165,7 @@ export "./schemas" (./src/schemas.ts) serverHandoffDraftSchema serverHandoffReceiptSchema serverHelloSchema + serverLivePersonaSchema serverLocalExchangeResultSchema serverLocationRequestSchema serverMaskRequestSchema @@ -2144,6 +2200,7 @@ export "./schemas" (./src/schemas.ts) turnScopeSummarySchema v1ResolutionEffectSchema validateResolutionEffect + voiceSettingsResponseSchema export "./server" (./src/server/index.ts) ACTIVITY_COMPUTE_CAPABILITY @@ -2434,11 +2491,14 @@ export "./server" (./src/server/index.ts) type ConversationLimits type ConversationOrientation type ConversationOutputRecord + type ConversationPersona + type ConversationPersonaRef type ConversationPlayback type ConversationProfile type ConversationResync type ConversationScope type ConversationTaskRef + type ConversationVoice type ConversationWireEvent type ConversationWorkReceipt type ConversationWorkRef @@ -2575,6 +2635,7 @@ export "./server" (./src/server/index.ts) type Keyterm type KillableProcess LIVENESS_CAPABILITY + LIVE_PERSONA_LIMITS LOCAL_ANSWER_CLOSE LOCATION_PAYLOAD_SCHEMA type LandOptions @@ -2583,6 +2644,14 @@ export "./server" (./src/server/index.ts) type LiveConversationOpenOptions type LiveConversationProvider type LiveConversationSession + type LivePersona + type LivePersonaCreateRequest + type LivePersonaInvalidReason + type LivePersonaListResponse + type LivePersonaProviderStatus + type LivePersonaStatus + type LivePersonaSummary + type LivePersonaUpdateRequest type LocalAnswer type LocalExchange type LocationFix @@ -2699,6 +2768,8 @@ export "./server" (./src/server/index.ts) SPAN_OP_EXECUTE_TOOL SPAN_OP_INVOKE_AGENT SPAN_TOOL_NAME_PREFIX + STANDARD_PERSONA_ID + STANDARD_PERSONA_REVISION SUBSCRIPTION_AUTH_INSTRUCTIONS SUBSCRIPTION_RELOGIN_PROCEDURE type SafetyCapabilities @@ -2736,6 +2807,7 @@ export "./server" (./src/server/index.ts) type ServerHandoffDraft type ServerHandoffReceipt type ServerHello + type ServerLivePersona type ServerLocalExchangeResult type ServerLocationRequest type ServerMaskRequest @@ -2901,6 +2973,8 @@ export "./server" (./src/server/index.ts) type VoiceProvidersResponse type VoiceSessionRequest type VoiceSessionResponse + type VoiceSettingsResponse + type VoiceSettingsUpdateRequest type VoiceTokenResponse WEB_SEARCH_INPUT_SCHEMA WEB_TOOL_CONTRACTS @@ -6793,6 +6867,7 @@ signatures (every public export and the types it is made of) ClientConversationStart (packages/ui-sdk/src/protocol.ts) export interface ClientConversationStart { disclosed?: ConversationProfile; + personaRef?: ConversationPersonaRef; historyOwnerId?: string; contextualTasks?: boolean; type: "conversation_start"; @@ -7216,6 +7291,17 @@ signatures (every public export and the types it is made of) end: number; }; } + ConversationPersona (packages/ui-sdk/src/server/conversation.ts) + export interface ConversationPersona { + voice?: string; + instructions: string; + } + ConversationPersonaRef (packages/ui-sdk/src/protocol.ts) + export interface ConversationPersonaRef { + id: string; + revision: string; + voice?: "default"; + } ConversationPlayback (packages/ui-sdk/src/protocol.ts) export type ConversationPlayback = "played" | "discarded" | "unknown"; ConversationProfile (packages/ui-sdk/src/protocol.ts) @@ -7223,6 +7309,9 @@ signatures (every public export and the types it is made of) providerId: string; capabilities: ConversationCapabilities; disclosure: ConversationDisclosure; + voices?: ConversationVoice[]; + defaultVoice?: string; + personaInstructionBytes?: number; } ConversationResync (packages/ui-sdk/src/server/conversation.ts) export interface ConversationResync { @@ -7246,6 +7335,11 @@ signatures (every public export and the types it is made of) requestId: string; nativeHandle: string; }; + ConversationVoice (packages/ui-sdk/src/protocol.ts) + export interface ConversationVoice { + id: string; + label: string; + } ConversationWireEvent (packages/ui-sdk/src/protocol.ts) export type ConversationWireEvent = { kind: "unassigned_input_fragment"; @@ -8462,6 +8556,15 @@ signatures (every public export and the types it is made of) const LIVENESS_IDLE_MS: 15000; LIVENESS_RESPONSE_MS (packages/ui-sdk/src/client/ws-client.ts) const LIVENESS_RESPONSE_MS: 5000; + LIVE_PERSONA_LIMITS (packages/ui-sdk/src/protocol.ts) + const LIVE_PERSONA_LIMITS: { + readonly maxFileBytes: 16384; + readonly maxIdChars: 48; + readonly maxInstructionBytes: 6000; + readonly maxNameChars: 40; + readonly maxPersonas: 20; + readonly maxVoices: 16; + }; LOCAL_ANSWER_CLOSE (packages/ui-sdk/src/protocol.ts) const LOCAL_ANSWER_CLOSE: ""; LOCATION_PAYLOAD_SCHEMA (packages/ui-sdk/src/tool-contracts/bridge.ts) @@ -8550,12 +8653,16 @@ signatures (every public export and the types it is made of) resync: ConversationResync; history?: ConversationHistoryEnvelope; orientation?: ConversationOrientation; + persona?: ConversationPersona; } LiveConversationProvider (packages/ui-sdk/src/server/conversation.ts) export interface LiveConversationProvider { id: string; capabilities: ConversationCapabilities; disclosure: ConversationDisclosure; + voices?: readonly ConversationVoice[]; + defaultVoice?: string; + personaInstructionBytes?: number; open(scope: ConversationScope, options: LiveConversationOpenOptions): Promise; } LiveConversationSession (packages/ui-sdk/src/server/conversation.ts) @@ -8589,6 +8696,60 @@ signatures (every public export and the types it is made of) remote: "acknowledged" | "unknown"; }>; } + LivePersona (packages/ui-sdk/src/protocol.ts) + export interface LivePersona extends LivePersonaSummary { + instructions: string; + } + LivePersonaCreateRequest (packages/ui-sdk/src/protocol.ts) + export interface LivePersonaCreateRequest { + id?: string; + name: string; + voices: Record; + instructions: string; + } + LivePersonaInvalidReason (packages/ui-sdk/src/protocol.ts) + export type LivePersonaInvalidReason = "front_matter" | "schema" | "name" | "voices" | "too_long" | "encoding" | "over_count"; + LivePersonaListResponse (packages/ui-sdk/src/protocol.ts) + export interface LivePersonaListResponse { + personas: LivePersonaSummary[]; + } + LivePersonaProviderStatus (packages/ui-sdk/src/protocol.ts) + export interface LivePersonaProviderStatus { + voice: string; + voiceSource: "persona" | "default"; + staleVoice?: string; + maxInstructionBytes: number; + overLimit: boolean; + } + LivePersonaStatus (packages/ui-sdk/src/protocol.ts) + export interface LivePersonaStatus { + selected: string; + selectedMissing: boolean; + selectedInvalid: boolean; + persona: LivePersonaSummary; + personaRef: { + id: string; + revision: string; + }; + providers: Record; + } + LivePersonaSummary (packages/ui-sdk/src/protocol.ts) + export interface LivePersonaSummary { + id: string; + name: string; + voices: Record; + instructionBytes: number; + revision: string; + builtIn?: true; + invalid?: LivePersonaInvalidReason; + } + LivePersonaUpdateRequest (packages/ui-sdk/src/protocol.ts) + export interface LivePersonaUpdateRequest { + baseRevision: string; + name: string; + voices: Record; + instructions: string; + } LivenessEvent (packages/ui-sdk/src/client/ws-client.ts) export type LivenessEvent = { type: "probe"; @@ -10965,6 +11126,10 @@ signatures (every public export and the types it is made of) const SPAN_TOOL_NAME_PREFIX: "execute_tool "; STALE_SOCKET_CLOSE_CODE (packages/ui-sdk/src/client/ws-client.ts) const STALE_SOCKET_CLOSE_CODE: 4000; + STANDARD_PERSONA_ID (packages/ui-sdk/src/protocol.ts) + const STANDARD_PERSONA_ID: "standard"; + STANDARD_PERSONA_REVISION (packages/ui-sdk/src/protocol.ts) + const STANDARD_PERSONA_REVISION: "builtin"; SUBSCRIPTION_AUTH_INSTRUCTIONS (packages/ui-sdk/src/protocol.ts) const SUBSCRIPTION_AUTH_INSTRUCTIONS: Readonly>; SUBSCRIPTION_RELOGIN_PROCEDURE (packages/ui-sdk/src/protocol.ts) @@ -11180,6 +11345,7 @@ signatures (every public export and the types it is made of) export interface ServerHello { safetyCapabilities?: SafetyCapabilities; conversationProfile?: ConversationProfile; + livePersona?: LivePersonaStatus; type: "server_hello"; protocolRev: number; principalKey?: string; @@ -11187,6 +11353,11 @@ signatures (every public export and the types it is made of) sessionDraftLimits?: SessionDraftLimits; attachmentLimits?: AttachmentLimits; } + ServerLivePersona (packages/ui-sdk/src/protocol.ts) + export interface ServerLivePersona { + type: "live_persona"; + livePersona: LivePersonaStatus; + } ServerLocalExchangeResult (packages/ui-sdk/src/protocol.ts) export interface ServerLocalExchangeResult extends SessionScoped { type: "local_exchange_result"; @@ -11209,7 +11380,7 @@ signatures (every public export and the types it is made of) instruction?: string; } ServerMessage (packages/ui-sdk/src/protocol.ts) - export type ServerMessage = ServerSafetyHistory | ServerSafetyUpdate | ServerSafetyUnavailable | ServerScopeDecisionReceipt | ServerHello | ServerRetryReceipt | ServerTextDelta | ServerThinkingDelta | ServerToolUseStart | ServerToolInputDelta | ServerToolUseComplete | ServerToolResult | ServerToolApprovalRequest | ServerResultMessage | ServerError | ServerStatus | ServerSessionInfo | ServerSessionHistory | ServerAskUserRequest | ServerAskUserListRequest | ServerAskUserRankRequest | ServerAskUserFormRequest | ServerAskAnswerReceipt | ServerPong | ServerLocationRequest | ServerMaskRequest | ServerActivitySnapshot | ServerActivityDelta | ServerMessageBlocks | ServerMessageLinks | ServerLocalExchangeResult | ServerHandoffDraft | ServerHandoffReceipt | InboxSnapshot | InboxDelta | ServerToolResolution | ServerSessionQueue | ServerDialogueHistory | ServerConversationOpened | ServerConversationClosed | ServerConversationEvent | ServerConversationWork | ServerConversationOutput | ServerConversationPermission | ServerTurnJournal | ServerUsage | ServerChatRetired | ServerAttachmentRead; + export type ServerMessage = ServerSafetyHistory | ServerSafetyUpdate | ServerSafetyUnavailable | ServerScopeDecisionReceipt | ServerHello | ServerRetryReceipt | ServerTextDelta | ServerThinkingDelta | ServerToolUseStart | ServerToolInputDelta | ServerToolUseComplete | ServerToolResult | ServerToolApprovalRequest | ServerResultMessage | ServerError | ServerStatus | ServerSessionInfo | ServerSessionHistory | ServerAskUserRequest | ServerAskUserListRequest | ServerAskUserRankRequest | ServerAskUserFormRequest | ServerAskAnswerReceipt | ServerPong | ServerLocationRequest | ServerMaskRequest | ServerActivitySnapshot | ServerActivityDelta | ServerMessageBlocks | ServerMessageLinks | ServerLocalExchangeResult | ServerHandoffDraft | ServerHandoffReceipt | InboxSnapshot | InboxDelta | ServerToolResolution | ServerSessionQueue | ServerDialogueHistory | ServerConversationOpened | ServerLivePersona | ServerConversationClosed | ServerConversationEvent | ServerConversationWork | ServerConversationOutput | ServerConversationPermission | ServerTurnJournal | ServerUsage | ServerChatRetired | ServerAttachmentRead; ServerMessageBlocks (packages/ui-sdk/src/protocol.ts) export interface ServerMessageBlocks extends SessionScoped { type: "message_blocks"; @@ -12695,6 +12866,21 @@ signatures (every public export and the types it is made of) expiresAt: number; capabilities: SpeechCapabilities; } + VoiceSettingsResponse (packages/ui-sdk/src/protocol.ts) + export interface VoiceSettingsResponse { + persona: { + value: string; + revision: number; + }; + livePersona: LivePersonaStatus; + } + VoiceSettingsUpdateRequest (packages/ui-sdk/src/protocol.ts) + export interface VoiceSettingsUpdateRequest { + persona?: { + value: string; + revision: number; + }; + } VoiceTokenResponse (packages/ui-sdk/src/protocol.ts) export interface VoiceTokenResponse { token: string; @@ -13245,13 +13431,24 @@ signatures (every public export and the types it is made of) unsupported: "unsupported"; }>; }, z.core.$loose>; + defaultVoice: z.ZodCatch>; disclosure: z.ZodObject<{ destinations: z.ZodArray; voiceService: z.ZodString; }, z.core.$loose>; + personaInstructionBytes: z.ZodCatch>; providerId: z.ZodString; + voices: z.ZodCatch>>>; }, z.core.$strip>>>; historyOwnerId: z.ZodOptional; + personaRef: z.ZodOptional>; + }, z.core.$strip>>>; requestId: z.ZodOptional; sessionId: z.ZodOptional; type: z.ZodLiteral<"conversation_start">; @@ -13756,13 +13953,24 @@ signatures (every public export and the types it is made of) unsupported: "unsupported"; }>; }, z.core.$loose>; + defaultVoice: z.ZodCatch>; disclosure: z.ZodObject<{ destinations: z.ZodArray; voiceService: z.ZodString; }, z.core.$loose>; + personaInstructionBytes: z.ZodCatch>; providerId: z.ZodString; + voices: z.ZodCatch>>>; }, z.core.$strip>>>; historyOwnerId: z.ZodOptional; + personaRef: z.ZodOptional>; + }, z.core.$strip>>>; requestId: z.ZodOptional; sessionId: z.ZodOptional; type: z.ZodLiteral<"conversation_start">; @@ -13987,6 +14195,12 @@ signatures (every public export and the types it is made of) start: z.ZodNumber; }, z.core.$loose>>; }, z.core.$loose>; + conversationPersonaRefSchema (packages/ui-sdk/src/schemas.ts) + const conversationPersonaRefSchema: z.ZodObject<{ + id: z.ZodString; + revision: z.ZodString; + voice: z.ZodOptional>; + }, z.core.$strip>; conversationProfileSchema (packages/ui-sdk/src/schemas.ts) const conversationProfileSchema: z.ZodObject<{ capabilities: z.ZodObject<{ @@ -14031,14 +14245,25 @@ signatures (every public export and the types it is made of) unsupported: "unsupported"; }>; }, z.core.$loose>; + defaultVoice: z.ZodCatch>; disclosure: z.ZodObject<{ destinations: z.ZodArray; voiceService: z.ZodString; }, z.core.$loose>; + personaInstructionBytes: z.ZodCatch>; providerId: z.ZodString; + voices: z.ZodCatch>>>; }, z.core.$strip>; conversationSampleRateSchema (packages/ui-sdk/src/schemas.ts) const conversationSampleRateSchema: z.ZodNumber; + conversationVoiceSchema (packages/ui-sdk/src/schemas.ts) + const conversationVoiceSchema: z.ZodObject<{ + id: z.ZodString; + label: z.ZodString; + }, z.core.$strip>; conversationWireEventSchema (packages/ui-sdk/src/schemas.ts) const conversationWireEventSchema: z.ZodUnion; @@ -17848,6 +18073,111 @@ signatures (every public export and the types it is made of) const isWebToolName: (name: string) => name is WebToolName; killWrapped (packages/ui-sdk/src/server/exec-wrapper.ts) export function killWrapped(proc: KillableProcess, config?: ExecWrapperConfig, signal?: NodeJS.Signals, onFailure?: (message: string) => void, bounded?: WrappedKillOptions): void; + livePersonaListResponseSchema (packages/ui-sdk/src/schemas.ts) + const livePersonaListResponseSchema: z.ZodObject<{ + personas: z.ZodArray>; + id: z.ZodString; + instructionBytes: z.ZodNumber; + invalid: z.ZodOptional>; + name: z.ZodString; + revision: z.ZodString; + voices: z.ZodRecord; + }, z.core.$loose>>; + }, z.core.$loose>; + livePersonaProviderStatusSchema (packages/ui-sdk/src/schemas.ts) + const livePersonaProviderStatusSchema: z.ZodObject<{ + maxInstructionBytes: z.ZodNumber; + overLimit: z.ZodBoolean; + staleVoice: z.ZodOptional; + voice: z.ZodString; + voiceSource: z.ZodEnum<{ + default: "default"; + persona: "persona"; + }>; + }, z.core.$loose>; + livePersonaSchema (packages/ui-sdk/src/schemas.ts) + const livePersonaSchema: z.ZodObject<{ + builtIn: z.ZodOptional>; + id: z.ZodString; + instructionBytes: z.ZodNumber; + instructions: z.ZodString; + invalid: z.ZodOptional>; + name: z.ZodString; + revision: z.ZodString; + voices: z.ZodRecord; + }, z.core.$loose>; + livePersonaStatusSchema (packages/ui-sdk/src/schemas.ts) + const livePersonaStatusSchema: z.ZodObject<{ + persona: z.ZodObject<{ + builtIn: z.ZodOptional>; + id: z.ZodString; + instructionBytes: z.ZodNumber; + invalid: z.ZodOptional>; + name: z.ZodString; + revision: z.ZodString; + voices: z.ZodRecord; + }, z.core.$loose>; + personaRef: z.ZodObject<{ + id: z.ZodString; + revision: z.ZodString; + }, z.core.$strip>; + providers: z.ZodRecord; + voice: z.ZodString; + voiceSource: z.ZodEnum<{ + default: "default"; + persona: "persona"; + }>; + }, z.core.$loose>>; + selected: z.ZodString; + selectedInvalid: z.ZodBoolean; + selectedMissing: z.ZodBoolean; + }, z.core.$loose>; + livePersonaSummarySchema (packages/ui-sdk/src/schemas.ts) + const livePersonaSummarySchema: z.ZodObject<{ + builtIn: z.ZodOptional>; + id: z.ZodString; + instructionBytes: z.ZodNumber; + invalid: z.ZodOptional>; + name: z.ZodString; + revision: z.ZodString; + voices: z.ZodRecord; + }, z.core.$loose>; localExchangeSchema (packages/ui-sdk/src/schemas.ts) const localExchangeSchema: z.ZodObject<{ answer: z.ZodUnknown; @@ -20146,12 +20476,54 @@ signatures (every public export and the types it is made of) unsupported: "unsupported"; }>; }, z.core.$loose>; + defaultVoice: z.ZodCatch>; disclosure: z.ZodObject<{ destinations: z.ZodArray; voiceService: z.ZodString; }, z.core.$loose>; + personaInstructionBytes: z.ZodCatch>; providerId: z.ZodString; + voices: z.ZodCatch>>>; }, z.core.$strip>>>>; + livePersona: z.ZodCatch>; + id: z.ZodString; + instructionBytes: z.ZodNumber; + invalid: z.ZodOptional>; + name: z.ZodString; + revision: z.ZodString; + voices: z.ZodRecord; + }, z.core.$loose>; + personaRef: z.ZodObject<{ + id: z.ZodString; + revision: z.ZodString; + }, z.core.$strip>; + providers: z.ZodRecord; + voice: z.ZodString; + voiceSource: z.ZodEnum<{ + default: "default"; + persona: "persona"; + }>; + }, z.core.$loose>>; + selected: z.ZodString; + selectedInvalid: z.ZodBoolean; + selectedMissing: z.ZodBoolean; + }, z.core.$loose>>>>; principalKey: z.ZodOptional; protocolRev: z.ZodNumber; safetyCapabilities: z.ZodCatch>>; type: z.ZodLiteral<"server_hello">; }, z.core.$loose>; + serverLivePersonaSchema (packages/ui-sdk/src/schemas.ts) + const serverLivePersonaSchema: z.ZodObject<{ + livePersona: z.ZodObject<{ + persona: z.ZodObject<{ + builtIn: z.ZodOptional>; + id: z.ZodString; + instructionBytes: z.ZodNumber; + invalid: z.ZodOptional>; + name: z.ZodString; + revision: z.ZodString; + voices: z.ZodRecord; + }, z.core.$loose>; + personaRef: z.ZodObject<{ + id: z.ZodString; + revision: z.ZodString; + }, z.core.$strip>; + providers: z.ZodRecord; + voice: z.ZodString; + voiceSource: z.ZodEnum<{ + default: "default"; + persona: "persona"; + }>; + }, z.core.$loose>>; + selected: z.ZodString; + selectedInvalid: z.ZodBoolean; + selectedMissing: z.ZodBoolean; + }, z.core.$loose>; + type: z.ZodLiteral<"live_persona">; + }, z.core.$loose>; serverLocalExchangeResultSchema (packages/ui-sdk/src/schemas.ts) const serverLocalExchangeResultSchema: z.ZodObject<{ exchangeId: z.ZodString; @@ -20874,12 +21286,54 @@ signatures (every public export and the types it is made of) unsupported: "unsupported"; }>; }, z.core.$loose>; + defaultVoice: z.ZodCatch>; disclosure: z.ZodObject<{ destinations: z.ZodArray; voiceService: z.ZodString; }, z.core.$loose>; + personaInstructionBytes: z.ZodCatch>; providerId: z.ZodString; + voices: z.ZodCatch>>>; }, z.core.$strip>>>>; + livePersona: z.ZodCatch>; + id: z.ZodString; + instructionBytes: z.ZodNumber; + invalid: z.ZodOptional>; + name: z.ZodString; + revision: z.ZodString; + voices: z.ZodRecord; + }, z.core.$loose>; + personaRef: z.ZodObject<{ + id: z.ZodString; + revision: z.ZodString; + }, z.core.$strip>; + providers: z.ZodRecord; + voice: z.ZodString; + voiceSource: z.ZodEnum<{ + default: "default"; + persona: "persona"; + }>; + }, z.core.$loose>>; + selected: z.ZodString; + selectedInvalid: z.ZodBoolean; + selectedMissing: z.ZodBoolean; + }, z.core.$loose>>>>; principalKey: z.ZodOptional; protocolRev: z.ZodNumber; safetyCapabilities: z.ZodCatch; sessionId: z.ZodOptional; type: z.ZodLiteral<"conversation_opened">; + }, z.core.$loose>, z.ZodObject<{ + livePersona: z.ZodObject<{ + persona: z.ZodObject<{ + builtIn: z.ZodOptional>; + id: z.ZodString; + instructionBytes: z.ZodNumber; + invalid: z.ZodOptional>; + name: z.ZodString; + revision: z.ZodString; + voices: z.ZodRecord; + }, z.core.$loose>; + personaRef: z.ZodObject<{ + id: z.ZodString; + revision: z.ZodString; + }, z.core.$strip>; + providers: z.ZodRecord; + voice: z.ZodString; + voiceSource: z.ZodEnum<{ + default: "default"; + persona: "persona"; + }>; + }, z.core.$loose>>; + selected: z.ZodString; + selectedInvalid: z.ZodBoolean; + selectedMissing: z.ZodBoolean; + }, z.core.$loose>; + type: z.ZodLiteral<"live_persona">; }, z.core.$loose>, z.ZodObject<{ conversationId: z.ZodString; epoch: z.ZodNumber; @@ -25950,6 +26442,49 @@ signatures (every public export and the types it is made of) export function validateVersionMinimum(value: unknown, owner: string, identity: string): string; visibleToolName (packages/ui-sdk/src/tool-contracts/contract.ts) export function visibleToolName(name: string, adapter: ToolAdapter): string; + voiceSettingsResponseSchema (packages/ui-sdk/src/schemas.ts) + const voiceSettingsResponseSchema: z.ZodObject<{ + livePersona: z.ZodObject<{ + persona: z.ZodObject<{ + builtIn: z.ZodOptional>; + id: z.ZodString; + instructionBytes: z.ZodNumber; + invalid: z.ZodOptional>; + name: z.ZodString; + revision: z.ZodString; + voices: z.ZodRecord; + }, z.core.$loose>; + personaRef: z.ZodObject<{ + id: z.ZodString; + revision: z.ZodString; + }, z.core.$strip>; + providers: z.ZodRecord; + voice: z.ZodString; + voiceSource: z.ZodEnum<{ + default: "default"; + persona: "persona"; + }>; + }, z.core.$loose>>; + selected: z.ZodString; + selectedInvalid: z.ZodBoolean; + selectedMissing: z.ZodBoolean; + }, z.core.$loose>; + persona: z.ZodObject<{ + revision: z.ZodNumber; + value: z.ZodString; + }, z.core.$strip>; + }, z.core.$loose>; webToolProviders (packages/ui-sdk/src/tool-contracts/web.ts) export function webToolProviders(input: Record): readonly string[]; wrapCommand (packages/ui-sdk/src/server/exec-wrapper.ts) diff --git a/docs/configuration.md b/docs/configuration.md index eab803de76..e97f14babd 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -434,7 +434,7 @@ never replace them. | Key | Type | Built-in default | | ---------- | ---------- | ------------------------------------------------------------------------------------------------- | -| `dirs` | `string[]` | `.git`, `node_modules`, `.claude`, `.agents`, `scripts`, `logs`, `tmp`, `workspaces`, `okf-dist`, `.brain/scratch`, `evals`, `context/scheduled-tasks` | +| `dirs` | `string[]` | `.git`, `node_modules`, `.claude`, `.agents`, `scripts`, `logs`, `tmp`, `workspaces`, `okf-dist`, `.brain/scratch`, `evals`, `context/scheduled-tasks`, `context/policies`, `_voice` | | `files` | `string[]` | `CLAUDE.md`, `README.md`, `AGENTS.md`, `GEMINI.md` | | `segments` | `string[]` | *(none in core; modules may add — e.g. speaking excludes `alt-decks`, `versions`, `deck`)* | @@ -457,6 +457,12 @@ validation, including `GEMINI.md` generated by `brain skills sync`. These are exact root-relative paths: a content note at `notes/GEMINI.md` is still included. Adding your own `exclude.files` entries keeps the built-in exclusions. +`_voice` holds the live-conversation personas a UI host edits in Settings +(`_voice/personas/.md`). Their instructions only shape how a voice service +speaks, so they never appear in search, briefings or agent context. The files +stay in Git and are plainly editable. Before 0.45.0 the folder was indexed like +any other; an existing brain drops it on the next `brain index`. + ```ts exclude: { dirs: ["drafts"], segments: ["private"] } ``` diff --git a/docs/extending/speech.md b/docs/extending/speech.md index 93ad248f0f..d883ab237d 100644 --- a/docs/extending/speech.md +++ b/docs/extending/speech.md @@ -362,7 +362,8 @@ and [qualification plan](../investigations/live-conversation-investigation.md#bo `createGptLiveConversationProvider(serverOwnedApiKey)` from `@schlessera/brain-ui-server` supplies the separately registered `CreateAppOptions.conversationProvider`. The server retains the credential; -the adapter fixes `gpt-live-1`, Live v1 primary WebSocket, PCM16/24 kHz, marin, +the adapter fixes `gpt-live-1`, Live v1 primary WebSocket, PCM16/24 kHz, marin +(or a persona's voice from its 38 declared voices, #3617), client delegation and `store:false`. The host's independently selected backend continues streaming chat progress, tool activity and interactive cards while voice input/output and asynchronous delegated work remain active. diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index bb341c7eff..037523c30f 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -144,6 +144,13 @@ row's real mounting check. They do not establish mounting by themselves. | `GET /api/voice/keyterms` | `mounted supported handler: GET /api/voice/keyterms` | N | | `GET /api/voice/overrides` | `mounted supported handler: GET /api/voice/overrides` | N | | `GET /api/voice/providers` | `mounted supported handler: GET /api/voice/providers` | R | +| `GET /api/voice/personas` | `mounted supported handler: GET /api/voice/personas` | VP | +| `POST /api/voice/personas` | `mounted supported handler: POST /api/voice/personas` | VP | +| `GET /api/voice/personas/:id` | `mounted supported handler: GET /api/voice/personas/:id` | VP | +| `PUT /api/voice/personas/:id` | `mounted supported handler: PUT /api/voice/personas/:id` | VP | +| `DELETE /api/voice/personas/:id` | `mounted supported handler: DELETE /api/voice/personas/:id` | VP | +| `GET /api/settings/voice` | `mounted supported handler: GET /api/settings/voice` | VP | +| `PUT /api/settings/voice` | `mounted supported handler: PUT /api/settings/voice` | VP | | `GET /api/voice/dictation/settings` | `mounted supported handler: GET /api/voice/dictation/settings` | R | | `PUT /api/voice/dictation/settings` | `mounted supported handler: PUT /api/voice/dictation/settings` | R | | `GET /api/voice/capabilities` | `mounted supported handler: GET /api/voice/capabilities` | R | @@ -514,6 +521,8 @@ no inbox thread. Detailed parser/intake/containment checks live in **R** — [selectable-dictation.test.ts](../packages/ui-server/tests/selectable-dictation.test.ts) covers exact provider selection, settings revisions/authority and held mint/upload binding; [saved-transcription.test.ts](../packages/ui-server/tests/saved-transcription.test.ts): concurrent real-route claims/retries, server hashes, body caps, account access, terminal outcomes, tombstones and keyless provider transport. +**VP — Live-conversation personas.** [live-personas.test.ts](../packages/ui-server/tests/live-personas.test.ts) covers the file codec, the empty 403 for agent, system and anonymous callers, revision conflicts, creation limits, the selection key and its delete ordering, Start resolution and a linked persona directory; [live-persona-host.test.ts](../packages/ui-server/tests/live-persona-host.test.ts) covers hello, the `live_persona` push and the frozen Start through the real socket handlers. + **RV — User history restoration.** `turn-revert.test.ts` exercises raw restoration, Undo, partial conflicts, operation identity, authorization, original voice and cross-session refusal, and observed quarantine restoration on real SQLite and diff --git a/docs/http-api.md b/docs/http-api.md index 8983e6387b..c11c70b291 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -10,7 +10,7 @@ compatibility guarantee. Authentication requirements are a separate property. A public liveness probe can be supported; an authenticated settings route can be internal. -The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion, individual safety-review and safety-recording recovery routes mounted by `createApp`: 180 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion, individual safety-review, safety-recording recovery and live-persona routes mounted by `createApp`: 187 unique declared method/path pairs, plus the conditional SPA fallback. It describes the current implementation, including limitations, rather than a proposed redesign. Unknown response fields must be tolerated. There is no HTTP API revision @@ -185,6 +185,13 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/tracks` | I | Resolve canonical imported-track evidence | Paired React track-block/export transport; no independent retrieval API selected. | | GET | `/api/tool-permissions` | I | List remembered always-allow grants | React approval settings; paired administrative transport. Permission behavior remains governed by its own contract. | | DELETE | `/api/tool-permissions/:tool` | I | Revoke one remembered grant | React approval settings; paired administrative transport. Permission behavior remains governed by its own contract. | +| GET | `/api/voice/personas` | S | List live-conversation personas, Standard first, without instruction text | Human owner/ambient only; others get an empty 403. | +| POST | `/api/voice/personas` | S | Create a persona file under `_voice/personas` | Human owner/ambient only; 409 `PERSONA_EXISTS`/`PERSONA_LIMIT`. | +| GET | `/api/voice/personas/:id` | S | Read one persona with its plain-text instructions | Human owner/ambient only. | +| PUT | `/api/voice/personas/:id` | S | Replace a persona at its current revision | Human owner/ambient only; stale writes return 409 `PERSONA_CHANGED` with `current`. | +| DELETE | `/api/voice/personas/:id` | S | Delete a persona at its current revision | Human owner/ambient only; a selected persona's selection becomes Standard first. | +| GET | `/api/settings/voice` | S | Read the live persona selection and its resolved status | Human owner/ambient only; independent of dictation settings. | +| PUT | `/api/settings/voice` | S | Save the live persona selection at its revision | Human owner/ambient only; stale writes return 409 `LIVE_PERSONA_CHANGED`. | | GET | `/api/voice/providers` | S | Read registered dictation providers and effective selection; never mint | Authenticated discovery, no-store. | | GET | `/api/voice/dictation/settings` | S | Read brain-wide dictation choice, SMART mode and revision | Independent of live conversation settings. | | PUT | `/api/voice/dictation/settings` | S | Save dictation choice with If-Match revision | Human owner/ambient only; stale writes never overwrite. | @@ -213,7 +220,7 @@ Authentication factories live in [auth.ts](../packages/ui-server/src/middleware/ [passkeys.ts](../packages/ui-server/src/middleware/passkeys.ts) and [principals.ts](../packages/ui-server/src/middleware/principals.ts). [app.ts](../packages/ui-server/src/app.ts) owns prefixing and middleware order. -All 180 declared endpoints are mounted regardless of backend, renderer or +All 187 declared endpoints are mounted regardless of backend, renderer or speech-provider availability: unavailable capabilities return the responses below rather than removing their handlers. Only static serving is conditional. @@ -1429,6 +1436,66 @@ saved switch (initially true). A failed exact mint returns generic 500 `{ error: "Voice session failed" }` without provider diagnostics or credentials. Bodyless legacy requests retain their previous response/error shape. +## Live-conversation personas + +Personas are Markdown files at `_voice/personas/.md` in the brain, where +`id` matches `[a-z0-9-]{1,48}` and never changes: + +```md +--- +schema: 1 +name: "Ithaca steward" +voices: + gemini-live: "Kore" + gpt-live: "marin" +--- +Calm, brief, plain words. Speak like a ship's steward reporting to Odysseus. +``` + +`name` is 1–40 characters after trimming, without control characters. `voices` +maps a live service id to that service's voice id; a missing key means the +service default, and keys for services this host does not register are kept. +The body is the instructions: plain text, line endings normalized to LF and +trimmed, at most 6,000 UTF-8 bytes. A file over that, with unreadable front +matter or with `schema` other than 1 is listed with `invalid` and cannot be +selected; so are usable files beyond the 20th by name. Standard is built in, +read-only and has no file. Core excludes `_voice` from the content index, so +persona text never reaches search or agent context. + +Every route is `no-store` and needs a human session of the brain (owner or +ambient); others receive `403` with an empty body. + +- `GET /api/voice/personas` returns `{ personas: LivePersonaSummary[] }`: + Standard first, then by name. Summaries carry `id`, `name`, `voices`, + `instructionBytes`, `revision` (sha-256 hex of the file), and `builtIn` or + `invalid` when they apply, never the instructions. +- `GET /api/voice/personas/:id` returns `LivePersona` (the summary plus + `instructions`) or 404 `PERSONA_NOT_FOUND`. +- `POST /api/voice/personas` takes `{ id?, name, voices, instructions }`. Without + `id` one is derived from `name`. It returns 201 with the persona, 400 + `PERSONA_INVALID` with a `reason`, 409 `PERSONA_EXISTS` or 409 `PERSONA_LIMIT`. + A new persona is not selected. +- `PUT /api/voice/personas/:id` takes `{ baseRevision, name, voices, + instructions }` and replaces the file atomically. A revision mismatch returns + 409 `{ error: "PERSONA_CHANGED", current }`; Standard returns 409 + `PERSONA_READ_ONLY`. +- `DELETE /api/voice/personas/:id?baseRevision=` returns 204. When the + persona is selected, the selection is saved as Standard first and the file is + deleted only after that write succeeds. +- `GET /api/settings/voice` returns `{ persona: { value, revision }, + livePersona: LivePersonaStatus }`. `PUT` takes `{ persona: { value, revision } }`; + a missing or invalid persona returns 400, a stale revision 409 + `{ error: "LIVE_PERSONA_CHANGED", persona, livePersona }`. The selection is the + `voice.live.persona` server setting with its own revision; a corrupt row reads + as Standard at revision 0. + +Writes go through the brain's files with an atomic replace, inside a +directory chain opened without following links; storage that is unavailable or +redirected returns 503 `PERSONA_STORAGE`. An edit made directly to a file is +equally valid and applies from the next Start. Nothing here opens a provider, +the microphone or a running conversation, which keeps the persona frozen at its +Start ([wire](integration-contract/wire.md#live-conversation-personas-additive-0450-3617)). + ## Saved-audio transcription The protected `GET /api/voice/capabilities` returns `VoiceCapabilitiesResponse` diff --git a/docs/integration-contract.md b/docs/integration-contract.md index f648d4c178..2cd7e9afd4 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -52,6 +52,27 @@ client refuses a page that carries the new kinds. See and [the package API](integration-contract/package-api.md#retained-dialogue-data-3177). This ships in a minor; no breaking ruling is required. +## Live-conversation personas (additive, 0.45.0, #3617) + +A persona is authored Markdown at `_voice/personas/.md` in the brain: a +name, one voice per live service and plain-text speaking-style instructions. +Core excludes `_voice` from the content index by default +([configuration](configuration.md#exclude)). New owner-only routes read and +write personas with sha-256 revisions, and `GET/PUT /api/settings/voice` +carries the selection (`voice.live.persona`, its own revision) in the server +settings store, never in `brain.db`. `LiveConversationProvider` gains optional +`voices`, `defaultVoice` and `personaInstructionBytes`, mirrored on +`ConversationProfile` outside the disclosure a Start must echo; +`LiveConversationOpenOptions.persona` carries the persona frozen at Start. +`server_hello.livePersona` and the new `live_persona` frame describe the +selected persona to human sessions; `conversation_start.personaRef` echoes it, +with `voice: "default"` as the explicit one-time stale-voice override. A +conversation that sends no persona keeps exact current behaviour. See +[wire](integration-contract/wire.md#live-conversation-personas-additive-0450-3617), +[HTTP](integration-contract/http.md#live-conversation-personas-additive-0450-3617) +and [the package API](integration-contract/package-api.md#live-conversation-personas-additive-0450-3617). +This ships in a minor; no breaking ruling is required. + ## Choosing the dictation provider in the app (additive, 0.45.0, #3709) `openSettings("voice")` opens a new Settings › Voice pane, which holds the diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 4bdb3531d4..bf9d6ca408 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -1168,6 +1168,18 @@ headers preserve effective-provider resolution. Retry provider changes return error codes, response schemas and operation binding are supported HTTP promises. +### Live-conversation personas (additive, 0.45.0, #3617) + +The [persona routes](../http-api.md#live-conversation-personas) read and write +`_voice/personas/.md` and the selection. Every route requires a human +session of the brain (an owner, or an ambient-auth account); delegated agent, +worker and system principals receive `403` with an empty body. Writes replace +the file atomically inside the brain and never follow a link out of +`_voice/personas`. Revisions are the sha-256 of the file bytes; `PUT` and +`DELETE` must name the current one or receive `409 PERSONA_CHANGED`. Error +bodies are fixed codes, never persona text. Route paths, request and response +schemas, revision semantics and error codes are supported HTTP promises. + ### Checkpoint cleanup diagnostics (additive, #3815) Authenticated `GET /api/status` adds `journalCleanup`: `retained` contains diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 30bfe177f3..9da8f4ed03 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5093,6 +5093,37 @@ acknowledgement promise. Reviewed-only tasks keep their existing admission and result behavior. The [wire/disclosure amendment](wire.md#live-orientation-disclosure-and-progress-additive-3623) adds no frame, revision or client permission grant. +## Live-conversation personas (additive, 0.45.0, #3617) + +`LiveConversationProvider` (`@schlessera/brain-ui-sdk/server`) gains three +optional fields, all present or all absent: `voices: readonly +ConversationVoice[]` (one to 128 unique `{ id, label }`), `defaultVoice` (one +of them) and `personaInstructionBytes` (1 to 6,000). `assertLiveConversationProvider` +refuses a partial or inconsistent set. A provider without them supports only +Standard, and the host refuses any other persona for it. + +`LiveConversationOpenOptions.persona?: ConversationPersona` (`{ voice?: string; +instructions: string }`) is the persona the host froze at Start. Absent means +Standard and must reproduce the provider's behaviour before personas exactly. +`voice` is one of the provider's `voices`; absent means `defaultVoice`. +`instructions` is normalized plain text (line endings to LF, trimmed) within +`personaInstructionBytes`. A provider frames it after its own fixed rules and +never lets it reach tool declarations, permissions or history; the first-party +adapters refuse an unoffered voice or an over-cap text rather than substitute +or truncate. This adds fields to the existing live-conversation seam; it is not +a new extension point. + +`@schlessera/brain-ui-sdk/protocol` exports `ConversationVoice`, +`ConversationPersonaRef`, `LivePersona`, `LivePersonaSummary`, +`LivePersonaInvalidReason`, `LivePersonaListResponse`, +`LivePersonaCreateRequest`, `LivePersonaUpdateRequest`, +`LivePersonaProviderStatus`, `LivePersonaStatus`, `VoiceSettingsResponse`, +`VoiceSettingsUpdateRequest`, `ServerLivePersona`, `STANDARD_PERSONA_ID`, +`STANDARD_PERSONA_REVISION` and `LIVE_PERSONA_LIMITS`; the schemas entry point +exports their zod schemas. In `@schlessera/brain-ui-react`, the conversation +client's state gains `livePersona: LivePersonaStatus | null` and its Start +echoes `livePersona.personaRef`; Settings › Voice gains the Persona group. + ## Observed live content map (additive, 0.45.0, #3630) `ConversationOrientation.knowledge[].topic` gains `content_map`. It carries diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index f29304d0cd..522582d1bd 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -2748,6 +2748,67 @@ observation alone draws neither. A client from an earlier minor validates `DialogueEvidence` exhaustively and refuses a page that carries one of these kinds; the first-party client ships with the host in lockstep. +### Live-conversation personas (additive, 0.45.0, #3617) + +A persona customizes how a live conversation sounds; it never grants tool, +data, permission, task-admission or history authority. + +**Profile.** `ConversationProfile` gains optional `voices: { id, label }[]`, +`defaultVoice` and `personaInstructionBytes`, copied from the registered +provider. They describe persona support. The disclosure a Start must echo is +still exactly `providerId`, `capabilities` and `disclosure`, so a client that +drops or does not know these fields keeps starting. The first-party adapters +declare 30 Gemini Live voices (default `Kore`, 6,000 bytes) and 38 GPT-Live +voices (default `marin`, 2,000 bytes), checked against the providers' +documentation. The byte caps are application limits, not provider guarantees. + +**Status.** `LivePersonaStatus` is `{ selected, selectedMissing, +selectedInvalid, persona, personaRef: { id, revision }, providers }`. `persona` +is the selected `LivePersonaSummary` (Standard when the selected file is +missing). `providers` maps each persona-capable registered service to +`{ voice, voiceSource: "persona" | "default", staleVoice?, maxInstructionBytes, +overLimit }` and is empty for an invalid persona. Standard is +`{ id: "standard", revision: "builtin", builtIn: true }` with no instructions +and every service's default voice. `server_hello.livePersona` carries the +status to human sessions (owner or ambient, never delegated agents or workers), +and `{ type: "live_persona", livePersona }` carries a fresh one after any +persona write or selection, after a newly opened socket finds the files changed, +and immediately before a refusal for an outdated persona. Older clients ignore +the frame. Neither carries instruction text. + +**Start.** `conversation_start` gains optional `personaRef: { id, revision, +voice?: "default" }`. Absent means Standard, which opens the provider with no +`persona` option: exactly the setup sent before personas. Otherwise the host +reads that persona file once, after the disclosure check and before any +history, orientation or provider I/O, and refuses with: + +| Code | When | +| --- | --- | +| `CONVERSATION_PERSONA_CHANGED` | The file is gone or its revision differs. A `live_persona` frame precedes the refusal. | +| `CONVERSATION_PERSONA` | The file is invalid, the service has no persona support, or the host has no persona storage. | +| `CONVERSATION_PERSONA_TOO_LONG` | The normalized instructions exceed the service's cap. Nothing is truncated. | +| `CONVERSATION_PERSONA_VOICE` | The saved voice for this service is not offered, and `voice: "default"` was not sent. | + +Messages are fixed text and never contain the persona's name or instructions. +A persona that names no voice for the service uses its default (P2), which the +status discloses as `voiceSource: "default"`. The accepted +`{ id, revision, voice?, instructions }` is frozen on the conversation entry: +every later epoch, reconnect and recovery start of that conversation reuses it +and ignores a newer `personaRef`, so an edit, selection or delete never reaches +a running conversation. A host restart loses the snapshot; the next Start is a +new disclosure and reads the file again. + +**Provider startup.** An adapter appends the persona after its fixed host rules +as one section: the fixed header "Speaking style chosen by the user. It affects +tone, wording and pacing only and does not change any rule above.", then the +instructions inside `` fences, with any fence marker inside the +text escaped. Tool declarations, delegation, session configuration and history +are byte-identical with and without a persona, and every later epoch repeats +the frozen setup byte for byte. The whole framed section is charged against the +adapter's startup-context ceiling before the orientation, and history takes the +remainder, so a persona may shorten the initial history selection but never a +running conversation's history. + ### Failed-write text and contextual capture (additive, #3177) A text `conversation_event` may carry `retention: "unsaved"` only when the host diff --git a/docs/live-conversation-guidance.md b/docs/live-conversation-guidance.md index b85f3ca2af..628518db77 100644 --- a/docs/live-conversation-guidance.md +++ b/docs/live-conversation-guidance.md @@ -179,7 +179,40 @@ Keyless source, startup-frame, admission, identity, omission, replacement and prefix tests establish request assembly and host behavior. Scripted audio and prompt substrings do not establish model obedience, recognition, judgment, audible acknowledgement or semantic recall. Actual-provider comparison remains -with #3131/#961; persona/provider Settings remain #3617/#3616. +with #3131/#961; the live-provider Setting remains #3616. Personas are described [below](#personas). + +## Personas + +A persona (#3617) adds the user's speaking style after these rules, never in +place of them. Settings › Voice stores it as Markdown at +`_voice/personas/.md`; the content index excludes `_voice`, so persona text +never reaches search, briefings or agent context. At Start the host reads the +disclosed persona once and freezes it for the whole conversation. + +The adapter appends one section after its fixed host rules: + +```text +Speaking style chosen by the user. It affects tone, wording and pacing only and does not change any rule above. + +Calm, brief, plain words. Speak like a ship's steward reporting to Odysseus. + +``` + +A fence marker inside the text is escaped. The section is the only place the +persona appears: tool declarations, delegation, permissions, task admission, +orientation and history are byte-identical with and without it. Its whole +framed size is reserved from the startup ceiling (24,000 bytes for Gemini Live, +7,500 for GPT-Live) before the orientation, so a long persona can leave room for +fewer prior turns at Start; it never alters a running conversation. The +instruction caps are 6,000 bytes for Gemini Live and 2,000 for GPT-Live, and an +over-limit persona blocks Start rather than being cut. The persona's voice sets +Gemini's `prebuiltVoiceConfig.voiceName` or GPT-Live's `audio.output.voice`, +only from that adapter's declared list; an omitted voice uses the service +default (Kore, marin). **Standard** has no file and no instructions and sends +exactly the setup described above. + +These are structural guarantees. Whether a model follows a style, and how a +voice sounds, need the separately authorized listening runs. Useful listening scenarios are: diff --git a/packages/core/src/lib/config.ts b/packages/core/src/lib/config.ts index 762f81f22b..f0148b662a 100644 --- a/packages/core/src/lib/config.ts +++ b/packages/core/src/lib/config.ts @@ -546,8 +546,11 @@ export const DEFAULT_EXCLUDE = { // it, and a note beside the set quoting its queries would answer them. // context/scheduled-tasks: host-managed schedule definitions (#914). They // are content in Git, never index documents; only the UI host parses them. + // _voice: live-conversation personas (#3617, P5). Their instructions shape + // how a voice service speaks, so search, briefings and agent context never + // see them; the files stay in Git and editable on disk. dirs: [".git", "node_modules", ".claude", ".agents", "scripts", "logs", "tmp", "workspaces", "okf-dist", SCRATCH_DIR, "evals", - "context/scheduled-tasks", "context/policies"], + "context/scheduled-tasks", "context/policies", "_voice"], files: ["CLAUDE.md", "README.md", "AGENTS.md", "GEMINI.md"], segments: [] as string[], }; diff --git a/packages/core/tests/voice-namespace-exclude.test.ts b/packages/core/tests/voice-namespace-exclude.test.ts new file mode 100644 index 0000000000..1188eb8df8 --- /dev/null +++ b/packages/core/tests/voice-namespace-exclude.test.ts @@ -0,0 +1,58 @@ +/** + * Live-conversation personas (#3617, P5) are authored Markdown under + * `_voice/personas/`. Their instructions only shape how a voice service + * speaks, so no content scan indexes them: search and context assembly never + * return them, and a forced rebuild leaves the files intact. + */ +import { afterAll, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; + +import { DEFAULT_EXCLUDE } from "../src/lib/config"; +import { assembleContext } from "../src/lib/context-assembler"; +import { initContext } from "../src/lib/context"; +import { openDatabase } from "../src/lib/db"; +import { indexAll } from "../src/lib/indexer"; +import { getMarkdownFiles } from "../src/lib/indexer/scan"; +import { hybridSearch } from "../src/lib/search-engine"; + +const temps: string[] = []; +afterAll(() => { for (const dir of temps) rmSync(dir, { recursive: true, force: true }); }); + +const MARKER = "penelopeloom"; +const PERSONA = `---\nschema: 1\nname: Ithaca steward\nvoices:\n gemini-live: Kore\n---\nSpeak like a ship's steward reporting to Odysseus about the ${MARKER}.\n`; + +test("_voice is a default exclusion", () => { + expect(DEFAULT_EXCLUDE.dirs).toContain("_voice"); +}); + +test("persona files under _voice/personas never reach the index, search or context assembly", async () => { + const root = mkdtempSync(join(tmpdir(), "brain-voice-exclude-")); + temps.push(root); + mkdirSync(join(root, "_voice/personas"), { recursive: true }); + writeFileSync(join(root, "_voice/personas/ithaca-steward.md"), PERSONA); + mkdirSync(join(root, "notes")); + writeFileSync(join(root, "notes/loom.md"), `---\ntitle: Loom\ntype: note\n---\n\nPenelope weaves at the ${MARKER} each day.\n`); + // A sibling whose name only starts like the namespace stays ordinary content. + mkdirSync(join(root, "_voice-notes")); + writeFileSync(join(root, "_voice-notes/plan.md"), `---\ntitle: Plan\ntype: note\n---\n\nThe ${MARKER} plan.\n`); + + const ctx = await initContext({ root }); + expect(getMarkdownFiles(root, ctx.taxonomy)).toEqual(["_voice-notes/plan.md", "notes/loom.md"]); + const db = openDatabase(ctx.dbPath); + try { + await indexAll(db, { root, taxonomy: ctx.taxonomy, quiet: true, graph: false, force: true }); + const paths = (db.prepare("SELECT path FROM documents ORDER BY path").all() as { path: string }[]).map((r) => r.path); + expect(paths).toEqual(["_voice-notes/plan.md", "notes/loom.md"]); + + const found = await hybridSearch(db, { query: MARKER, mode: "fts", rerank: "none", now: new Date("2026-07-12") }); + expect(found.results.map((r) => r.path).sort()).toEqual(["_voice-notes/plan.md", "notes/loom.md"]); + + const briefing = await assembleContext(db, ctx, { query: MARKER, maxTokens: 4000, now: new Date("2026-07-12") }); + expect(briefing).toContain("Penelope weaves"); + expect(briefing).not.toContain("ship's steward"); + expect(briefing).not.toContain("_voice/personas"); + } finally { db.close(); } + expect(readFileSync(join(root, "_voice/personas/ithaca-steward.md"), "utf8")).toBe(PERSONA); +}); diff --git a/packages/ui-react/README.md b/packages/ui-react/README.md index 004a44d537..de60d96f62 100644 --- a/packages/ui-react/README.md +++ b/packages/ui-react/README.md @@ -126,6 +126,31 @@ changes keep it; a new take or a send clears it. It is announced once politely, never takes focus, and offers no automatic restart. Distinct local microphone notices remain visible afterward. + +### Live-conversation personas + +The Persona group in Settings › Voice lists the built-in **Standard** persona +and the personas you add, each a Markdown file at `_voice/personas/.md` in +your brain. A persona has a name, one voice per live service (or that +service's default) and **How it speaks**, plain-text instructions about tone, +brevity and manner. Picking a radio saves the brain-wide selection at once. +**+ New persona** and each row's **⋯** menu (Edit, Rename, Duplicate, Delete; +desktop also shows **Edit**) open the editor in the pane. The editor counts the +instructions in exact UTF-8 bytes per service: GPT-Live accepts 2,000 and Gemini +Live 6,000, so a persona can be fine for one service and too long for the other. +Nothing is ever truncated; Start refuses instead. A save that another device +overtook keeps your text and offers **Show the newer version**; leaving with +unsaved edits asks first. Deleting the selected persona moves the selection to +Standard. Files that cannot be used are listed with the reason and cannot be +selected. + +Edits, selection and delete apply from the next Start. A running conversation, +including its reconnects, keeps the persona it started with. The connection +client's state carries `livePersona`, the selected persona as the host resolves +it per service (voice, default or stale voice, over-limit), and Start echoes +its `personaRef`. A persona shapes speech only; it cannot change what brain may +do, see or approve. The pane never opens the microphone or a provider. + ### Recording on the device Set `localCapture: true` and a stable `storagePrefix` on a persistent root to @@ -763,7 +788,8 @@ offers **Refresh and retry**. Sync and reset use immediate layout updates. Settings exposes the same nine panes on phone, tablet and desktop: Appearance & input, Models, Voice, Accounts, Skills, Modules, Storage, Security, and Devices & agents. -Voice holds the dictation service (see [Choosing the dictation service](#choosing-the-dictation-service)); +Voice holds the dictation service (see [Choosing the dictation service](#choosing-the-dictation-service)) +and the live-conversation persona (see [Live-conversation personas](#live-conversation-personas)); its groups each own their route and state, so the live-conversation service can join the same pane without sharing a revision. Theme and the single-key shortcut switch apply only on this device and live in diff --git a/packages/ui-react/src/components/settings/persona-settings.tsx b/packages/ui-react/src/components/settings/persona-settings.tsx new file mode 100644 index 0000000000..262f2120cf --- /dev/null +++ b/packages/ui-react/src/components/settings/persona-settings.tsx @@ -0,0 +1,397 @@ +import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties } from "react"; +import { useStore } from "zustand"; +import { Button, Callout, IconButton, Placeholder, TextButton } from "@schlessera/brain-ui-kit"; +import { + LIVE_PERSONA_LIMITS, + STANDARD_PERSONA_ID, + type ConversationProfile, + type LivePersona, + type LivePersonaInvalidReason, + type LivePersonaStatus, + type LivePersonaSummary, +} from "@schlessera/brain-ui-sdk/protocol"; +import { useBrainUiRoot } from "../../root-context.js"; +import { ApiRequestError } from "../../lib/api-client.js"; +import { conversationService } from "../../voice/conversation-client.js"; + +/** What Settings says about a persona file that cannot be used. */ +const PERSONA_REASON: Record = { + front_matter: "its front matter can't be read", + schema: "it was written for a different version", + name: "it needs a name of up to 40 characters", + voices: "a voice entry isn't valid", + too_long: `its instructions are over ${LIVE_PERSONA_LIMITS.maxInstructionBytes.toLocaleString("en-US")} bytes`, + encoding: "it isn't UTF-8 text", + over_count: `only the first ${LIVE_PERSONA_LIMITS.maxPersonas} personas can be used`, +}; + +const bytes = (text: string): number => new TextEncoder().encode(text.replace(/\r\n?/g, "\n").trim()).byteLength; +const count = (n: number): string => n.toLocaleString("en-US"); + +interface Draft { name: string; voices: Record; instructions: string } +type View = + | { kind: "list" } + | { kind: "edit"; base: LivePersona | null; draft: Draft; errors: string[]; conflict: LivePersona | null; saving: boolean; focusName?: boolean }; + +/** Persona-capable live services on this host, from the connection's profile. */ +function personaServices(profile: ConversationProfile | null): ConversationProfile[] { + return profile && profile.voices && profile.defaultVoice && profile.personaInstructionBytes !== undefined ? [profile] : []; +} + +/** + * The Persona group of Settings › Voice (#3617). Authored personas are + * Markdown in the brain (`_voice/personas/.md`); the selection is a + * brain-wide setting with its own revision. Like Dictation beside it, this + * group never opens the microphone or a provider. Edits, selection and delete + * apply from the next Start; a running conversation keeps the persona it + * started with. Instruction text is plain text everywhere, never markup. + */ +export function PersonaSettings({ active }: { active: boolean }) { + const root = useBrainUiRoot(); + const api = root.api; + const profile = useStore(root.connection.conversation.state, (s) => s.conversationProfile); + const pushed = useStore(root.connection.conversation.state, (s) => s.livePersona); + const services = personaServices(profile); + const [personas, setPersonas] = useState(null); + const [selection, setSelection] = useState<{ value: string; revision: number } | null>(null); + const [status, setStatus] = useState(null); + const [load, setLoad] = useState<"idle" | "loading" | "failed" | "forbidden">("idle"); + const [notice, setNotice] = useState(""); + const [failure, setFailure] = useState(""); + const [view, setView] = useState({ kind: "list" }); + const [confirm, setConfirm] = useState(null); + const [leave, setLeave] = useState<(() => void) | null>(null); + const generation = useRef(0); + + const refresh = useCallback(async () => { + const mine = ++generation.current; + setLoad((current) => current === "idle" || current === "failed" ? "loading" : current); + try { + const [list, settings] = await Promise.all([api.livePersonas(), api.voiceSettings()]); + if (mine !== generation.current) return; + setPersonas(list.personas); setSelection(settings.persona); setStatus(settings.livePersona); setLoad("idle"); + } catch (error) { + if (mine !== generation.current) return; + setLoad(error instanceof ApiRequestError && error.status === 403 ? "forbidden" : "failed"); + } + }, [api]); + + // Opening the pane, a pushed change and a return to the window read the files again. + useEffect(() => { if (active) void refresh(); }, [active, refresh, pushed]); + useEffect(() => { + if (!active) return; + const again = () => { if (document.visibilityState !== "hidden") void refresh(); }; + window.addEventListener("focus", again); + return () => window.removeEventListener("focus", again); + }, [active, refresh]); + + const editing = view.kind === "edit" ? view : null; + const dirty = !!editing && JSON.stringify(editing.draft) !== JSON.stringify(editing.base + ? { name: editing.base.name, voices: editing.base.voices, instructions: editing.base.instructions } + : { name: "", voices: {}, instructions: "" }); + useLayoutEffect(() => { + const ui = root.stores.ui.getState(); + ui.setSettingsNavigationGuard(dirty ? (go) => setLeave(() => go) : null); + return () => root.stores.ui.getState().setSettingsNavigationGuard(null); + }, [root, dirty]); + + const select = async (value: string) => { + if (!selection) return; + const before = selection; + // Shown at once, as the Dictation radios do; a refused save puts it back. + setSelection({ value, revision: before.revision }); + setStatus((current) => current && { ...current, selectedMissing: false }); + setNotice("Saving…"); setFailure(""); + try { + const saved = await api.saveLivePersonaSelection(value, before.revision); + setSelection(saved.persona); setStatus(saved.livePersona); setNotice(""); + } catch (error) { + if (error instanceof ApiRequestError && error.message === "LIVE_PERSONA_CHANGED") { + setNotice("Changed on another device. Showing the latest."); await refresh(); return; + } + setSelection(before); + setNotice(""); setFailure(error instanceof ApiRequestError && error.status === 403 ? "Only the owner can change this." : "Couldn't save the persona choice."); + } + }; + + const openEditor = async (summary: LivePersonaSummary | null, focusName = false) => { + setFailure(""); + if (!summary) { + const voices: Record = {}; + setView({ kind: "edit", base: null, draft: { name: "", voices, instructions: "" }, errors: [], conflict: null, saving: false, focusName: true }); + return; + } + try { + const base = await api.livePersona(summary.id); + setView({ kind: "edit", base, draft: { name: base.name, voices: { ...base.voices }, instructions: base.instructions }, errors: [], conflict: null, saving: false, focusName }); + } catch { setFailure("Couldn't open that persona."); void refresh(); } + }; + + const duplicate = async (summary: LivePersonaSummary) => { + setFailure(""); + try { + const source = await api.livePersona(summary.id); + const name = [...`${source.name} (copy)`].slice(0, LIVE_PERSONA_LIMITS.maxNameChars).join(""); + for (let n = 1; n < 50; n++) { + const id = `${source.id}-copy${n > 1 ? `-${n}` : ""}`.slice(0, LIVE_PERSONA_LIMITS.maxIdChars); + try { await api.createLivePersona({ id, name, voices: source.voices, instructions: source.instructions }); break; } + catch (error) { if (!(error instanceof ApiRequestError && error.message === "PERSONA_EXISTS")) throw error; } + } + setView({ kind: "list" }); await refresh(); + } catch (error) { setFailure(writeFailure(error)); } + }; + + const remove = async (summary: LivePersonaSummary) => { + setConfirm(null); setFailure(""); + try { + await api.deleteLivePersona(summary.id, summary.revision); + setView({ kind: "list" }); await refresh(); + } catch (error) { + if (error instanceof ApiRequestError && error.message === "PERSONA_CHANGED") { setNotice("Changed on another device. Showing the latest."); await refresh(); return; } + setFailure(writeFailure(error)); + } + }; + + const save = async (current: Extract) => { + const errors = draftErrors(current.draft); + if (errors.length) { setView({ ...current, errors }); return; } + setView({ ...current, errors: [], saving: true }); + try { + // After a conflict, saving again is the deliberate choice to replace the newer version. + if (current.base) await api.updateLivePersona(current.base.id, { baseRevision: (current.conflict ?? current.base).revision, ...current.draft }); + else await api.createLivePersona(current.draft); + setView({ kind: "list" }); await refresh(); + } catch (error) { + if (error instanceof ApiRequestError && error.message === "PERSONA_CHANGED" && current.base) { + const newer = await api.livePersona(current.base.id).catch(() => null); + setView({ ...current, saving: false, conflict: newer ?? current.base, errors: [] }); + return; + } + setView({ ...current, saving: false, errors: [writeFailure(error)] }); + } + }; + + const discardAndLeave = () => { const go = leave; setLeave(null); setView({ kind: "list" }); root.stores.ui.getState().setSettingsNavigationGuard(null); go?.(); }; + + return
+ {editing + ? setView({ ...editing, draft })} + onBack={() => dirty ? setLeave(() => () => setView({ kind: "list" })) : setView({ kind: "list" })} + onSave={() => void save(editing)} + onShowNewer={() => editing.conflict && setView({ ...editing, base: editing.conflict, conflict: null, + draft: { name: editing.conflict.name, voices: { ...editing.conflict.voices }, instructions: editing.conflict.instructions } })} + onDuplicate={() => editing.base && void duplicate(editing.base)} + onDelete={() => editing.base && setConfirm(editing.base)} /> + : void refresh()} onSelect={(id) => void select(id)} onNew={() => void openEditor(null)} + onEdit={(p, rename) => void openEditor(p, rename)} onDuplicate={(p) => void duplicate(p)} onDelete={setConfirm} />} + + {confirm &&
+

Delete “{confirm.name}”?

+

+ {selection?.value === confirm.id ? "It's the selected persona. New conversations will use Standard. " : ""}A conversation already running keeps it until it ends. +

+
+
+
} + + {leave &&
+

Keep your unsaved changes?

+
+
+
} + +
{notice}
+ {failure &&
} +
; +} + +function writeFailure(error: unknown): string { + if (error instanceof ApiRequestError) { + if (error.status === 403) return "Only the owner can change personas."; + if (error.message === "PERSONA_LIMIT") return `You can keep up to ${LIVE_PERSONA_LIMITS.maxPersonas} personas. Delete one first.`; + if (error.message === "PERSONA_EXISTS") return "A persona with that name already exists. Choose another name."; + if (error.message === "PERSONA_NOT_FOUND") return "That persona was removed on another device."; + } + return "Couldn't save the persona. Try again."; +} + +function draftErrors(draft: Draft): string[] { + const errors: string[] = []; + const name = draft.name.trim(); + if (!name || [...name].length > LIVE_PERSONA_LIMITS.maxNameChars || /\p{Cc}/u.test(name)) errors.push(`Give the persona a name (up to ${LIVE_PERSONA_LIMITS.maxNameChars} characters).`); + const size = bytes(draft.instructions); + if (size > LIVE_PERSONA_LIMITS.maxInstructionBytes) errors.push(`Shorten “How it speaks” to ${count(LIVE_PERSONA_LIMITS.maxInstructionBytes)} bytes (now ${count(size)}).`); + return errors; +} + +const ROW = "flex min-h-[52px] items-center gap-3 rounded-lg border px-3 py-2"; + +function PersonaList(p: { + personas: LivePersonaSummary[] | null; status: LivePersonaStatus | null; selected: string | null; services: ConversationProfile[]; + load: "idle" | "loading" | "failed" | "forbidden"; + onReload: () => void; onSelect: (id: string) => void; onNew: () => void; + onEdit: (persona: LivePersonaSummary, rename: boolean) => void; onDuplicate: (persona: LivePersonaSummary) => void; onDelete: (persona: LivePersonaSummary) => void; +}) { + const id = useId(); + const heading = `${id}-heading`; + const own = p.personas?.filter((persona) => !persona.builtIn) ?? []; + const meta = (persona: LivePersonaSummary): string => persona.builtIn ? "built in · default voices" + : persona.invalid ? `Can't be used: ${PERSONA_REASON[persona.invalid]}` + : [...p.services.map((service) => persona.voices[service.providerId] ?? "default voice"), `${count(persona.instructionBytes)} bytes`].join(" · "); + return <> +
+

Persona

+

How live conversation sounds: a voice per service and a speaking style. Used from the next Start; it never changes what brain may do.

+
+ {p.load === "loading" && !p.personas && } + {p.load === "forbidden" &&

Only the owner can see and change personas.

} + {p.load === "failed" &&
+ +
+
} + {p.personas && <> + {p.status?.selectedMissing &&

The selected persona was removed. New conversations use Standard.

} +
+ {p.personas.map((persona) => { + const checked = persona.builtIn ? p.selected === STANDARD_PERSONA_ID || !!p.status?.selectedMissing : p.selected === persona.id; + const disabled = !!persona.invalid; + return
+ + {!persona.builtIn && <> + p.onEdit(persona, false)} /> + p.onEdit(persona, false)} onRename={() => p.onEdit(persona, true)} + onDuplicate={persona.invalid ? undefined : () => p.onDuplicate(persona)} onDelete={() => p.onDelete(persona)} /> + } +
; + })} +
+ {own.length === 0 &&

Only Standard so far. Personas you add appear here.

} +
+ } + ; +} + +function PersonaMenu(p: { name: string; onEdit: () => void; onRename?: () => void; onDuplicate?: () => void; onDelete: () => void }) { + const [open, setOpen] = useState(false); + const menuId = useId(); + const trigger = useRef(null); + const first = useRef(null); + useEffect(() => { if (open) first.current?.focus(); }, [open]); + const items = [["Edit", p.onEdit], ["Rename", p.onRename], ["Duplicate", p.onDuplicate], ["Delete", p.onDelete]] + .filter((item): item is [string, () => void] => !!item[1]); + const close = () => { setOpen(false); trigger.current?.focus(); }; + return + setOpen((v) => !v)} data-persona-more="" /> + {open && } + ; +} + +function PersonaEditor(p: { + view: Extract; services: ConversationProfile[]; selected: string | null; + onChange: (draft: Draft) => void; onBack: () => void; onSave: () => void; onShowNewer: () => void; onDuplicate: () => void; onDelete: () => void; +}) { + const id = useId(); + const nameRef = useRef(null); + const { draft, base } = p.view; + useEffect(() => { if (p.view.focusName) nameRef.current?.focus(); }, [p.view.focusName]); + const size = bytes(draft.instructions); + const registered = new Set(p.services.map((service) => service.providerId)); + const elsewhere = Object.entries(draft.voices).filter(([provider]) => !registered.has(provider)); + const counters = p.services.map((service) => ({ service, max: service.personaInstructionBytes! })); + // Announced once at 90% and once when over, not on every keystroke. + const level = counters.some(({ max }) => size > max) ? "over" : counters.some(({ max }) => size >= max * 0.9) ? "near" : "ok"; + const errorIds = p.view.errors.map((_, index) => `${id}-error-${index}`).join(" ") || undefined; + const field = "w-full rounded-lg border border-border bg-surface px-3 py-2 text-sm text-foreground"; + return
+
+ +

{base ? base.name : "New persona"}

+ {base && nameRef.current?.focus()} onDuplicate={p.onDuplicate} onDelete={p.onDelete} />} +
+ + + +
+ Voice + {p.services.length === 0 &&

No live service on this host offers a voice choice.

} + {p.services.map((service) => { + const value = draft.voices[service.providerId] ?? ""; + const stale = value !== "" && !service.voices!.some((voice) => voice.id === value); + return ; + })} + {elsewhere.map(([provider, voice]) =>

+ {conversationService(provider)} (not on this host): {voice}. Kept as saved. +

)} +

Each service has its own voices; names aren{"'"}t shared between them.

+
+ +