Skip to content

The agent that grows with you

refactor(desktop): extract canonical protocol, client and authority helpers

Teknium233c094f4b7d
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index 324e7c6c085..cc81b2a52e4 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -99,6 +99,39 @@ export class CanonicalDesktopProtocol {
}
prepare(method: string, params: Record<string, unknown>): Record<string, unknown> {
+ const mutation = this.prepareMutation(method, params)
+
+ if (mutation) { return mutation }
+
+ if (method === 'session.create') { return this.prepareCreate(params) }
+
+ if (method === 'session.activate') {
+ return { session_id: params.session_id, source: 'desktop', ...(params.profile ? { profile: params.profile } : {}) }
+ }
+
+ if (method === 'session.interrupt' || method === 'session.redirect' || method === 'session.steer') {
+ const generation = params.execution_generation ?? this.generations.get(String(params.session_id))
+
+ if (typeof generation !== 'number') { throw new Error('Session execution identity unavailable; reconnect before controlling this turn') }
+
+ return { ...params, session_id: params.session_id, execution_generation: generation }
+ }
+
+ if (method === 'prompt.resolve_unknown') {
+ const lost = this.unknownAdmissions.get(String(params.admission_id))
+
+ if (!lost || lost.session_id !== params.session_id) { throw new Error('Admission is not an unknown lost turn; reopen the session before acknowledging') }
+
+ return { session_id: params.session_id, admission_id: params.admission_id, execution_generation: lost.generation }
+ }
+
+ if (method === 'approval.respond' || method === 'clarify.respond') { return this.preparePromptResponse(method, params) }
+
+ return params
+ }
+
+ // Metadata, branch and typed slash directives that travel as canonical `session.mutate`; null otherwise.
+ private prepareMutation(method: string, params: Record<string, unknown>): Record<string, unknown> | null {
const field = ({ 'session.title': 'title', 'session.archive': 'archived' } as Record<string, string>)[method]
if (field) { return this.retainedMutation(params.session_id, field === 'title' ? 'rename' : 'archive', { [field]: params[field] }, false) }
@@ -125,58 +158,38 @@ export class CanonicalDesktopProtocol {
if (directive) { return this.retainedMutation(params.session_id, directive.operation, directive.payload, true) }
}
- if (method === 'session.create') {
- const allowed = new Set(['request_id', 'source', 'cwd', 'model', 'toolsets', 'profile', 'cols', 'title', 'hidden', 'follow_profile_config'])
- const unsupported = Object.keys(params).filter(key => !allowed.has(key) && !(key === 'fast' && params[key] === false))
-
- if (unsupported.length) { throw new Error(`Canonical gateway does not support explicit session options: ${unsupported.join(', ')}`) }
-
- // The socket is bound to a profile already; only a sibling the host multiplexes rides as `profile`.
- const result = Object.fromEntries(Object.entries(params).filter(([key, value]) =>
- ['request_id', 'cwd', 'model', 'toolsets', 'title', 'hidden'].includes(key) || (key === 'profile' && value && value !== 'default')))
-
- const key = JSON.stringify(result)
- const requestId = params.request_id ?? this.creates.get(key) ?? crypto.randomUUID()
- this.creates.set(key, String(requestId))
-
- return { ...result, request_id: requestId, source: 'gui' }
- }
+ return null
+ }
- if (method === 'session.activate') {
- return { session_id: params.session_id, source: 'desktop', ...(params.profile ? { profile: params.profile } : {}) }
- }
+ private prepareCreate(params: Record<string, unknown>): Record<string, unknown> {
+ const allowed = new Set(['request_id', 'source', 'cwd', 'model', 'toolsets', 'profile', 'cols', 'title', 'hidden', 'follow_profile_config'])
+ const unsupported = Object.keys(params).filter(key => !allowed.has(key) && !(key === 'fast' && params[key] === false))
- if (method === 'session.interrupt' || method === 'session.redirect' || method === 'session.steer') {
- const generation = params.execution_generation ?? this.generations.get(String(params.session_id))
+ if (unsupported.length) { throw new Error(`Canonical gateway does not support explicit session options: ${unsupported.join(', ')}`) }
- if (typeof generation !== 'number') { throw new Error('Session execution identity unavailable; reconnect before controlling this turn') }
+ // The socket is bound to a profile already; only a sibling the host multiplexes rides as `profile`.
+ const result = Object.fromEntries(Object.entries(params).filter(([key, value]) =>
+ ['request_id', 'cwd', 'model', 'toolsets', 'title', 'hidden'].includes(key) || (key === 'profile' && value && value !== 'default')))
- return { ...params, session_id: params.session_id, execution_generation: generation }
- }
+ const key = JSON.stringify(result)
+ const requestId = params.request_id ?? this.creates.get(key) ?? crypto.randomUUID()
+ this.creates.set(key, String(requestId))
- if (method === 'prompt.resolve_unknown') {
- const lost = this.unknownAdmissions.get(String(params.admission_id))
+ return { ...result, request_id: requestId, source: 'gui' }
+ }
- if (!lost || lost.session_id !== params.session_id) { throw new Error('Admission is not an unknown lost turn; reopen the session before acknowledging') }
+ private preparePromptResponse(method: string, params: Record<string, unknown>): Record<string, unknown> {
+ const id = String(params.prompt_id ?? params.request_id ?? '')
+ const prompt = this.prompts.get(id)
+ const sessionId = params.session_id ?? prompt?.session_id
- return { session_id: params.session_id, admission_id: params.admission_id, execution_generation: lost.generation }
+ if (!prompt || prompt.session_id !== sessionId || prompt.execution_generation !== this.generations.get(String(sessionId))) {
+ throw new Error('Prompt is stale or unavailable; reconnect before responding')
}
- if (method === 'approval.respond' || method === 'clarify.respond') {
- const id = String(params.prompt_id ?? params.request_id ?? '')
- const prompt = this.prompts.get(id)
- const sessionId = params.session_id ?? prompt?.session_id
-
- if (!prompt || prompt.session_id !== sessionId || prompt.execution_generation !== this.generations.get(String(sessionId))) {
- throw new Error('Prompt is stale or unavailable; reconnect before responding')
- }
-
- const field = method === 'approval.respond' ? 'choice' : 'answer'
+ const field = method === 'approval.respond' ? 'choice' : 'answer'
- return { session_id: sessionId, execution_generation: prompt.execution_generation, prompt_id: id, [field]: params[field] }
- }
-
- return params
+ return { session_id: sessionId, execution_generation: prompt.execution_generation, prompt_id: id, [field]: params[field] }
}
event(event: { type: string; session_id?: string; payload?: unknown }) {
@@ -228,23 +241,25 @@ export class CanonicalDesktopProtocol {
}
if (MUTATION_METHODS.has(method) || (method === 'slash.exec' && typeof params.operation === 'string')) {
- if (value.session_id !== params.session_id) { throw new Error('Metadata receipt destination mismatch') }
+ return this.mutationReceipt(method, params, value)
+ }
- for (const [key, mutation] of this.mutations) { if (mutation.request_id === params.request_id) { this.mutations.delete(key) } }
+ if (method === 'session.create') {
+ for (const [key, id] of this.creates) { if (id === params.request_id) { this.creates.delete(key) } }
+ }
- if (BRANCH_METHODS.has(method)) {
- return { ...value, session_id: value.branched_session_id, stored_session_id: value.branched_session_id, parent_session_id: params.session_id, message_count: value.copied_messages }
- }
+ if (method === 'prompt.submit' || method === 'prompt.resolve_unknown') { return this.admissionReceipt(method, params, value) }
- if (method === 'slash.exec') { return { type: 'exec', output: mutationSummary(params.operation as string, value) } }
+ if (method === 'session.resume' || method === 'session.create' || method === 'session.activate') { return this.snapshotResult(value) }
- return { ...value, ok: true }
+ if (method === 'session.events.since') {
+ for (const event of value.events ?? []) { this.event(event) }
}
- if (method === 'session.create') {
- for (const [key, id] of this.creates) { if (id === params.request_id) { this.creates.delete(key) } }
- }
+ return value
+ }
+ private admissionReceipt(method: string, params: Record<string, unknown>, value: any): any {
if (method === 'prompt.submit') {
if (value.ref?.session_id !== params.session_id || typeof value.admission_id !== 'string') {
throw new Error('Canonical admission receipt destination mismatch')
@@ -253,35 +268,41 @@ export class CanonicalDesktopProtocol {
return { ...value, session_id: value.ref.session_id, submission_id: params.submission_id ?? params.input_id }
}
- if (method === 'prompt.resolve_unknown') {
- if (value.ref?.session_id !== params.session_id || value.admission_id !== params.admission_id) {
- throw new Error('Canonical admission receipt destination mismatch')
- }
+ if (value.ref?.session_id !== params.session_id || value.admission_id !== params.admission_id) {
+ throw new Error('Canonical admission receipt destination mismatch')
+ }
+
+ this.unknownAdmissions.delete(String(params.admission_id))
- this.unknownAdmissions.delete(String(params.admission_id))
+ return { ...value, session_id: value.ref.session_id }
+ }
+
+ private mutationReceipt(method: string, params: Record<string, unknown>, value: any): any {
+ if (value.session_id !== params.session_id) { throw new Error('Metadata receipt destination mismatch') }
- return { ...value, session_id: value.ref.session_id }
+ for (const [key, mutation] of this.mutations) { if (mutation.request_id === params.request_id) { this.mutations.delete(key) } }
+
+ if (BRANCH_METHODS.has(method)) {
+ return { ...value, session_id: value.branched_session_id, stored_session_id: value.branched_session_id, parent_session_id: params.session_id, message_count: value.copied_messages }
}
- if (method === 'session.resume' || method === 'session.create' || method === 'session.activate') {
- const sid = value.session_id
- this.event({ type: 'session.info', session_id: sid, payload: value })
+ if (method === 'slash.exec') { return { type: 'exec', output: mutationSummary(params.operation as string, value) } }
- const prompts = (value.prompts ?? []).map((prompt: Record<string, unknown>) => {
- const projected = { ...prompt, request_id: prompt.prompt_id }
- this.event({ type: `${prompt.kind}.request`, session_id: sid, payload: projected })
+ return { ...value, ok: true }
+ }
- return projected
- })
+ private snapshotResult(value: any): any {
+ const sid = value.session_id
+ this.event({ type: 'session.info', session_id: sid, payload: value })
- return { ...value, pending_approval: prompts.find((p: any) => p.kind === 'approval'), pending_clarify: prompts.find((p: any) => p.kind === 'clarify'), info: { ...value.info, stored_session_id: value.stored_session_id, pending_submissions: value.pending_submissions, execution_generation: value.execution_generation, running: value.running } }
- }
+ const prompts = (value.prompts ?? []).map((prompt: Record<string, unknown>) => {
+ const projected = { ...prompt, request_id: prompt.prompt_id }
+ this.event({ type: `${prompt.kind}.request`, session_id: sid, payload: projected })
- if (method === 'session.events.since') {
- for (const event of value.events ?? []) { this.event(event) }
- }
+ return projected
+ })
- return value
+ return { ...value, pending_approval: prompts.find((p: any) => p.kind === 'approval'), pending_clarify: prompts.find((p: any) => p.kind === 'clarify'), info: { ...value.info, stored_session_id: value.stored_session_id, pending_submissions: value.pending_submissions, execution_generation: value.execution_generation, running: value.running } }
}
// The canonical compress receipt carries counts, not the retained transcript;
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index b0b9c043333..8df4e5fc668 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -158,17 +158,8 @@ export class HermesGateway extends JsonRpcGatewayClient {
return this.request<T>('clarify.respond', { session_id: promptSession, request_id: params.request_id, answer }, timeoutMs, signal)
}
- const sid = typeof params.session_id === 'string' ? params.session_id : null
-
- if (sid && ATTACH_REQUIRED.has(method) && !this.attached.has(sid)) {
- await this.request('session.resume', { session_id: sid, defer_history: true, omit_messages: true, ...(params.profile ? { profile: params.profile } : {}) })
- }
- const parent = PARENT_ATTACH_REQUIRED.has(method) ? params.parent_session_id ?? params.session_id : null
-
- if (typeof parent === 'string' && parent && !this.attached.has(parent)) {
- await this.request('session.resume', { session_id: parent, defer_history: true, omit_messages: true, ...(params.profile ? { profile: params.profile } : {}) })
- }
+ await this.attachForRequest(method, params)
const prepared = this.protocol.prepare(method, params)
const wireMethod = this.protocol.wire(method, prepared)
@@ -181,14 +172,7 @@ export class HermesGateway extends JsonRpcGatewayClient {
const settled = this.protocol.settle(method, prepared, this.protocol.result(method, prepared, result), followUp) as T
if (method === 'session.resume' || method === 'session.create' || method === 'session.activate') {
- // Prompts still open on the authority re-deliver like `open_requests` after a reconnect.
- const sid = (settled as { session_id?: string }).session_id
-
- if (sid) { this.attached.add(sid) }
-
- for (const prompt of ((settled as { prompts?: Array<Record<string, unknown>> }).prompts ?? [])) {
- this.deliverCanonicalPrompt({ type: `${prompt.kind}.request`, session_id: sid, payload: prompt }, true)
- }
+ this.adoptAttachedSnapshot(settled as { session_id?: string; prompts?: Array<Record<string, unknown>> })
}
return settled
@@ -198,6 +182,33 @@ export class HermesGateway extends JsonRpcGatewayClient {
}
}
+ // Resume the session (and, for branch-like methods, its parent) on THIS socket before a
+ // method that needs an authority subscription here.
+ private async attachForRequest(method: string, params: Record<string, unknown>): Promise<void> {
+ const sid = typeof params.session_id === 'string' ? params.session_id : null
+
+ if (sid && ATTACH_REQUIRED.has(method) && !this.attached.has(sid)) {
+ await this.request('session.resume', { session_id: sid, defer_history: true, omit_messages: true, ...(params.profile ? { profile: params.profile } : {}) })
+ }
+
+ const parent = PARENT_ATTACH_REQUIRED.has(method) ? params.parent_session_id ?? params.session_id : null
+
+ if (typeof parent === 'string' && parent && !this.attached.has(parent)) {
+ await this.request('session.resume', { session_id: parent, defer_history: true, omit_messages: true, ...(params.profile ? { profile: params.profile } : {}) })
+ }
+ }
+
+ private adoptAttachedSnapshot(settled: { session_id?: string; prompts?: Array<Record<string, unknown>> }): void {
+ // Prompts still open on the authority re-deliver like `open_requests` after a reconnect.
+ const sid = settled.session_id
+
+ if (sid) { this.attached.add(sid) }
+
+ for (const prompt of (settled.prompts ?? [])) {
+ this.deliverCanonicalPrompt({ type: `${prompt.kind}.request`, session_id: sid, payload: prompt }, true)
+ }
+ }
+
constructor() {
super({
closedErrorMessage: 'Hermes gateway connection closed',
diff --git a/apps/desktop/src/lib/execution-authority.ts b/apps/desktop/src/lib/execution-authority.ts
index e1e077cdd86..ee8a986ee47 100644
--- a/apps/desktop/src/lib/execution-authority.ts
+++ b/apps/desktop/src/lib/execution-authority.ts
@@ -17,6 +17,35 @@ export interface ExecutionStampedEvent {
payload?: unknown
}
+const LIFECYCLE_TYPES = ['session.info', 'message.start', 'message.complete', 'message.error']
+
+/** The event's opaque epoch (string form) and generation, or null when it is unversioned. */
+function executionStamp(event?: ExecutionStampedEvent): { epoch: string; generation: number } | null {
+ const rawEpoch = event?.authority_epoch
+ const epoch = typeof rawEpoch === 'number' && Number.isSafeInteger(rawEpoch) ? String(rawEpoch) : rawEpoch
+ const generation = event?.execution_generation
+ const versioned = typeof epoch === 'string' && epoch.length > 0 && typeof generation === 'number' && Number.isSafeInteger(generation) && generation >= 0
+
+ return versioned ? { epoch, generation } : null
+}
+
+/** Whether a versioned lifecycle frame is fenced off by the previous owner (retiring its epoch on a valid takeover). */
+function fencedByPrevious(previous: ExecutionAuthority, type: string, epoch: string, generation: number, payload: Record<string, unknown> | undefined): boolean {
+ if (previous.retiredEpochs.has(epoch)) {return true}
+
+ if (previous.epoch === epoch) {
+ if (generation < previous.generation) {return true}
+
+ return generation === previous.generation && previous.terminal && (type === 'message.start' || payload?.running === true)
+ }
+
+ // Only an owner snapshot/start can establish a new epoch, not a late finalizer.
+ if (type !== 'session.info' && type !== 'message.start') {return true}
+ previous.retiredEpochs.add(previous.epoch)
+
+ return false
+}
+
/** Each transport consumer owns its map; epochs are opaque, never ordered. */
export function acceptExecutionEvent(
authorities: Map<string, ExecutionAuthority>,
@@ -24,36 +53,22 @@ export function acceptExecutionEvent(
type: string,
event?: ExecutionStampedEvent
): boolean {
- const lifecycle = ['session.info', 'message.start', 'message.complete', 'message.error'].includes(type)
+ const lifecycle = LIFECYCLE_TYPES.includes(type)
const previous = authorities.get(key)
const payload = event?.payload as Record<string, unknown> | undefined
- const rawEpoch = event?.authority_epoch
- const epoch = typeof rawEpoch === 'number' && Number.isSafeInteger(rawEpoch) ? String(rawEpoch) : rawEpoch
- const generation = event?.execution_generation
- const versioned = typeof epoch === 'string' && epoch.length > 0 && typeof generation === 'number' && Number.isSafeInteger(generation) && generation >= 0
+ const stamp = executionStamp(event)
// Output may follow the current owner, but cannot establish another one.
// Keep legacy unversioned output compatible; fence stamped late frames.
if (!lifecycle) {
- return !versioned || !previous || (previous.epoch === epoch && previous.generation === generation && !previous.terminal)
+ return !stamp || !previous || (previous.epoch === stamp.epoch && previous.generation === stamp.generation && !previous.terminal)
}
- if (!versioned) {return !previous}
+ if (!stamp) {return !previous}
+ const { epoch, generation } = stamp
const terminal = type === 'message.complete' || type === 'message.error' || payload?.running === false
- if (previous) {
- if (previous.retiredEpochs.has(epoch)) {return false}
-
- if (previous.epoch === epoch) {
- if (generation < previous.generation) {return false}
-
- if (generation === previous.generation && previous.terminal && (type === 'message.start' || payload?.running === true)) {return false}
- } else {
- // Only an owner snapshot/start can establish a new epoch, not a late finalizer.
- if (type !== 'session.info' && type !== 'message.start') {return false}
- previous.retiredEpochs.add(previous.epoch)
- }
- }
+ if (previous && fencedByPrevious(previous, type, epoch, generation, payload)) {return false}
authorities.set(key, { epoch, generation, terminal: terminal || Boolean(previous?.epoch === epoch && previous.generation === generation && previous.terminal), retiredEpochs: previous?.retiredEpochs ?? new Set() })