import { randomUUID } from 'node:crypto'; import { DetailCapture } from '../../../observability/detail-capture.js'; import { performance } from 'node:perf_hooks'; import type { GameClient } from '../../../../lib/game-client.js'; import { ApiError } from '../../../../lib/http-transport.js'; import type { TransportResponse } from '../../../../short-command/transport-response.js'; import { actionFailureDiagnosticSeverity } from '../../../framework/action-diagnostics.js'; import type { ActionCaller, ActionControlDescriptor, ActionDispatch, ActionExecutionContext, ActionResult, ActionServiceResult, ScopeRef, } from '../../../framework/contracts.js'; import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult, } from '../../../framework/plugins/index.js'; import { isClawclawRuntimeState, type ClawclawRuntimeStage } from '../../runtime-state.js'; import { sabotageTaskActionBlocked } from '../../task-choice-projection.js'; export const CLAWCLAW_ACTION_PLUGIN_ID = 'clawclaw.action'; export const CLAWCLAW_ACTION_CAPABILITY = 'clawclaw.action'; export const CLAWCLAW_AGENT_CONTROL_LEASE_MS = 1_000; export interface ClawclawActionRequest { route?: 'auto' | 'game' | 'room_chat'; action: Record; audioFile?: { path: string; contentType: string }; /** Host-only preconditions for one unified Behavior activation instance. */ behaviorOriginEpochSeq?: number; /** Runtime-owned operation name, for diagnostic attribution; not sent to the backend. */ behaviorOriginId?: string; behaviorOriginTick?: number; behaviorActionSafetyGeneration?: number; behaviorActivationGeneration?: number; } export function describeClawclawActionControl( request: ClawclawActionRequest, ): ActionControlDescriptor { const action = typeof request.action?.action === 'string' ? request.action.action : undefined; let domains: string[]; switch (action) { case 'move': case 'task': case 'kill': case 'report': domains = ['physical']; break; case 'speech': domains = ['communication']; break; case 'vote': domains = ['meeting_vote']; break; case 'think': case 'strategy': domains = []; break; default: domains = ['*']; break; } return { domains, agentLeaseMs: CLAWCLAW_AGENT_CONTROL_LEASE_MS }; } function cleanActionResponseValue(value: any): any { return value === undefined ? undefined : structuredClone(value); } function backendError(error: unknown): unknown { if (error instanceof ApiError) { const parsed = error.response?.body.kind === 'json' ? error.response.body.value : (() => { try { return JSON.parse(error.body); } catch { return null; } })(); return parsed ?? { error: { code: `HTTP_${error.status}`, message: error.body }, http_status: error.status, }; } return { error: { code: 'ACTION_REQUEST_FAILED', message: error instanceof Error ? error.message : String(error), }, }; } function actionResultErrorCode(result: ActionResult): string | undefined { const outer = result.error && typeof result.error === 'object' && !Array.isArray(result.error) ? result.error as Record : {}; const nested = outer.error && typeof outer.error === 'object' && !Array.isArray(outer.error) ? outer.error as Record : {}; const code = nested.code ?? outer.code; return typeof code === 'string' && code.trim() ? code.trim() : undefined; } function actionResult( scope: ScopeRef, actionId: string, status: ActionResult['status'], value?: unknown, error?: unknown, metadata: Pick = {}, ): ActionResult { return { scope, actionId, status, ...metadata, ...(value === undefined ? {} : { value: cleanActionResponseValue(value) }), ...(error === undefined ? {} : { error: cleanActionResponseValue(error) }), }; } function deferredAtCommitBoundary( context: ActionExecutionContext, ): ActionResult | undefined { const authority = context.revalidate(); return authority.status === 'deferred' ? authority.result : undefined; } /** Release the Action even if preparation or a provider ignores cancellation. */ function untilAborted(operation: Promise, signal: AbortSignal): Promise { return new Promise((resolve, reject) => { const abort = (): void => reject(signal.reason ?? new Error('ACTION_CANCELLED')); const cleanup = (): void => signal.removeEventListener('abort', abort); operation.then((value) => { cleanup(); resolve(value); }, (error) => { cleanup(); reject(error); }); if (signal.aborted) abort(); else signal.addEventListener('abort', abort, { once: true }); }); } type AutomatedActionCaller = Extract; function isAutomatedCaller(caller: ActionCaller): caller is AutomatedActionCaller { return caller.kind === 'behavior'; } interface ActionTargetFailure { code: 'INVALID_ACTION_TARGET_SEAT'; message: string; } type ActionTargetPreparation = | { action: Record } | { failure: ActionTargetFailure }; interface AdmittedClawclawAction { actionId: string; action: Record; route: 'game' | 'room_chat'; } interface AutomatedProviderTiming { readonly queuedAtMs: number; readonly queueDepthAtAdmission: number; readonly inFlightAtAdmission: number; startedAtMs?: number; } interface AutomatedSubmission { readonly settlement: Promise; readonly timing: AutomatedProviderTiming; } function elapsedMs(startedAtMs: number, endedAtMs = performance.now()): number { return Math.round(Math.max(0, endedAtMs - startedAtMs) * 1_000) / 1_000; } function automatedDiagnosticAttributes( request: ClawclawActionRequest, admitted: AdmittedClawclawAction, caller: AutomatedActionCaller, ): Readonly> { return { action_id: admitted.actionId, action_kind: typeof admitted.action.action === 'string' ? admitted.action.action : 'unknown', route: admitted.route, caller_kind: caller.kind, behavior_id: request.behaviorOriginId, behavior_activation_id: caller.activationId, behavior_activation_generation: caller.activationGeneration, behavior_layer: caller.layer, ...(request.behaviorOriginEpochSeq === undefined ? {} : { epoch_seq: request.behaviorOriginEpochSeq, origin_epoch_seq: request.behaviorOriginEpochSeq, }), ...(request.behaviorOriginTick === undefined ? {} : { origin_tick: request.behaviorOriginTick }), }; } /** Validates authoritative seat targets without consulting names or roster state. */ function prepareActionTarget(action: Record): ActionTargetPreparation { if (action.action !== 'kill' && action.action !== 'vote') return { action }; const seat = action.target_seat; if ( !Number.isInteger(seat) || seat < (action.action === 'vote' ? 0 : 1) || seat > 10 ) { return { failure: { code: 'INVALID_ACTION_TARGET_SEAT', message: 'Kill requires target_seat 1-10; vote requires target_seat 0-10, where 0 skips.', }, }; } return { action }; } function acknowledgedActionResult( scope: ScopeRef, actionId: string, response: TransportResponse, ): ActionResult { const root = response.body.kind === 'json' && response.body.value && typeof response.body.value === 'object' && !Array.isArray(response.body.value) ? response.body.value as Record : null; if (!root) { return actionResult(scope, actionId, 'failure', undefined, { error: { code: 'ACTION_PROTOCOL_ERROR', message: response.body.kind === 'empty' ? 'The action endpoint returned an empty response.' : 'The action endpoint returned a non-object response.', }, http_status: response.status, }, { source: 'protocol', actionOutcome: 'unknown' }); } const rejected = response.status < 200 || response.status >= 300 || root.success === false || root.ok === false; return rejected ? actionResult(scope, actionId, 'failure', undefined, root, { source: 'backend', actionOutcome: 'confirmed', }) : actionResult(scope, actionId, 'success', root, undefined, { source: 'backend', actionOutcome: 'confirmed', }); } /** ClawClaw command provider. Runtime only routes the declared capability. */ export class ClawclawActionPlugin implements RuntimeEpochPlugin> { readonly kind = 'epoch' as const; readonly id = CLAWCLAW_ACTION_PLUGIN_ID; readonly version = '1'; readonly capabilities = { provides: [CLAWCLAW_ACTION_CAPABILITY] } as const; private unregister?: () => void; private stage: ClawclawRuntimeStage = 'matching'; private connection: 'connected' | 'reconnecting' | 'disconnected' = 'disconnected'; private noteAgentActivity?: () => void; private diagnostic?: RuntimeEpochPluginContext>['diagnostic']; private latestTaskGameState?: { scopeKey: string; epochSeq: number; state: Record; }; private readonly ownedSettlements = new Map>(); /** * Automated callers may receive a queued receipt before HTTP settlement. * Keep one provider-start FIFO per scope so a controller replacement or a * Behavior handoff cannot let a later admitted Action reach the * gameplay endpoint before an earlier one has started. */ private readonly automatedProviderStarts = new Map>(); private readonly automatedProviderQueueDepths = new Map(); constructor(private readonly client: GameClient) {} private detailCapture?: DetailCapture; attachAgentActivity(listener: () => void): void { this.noteAgentActivity = listener; } start(context: RuntimeEpochPluginContext>): void { if (this.unregister) throw new Error('Clawclaw Action Plugin is already started.'); this.latestTaskGameState = undefined; this.stage = context.currentSegment().kind === 'room_lobby' ? 'room' : 'matching'; this.diagnostic = context.diagnostic; this.detailCapture = new DetailCapture('actions', context.diagnostic); this.unregister = context.capabilities.provideAction({ capability: CLAWCLAW_ACTION_CAPABILITY, describeControl: describeClawclawActionControl, perform: (request, scope, caller, actionContext) => ( this.perform(request, scope, caller, actionContext) ), }); } update(input: RuntimeEpochPluginInput>): RuntimeEpochPluginResult { const scopeKey = this.automatedProviderQueueKey(input.epoch.scope); if (this.latestTaskGameState?.scopeKey !== scopeKey) this.latestTaskGameState = undefined; if (isClawclawRuntimeState(input.epoch.state)) { this.stage = input.epoch.state.stage; this.connection = input.epoch.state.connection; if ((input.epoch.state.game_snapshot.status === 'fresh' || input.epoch.state.game_snapshot.status === 'cached')) { this.rememberTaskGameState(input.epoch.scope, input.epoch.epochSeq, input.epoch.state.game_snapshot.state); } } return { outcome: 'noop', reason: 'no_action_request' }; } stop(): void { this.unregister?.(); this.unregister = undefined; this.diagnostic = undefined; this.latestTaskGameState = undefined; this.automatedProviderStarts.clear(); this.automatedProviderQueueDepths.clear(); } private automatedProviderQueueKey(scope: ScopeRef): string { return `${scope.sessionId}:${scope.segmentId}`; } private rememberTaskGameState(scope: ScopeRef, epochSeq: number, state: Record): void { const scopeKey = this.automatedProviderQueueKey(scope); if (this.latestTaskGameState?.scopeKey === scopeKey && this.latestTaskGameState.epochSeq > epochSeq) return; this.latestTaskGameState = { scopeKey, epochSeq, state: structuredClone(state) }; } private taskAdmissionRejection( request: ClawclawActionRequest, scope: ScopeRef, actionId: string, context: ActionExecutionContext, ): ActionResult | undefined { if (request.action.action !== 'task') return undefined; const scopeKey = this.automatedProviderQueueKey(scope); if (this.latestTaskGameState?.scopeKey !== scopeKey) this.latestTaskGameState = undefined; const latest = context.latestAcceptedState(); const runtimeState = latest?.state; let game: Record | undefined; if (isClawclawRuntimeState(runtimeState)) { if ((runtimeState.game_snapshot.status === 'fresh' || runtimeState.game_snapshot.status === 'cached')) { game = runtimeState.game_snapshot.state; this.rememberTaskGameState(scope, latest!.epochSeq, game); } else if (runtimeState.game_snapshot.status === 'not_updated' && runtimeState.connection === 'connected') { // Control-only epochs retain the last authoritative game observation. game = this.latestTaskGameState?.state; } if (runtimeState.connection !== 'connected') game = undefined; } else if (runtimeState) { game = runtimeState; this.rememberTaskGameState(scope, latest!.epochSeq, game); } // An unavailable snapshot may retain task identity for rejection, but can // never borrow a previous ready status to authorize sabotage. if (!game && this.latestTaskGameState) { game = { ...this.latestTaskGameState.state, crab_sabotage: undefined }; } if (!sabotageTaskActionBlocked(game, request.action.task_name)) return undefined; return actionResult(scope, actionId, 'failure', undefined, { error: { code: 'SABOTAGE_NOT_READY', message: 'The sabotage task requires the current shared sabotage state to be ready.', }, }, { source: 'local', actionOutcome: 'not_submitted' }); } private enqueueAutomatedSubmission( request: ClawclawActionRequest, scope: ScopeRef, caller: AutomatedActionCaller, context: ActionExecutionContext, admitted: AdmittedClawclawAction, ): AutomatedSubmission { const queueKey = this.automatedProviderQueueKey(scope); const previousStarted = this.automatedProviderStarts.get(queueKey) ?? Promise.resolve(); const queueDepthAtAdmission = (this.automatedProviderQueueDepths.get(queueKey) ?? 0) + 1; this.automatedProviderQueueDepths.set(queueKey, queueDepthAtAdmission); const timing: AutomatedProviderTiming = { queuedAtMs: performance.now(), queueDepthAtAdmission, inFlightAtAdmission: this.ownedSettlements.size + 1, }; const diagnostic = this.diagnostic; let markStarted!: () => void; const started = new Promise((resolve) => { markStarted = resolve; }); this.automatedProviderStarts.set(queueKey, started); void started.finally(() => { if (this.automatedProviderStarts.get(queueKey) === started) { this.automatedProviderStarts.delete(queueKey); } }); let queuePositionReleased = false; const releaseQueuePosition = (endpointStarted: boolean): void => { if (queuePositionReleased) return; queuePositionReleased = true; const releasedAtMs = performance.now(); if (endpointStarted) timing.startedAtMs = releasedAtMs; this.detailCapture?.emit(endpointStarted ? 'queue_released' : 'provider_skipped', () => ({ ...automatedDiagnosticAttributes(request, admitted, caller), action: admitted.action, queue_wait_ms: elapsedMs(timing.queuedAtMs, releasedAtMs), })); const remainingQueueDepth = Math.max( 0, (this.automatedProviderQueueDepths.get(queueKey) ?? 1) - 1, ); if (remainingQueueDepth === 0) this.automatedProviderQueueDepths.delete(queueKey); else this.automatedProviderQueueDepths.set(queueKey, remainingQueueDepth); this.emitDiagnostic( endpointStarted ? 'runtime.action.provider_started' : 'runtime.action.provider_skipped', { ...automatedDiagnosticAttributes(request, admitted, caller), queue_wait_ms: elapsedMs(timing.queuedAtMs, releasedAtMs), queue_depth_at_admission: timing.queueDepthAtAdmission, in_flight_at_admission: timing.inFlightAtAdmission, remaining_queue_depth: remainingQueueDepth, }, 'debug', diagnostic, ); const queueWaitMs = elapsedMs(timing.queuedAtMs, releasedAtMs); if (endpointStarted && (queueWaitMs >= 20 || timing.queueDepthAtAdmission >= 2)) { this.emitDiagnostic('runtime.action.provider_queue_delayed', { ...automatedDiagnosticAttributes(request, admitted, caller), queue_wait_ms: queueWaitMs, queue_depth_at_admission: timing.queueDepthAtAdmission, in_flight_at_admission: timing.inFlightAtAdmission, remaining_queue_depth: remainingQueueDepth, budget_exceeded: queueWaitMs >= 100, }, 'warn', diagnostic); } markStarted(); }; const settlement = previousStarted .catch(() => {}) .then(() => this.submitAdmitted( request, scope, caller, context, admitted, releaseQueuePosition, )); return { settlement, timing }; } private automationSafetyRejection( request: ClawclawActionRequest, scope: ScopeRef, actionId: string, caller: ActionCaller, context: ActionExecutionContext, ): ActionResult | undefined { if (!isAutomatedCaller(caller)) return undefined; const originEpochSeq = request.behaviorOriginEpochSeq; const actionSafetyGeneration = request.behaviorActionSafetyGeneration; if ( !Number.isInteger(originEpochSeq) || originEpochSeq! <= 0 || !Number.isInteger(actionSafetyGeneration) || actionSafetyGeneration! < 0 || !Number.isSafeInteger(request.behaviorActivationGeneration) || request.behaviorActivationGeneration! <= 0 ) { return actionResult(scope, actionId, 'failure', undefined, { error: { code: 'BEHAVIOR_ACTION_PRECONDITION_MISSING', message: 'The Behavior Action is missing its Runtime safety precondition.', }, }, { source: 'local', actionOutcome: 'not_submitted' }); } if ( request.behaviorActivationGeneration !== caller.activationGeneration ) { return actionResult(scope, actionId, 'failure', undefined, { error: { code: 'STALE_BEHAVIOR_ACTION', message: 'The Behavior Action belongs to another activation generation.', }, }, { source: 'local', actionOutcome: 'not_submitted' }); } const latest = context.latestAcceptedState(); const state = latest?.state; if ( latest && latest.epochSeq >= originEpochSeq! && isClawclawRuntimeState(state) && state.action_safety_generation === actionSafetyGeneration && state.connection === 'connected' && state.stage === 'game' && ( (state.game_snapshot.status !== 'fresh' && state.game_snapshot.status !== 'cached') || ( state.game_snapshot.state.phase === 'wandering' && state.game_snapshot.state.you?.is_alive !== false ) ) ) return undefined; return actionResult(scope, actionId, 'failure', undefined, { error: { code: 'STALE_BEHAVIOR_ACTION', message: 'The automated Action was computed before the latest game safety boundary.', }, }, { source: 'local', actionOutcome: 'not_submitted' }); } private commitBoundaryRejection( request: ClawclawActionRequest, scope: ScopeRef, actionId: string, caller: ActionCaller, context: ActionExecutionContext, ): ActionResult | undefined { const stale = this.automationSafetyRejection(request, scope, actionId, caller, context); if (stale) return stale; const taskRejected = this.taskAdmissionRejection(request, scope, actionId, context); if (taskRejected) return taskRejected; if (caller.kind === 'behavior') { // A queued Behavior Action is owned by its exact activation controller // until the endpoint starts. Suspension, replacement, or restart must // cancel work that has not crossed that irreversible boundary. return deferredAtCommitBoundary(context); } return deferredAtCommitBoundary(context); } private perform( request: ClawclawActionRequest, scope: ScopeRef, caller: ActionCaller, context: ActionExecutionContext, ): ActionServiceResult | Promise { const actionId = randomUUID(); try { if (caller.kind === 'agent' || caller.kind === 'user') this.noteAgentActivity?.(); const staleAtStart = this.automationSafetyRejection(request, scope, actionId, caller, context); if (staleAtStart) return staleAtStart; const action = { ...request.action }; if (action.action === 'trigger_alarm') { return actionResult(scope, actionId, 'failure', undefined, { error: { code: 'TRIGGER_ALARM_REMOVED_USE_TASK', message: 'Crab sabotage emergencies now start when an assigned sabotage task completes.', }, }, { source: 'local', actionOutcome: 'not_submitted' }); } const route = request.route === 'auto' ? (this.stage === 'room' && action.action === 'speech' ? 'room_chat' : 'game') : request.route ?? 'game'; if (route === 'game' && this.connection !== 'connected') { return actionResult(scope, actionId, 'failure', undefined, { error: { code: 'GAME_SYNC_NOT_READY', message: 'GameSync snapshot/resume has not completed; retry after the next authoritative State.', }, }, { source: 'local', actionOutcome: 'not_submitted' }); } if (route === 'room_chat') { if (action.action !== 'speech' || typeof action.text !== 'string') { return actionResult(scope, actionId, 'failure', undefined, { error: { code: 'INVALID_ROOM_ACTION', message: 'Room chat requires a speech action.' }, }, { source: 'local', actionOutcome: 'not_submitted' }); } } else { const taskRejected = this.taskAdmissionRejection(request, scope, actionId, context); if (taskRejected) return taskRejected; const targetPreparation = prepareActionTarget(action); if ('failure' in targetPreparation) { return actionResult(scope, actionId, 'failure', undefined, { error: targetPreparation.failure, }, { source: 'local', actionOutcome: 'not_submitted' }); } Object.assign(action, targetPreparation.action); } const admitted: AdmittedClawclawAction = { actionId, action, route }; if (!isAutomatedCaller(caller)) { return this.submitAdmitted(request, scope, caller, context, admitted); } const queued = this.enqueueAutomatedSubmission( request, scope, caller, context, admitted, ); this.emitDiagnostic('runtime.action.provider_queued', { ...automatedDiagnosticAttributes(request, admitted, caller), queue_depth: queued.timing.queueDepthAtAdmission, in_flight: queued.timing.inFlightAtAdmission, }); this.detailCapture?.emit('queued', () => ({ ...automatedDiagnosticAttributes(request, admitted, caller), action: admitted.action, queue_depth: queued.timing.queueDepthAtAdmission })); const ownedSettlement = this.ownSettlement( scope, caller, action, actionId, admitted.route, request, queued.settlement, queued.timing, ); const dispatch: ActionDispatch = { receipt: actionResult(scope, actionId, 'success', { accepted: true, status: 'queued', }, undefined, { source: 'local', actionOutcome: 'unknown' }), settled: ownedSettlement, }; return dispatch; } catch (error) { return actionResult(scope, actionId, 'failure', undefined, backendError(error), { source: 'local', actionOutcome: 'not_submitted', }); } } private async submitAdmitted( request: ClawclawActionRequest, scope: ScopeRef, caller: ActionCaller, context: ActionExecutionContext, admitted: AdmittedClawclawAction, markProviderStartedOrSkipped: (endpointStarted: boolean) => void = () => {}, ): Promise { let actionEndpointStarted = false; const action = { ...admitted.action }; try { context.signal.throwIfAborted(); if (request.audioFile) { const uploaded = await untilAborted(this.client.uploadAudio( request.audioFile.path, undefined, request.audioFile.contentType, ), context.signal); action.audio_url = uploaded.audio_url; const rejected = this.commitBoundaryRejection( request, scope, admitted.actionId, caller, context, ); if (rejected) return rejected; } if (admitted.route === 'room_chat') { const rejected = this.commitBoundaryRejection( request, scope, admitted.actionId, caller, context, ); if (rejected) return rejected; const pending = this.client.chatRoomConfirmed(action.text); this.detailCapture?.emit('provider_started', () => ({ action_id: admitted.actionId, action, caller, behavior_id: request.behaviorOriginId, route: admitted.route })); actionEndpointStarted = true; markProviderStartedOrSkipped(true); return acknowledgedActionResult( scope, admitted.actionId, await untilAborted(pending, context.signal), ); } const preparedAction = await untilAborted(this.client.prepareActionForConfirmedSubmission(action as any), context.signal); context.signal.throwIfAborted(); const rejected = this.commitBoundaryRejection( request, scope, admitted.actionId, caller, context, ); if (rejected) return rejected; const pending = this.client.submitPreparedActionConfirmed(preparedAction, context.signal); this.detailCapture?.emit('provider_started', () => ({ action_id: admitted.actionId, action: preparedAction, caller, behavior_id: request.behaviorOriginId, origin_epoch_seq: request.behaviorOriginEpochSeq, origin_tick: request.behaviorOriginTick, route: admitted.route })); actionEndpointStarted = true; markProviderStartedOrSkipped(true); const response = await untilAborted(pending, context.signal); return acknowledgedActionResult(scope, admitted.actionId, response); } catch (error) { if (context.signal.aborted) { if (!actionEndpointStarted) { const rejected = deferredAtCommitBoundary(context); if (rejected) return rejected; } const reason = context.signal.reason; const code = reason instanceof Error && ['GAME_ENDED', 'ACTION_SCOPE_ENDED'].includes(reason.message) ? reason.message : 'ACTION_CANCELLED'; return actionResult(scope, admitted.actionId, 'failure', undefined, { error: { code, message: actionEndpointStarted ? 'Action wait cancelled; the backend execution outcome is unknown.' : 'Action cancelled before submission.' }, }, { source: 'local', actionOutcome: actionEndpointStarted ? 'unknown' : 'not_submitted' }); } return actionResult(scope, admitted.actionId, 'failure', undefined, backendError(error), { source: error instanceof ApiError ? 'backend' : 'transport', actionOutcome: actionEndpointStarted ? (error instanceof ApiError ? 'confirmed' : 'unknown') : 'not_submitted', }); } finally { // A local rejection or preparation failure is also a resolved queue // position: later Decisions may continue without waiting forever. markProviderStartedOrSkipped(false); } } private ownSettlement( scope: ScopeRef, caller: AutomatedActionCaller, action: Record, actionId: string, route: AdmittedClawclawAction['route'], request: ClawclawActionRequest, settlement: Promise, timing: AutomatedProviderTiming, ): Promise { // Keep the epoch's diagnostic sink with the owned submission. The plugin // may be stopped after the Runtime starts draining, but the final provider // result still belongs to this Action dispatch and must remain observable. const diagnostic = this.diagnostic; const detailCapture = this.detailCapture; const report = (result: ActionResult): ActionResult => { const settledAtMs = performance.now(); const errorCode = actionResultErrorCode(result); detailCapture?.emit('provider_settled', () => ({ action_id: actionId, action, caller, behavior_id: request.behaviorOriginId, origin_epoch_seq: request.behaviorOriginEpochSeq, origin_tick: request.behaviorOriginTick, result, total_duration_ms: elapsedMs(timing.queuedAtMs, settledAtMs) })); this.emitDiagnostic('runtime.action.provider_settled', { ...automatedDiagnosticAttributes(request, { actionId, action, route, }, caller), status: result.status, ...(result.source ? { action_source: result.source } : {}), ...(result.actionOutcome ? { action_outcome: result.actionOutcome } : {}), ...(errorCode ? { error_code: errorCode } : {}), queue_depth_at_admission: timing.queueDepthAtAdmission, in_flight_at_admission: timing.inFlightAtAdmission, in_flight_at_settlement: this.ownedSettlements.size, queue_wait_ms: timing.startedAtMs === undefined ? elapsedMs(timing.queuedAtMs, settledAtMs) : elapsedMs(timing.queuedAtMs, timing.startedAtMs), ...(timing.startedAtMs === undefined ? {} : { provider_duration_ms: elapsedMs(timing.startedAtMs, settledAtMs) }), total_duration_ms: elapsedMs(timing.queuedAtMs, settledAtMs), }, result.status === 'failure' ? actionFailureDiagnosticSeverity(result) : 'debug', diagnostic); return result; }; let owned!: Promise; owned = settlement.then(report, (error) => report(actionResult( scope, actionId, 'failure', undefined, backendError(error), { source: 'transport', actionOutcome: 'unknown' }, ))).finally(() => { if (this.ownedSettlements.get(actionId) === owned) this.ownedSettlements.delete(actionId); }); this.ownedSettlements.set(actionId, owned); return owned; } private emitDiagnostic( name: string, attributes: Readonly>, severity: 'debug' | 'info' | 'warn' | 'error' = 'debug', diagnostic = this.diagnostic, ): void { // Diagnostics must never become a second failure mode for a detached // provider result whose caller has already received its queue receipt. try { diagnostic?.(name, attributes, severity); } catch { // Best-effort operational telemetry only. } } }