import { startupMark, startupSpan, startupTraceEnabled, timeStartup } from '../../../bin/startup-trace.mjs'; import { strategyTriggerSource } from './behavior-trigger.js'; import { BUILTIN_PERCEPTION_NAMES } from './plugins/system-perception/system-perceptions.js'; import { BUILTIN_PERCEPTION_PREFIX } from './notification-policy.js'; import { isClawclawAgentNotification } from './notification-policy.js'; import { createClawclawProcessingCadence } from './runtime-cadence.js'; import { readRuntimeCycleIntervalMs } from '../../lib/runtime-cadence-config.js'; import { randomUUID } from 'node:crypto'; import { BehaviorReflexControl } from './behavior-reflex-control.js'; import { DeferredMeetingShortStrategy } from './behavior-start-control.js'; import { normalizeBehaviorInput } from './behavior-input-fields.js'; import { acquireOwnerLock, type OwnerLock } from './owner-lock.js'; import { createStartingOwnerControl } from './starting-owner-control.js'; export { acquireOwnerLock, type OwnerLock, type OwnerLockOperations } from './owner-lock.js'; import { chmodSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs'; import { join } from 'node:path'; import { getHeapStatistics } from 'node:v8'; import { RuntimeProcessTimingSampler } from '../observability/process-timing.js'; import type { AuthProfile } from '../../lib/auth.js'; import { GameClient } from '../../lib/game-client.js'; import { isTrainingRole } from '../../lib/training-role.js'; import { getProfileRuntimeStateDir, getWorkspaceDir } from '../../lib/init-command.js'; import { readWorkspacePerceptionConfig } from '../../lib/perception-config.js'; import { CLAWCLAW_ROLE_IDS, readGameplayConfig, type GameplayConfig, } from '../../lib/gameplay-config.js'; import { toTriggerRegistrationOverrides } from '../../lib/trigger-config.js'; import { isRoomMode, isTrainingRoomMode, queueMode, queueRoomCode, queueStatus, } from '../../lib/room.js'; import type { RuntimeEpochPlugin } from '../framework/plugins/index.js'; import type { ActionResult } from '../framework/contracts.js'; import { isMailboxRepository } from '../framework/mailbox/index.js'; import type { Runtime, RuntimeReadyView } from '../framework/runtime.js'; import { MailboxRelayBroker, runStdoutMailboxRelay, } from '../mailbox-host-relay.js'; import { HostMonitorWriteGate, } from '../host-monitor-rate-gate.js'; import { gameStartRuntimePath, readGameStartRuntime, startOwnerControlServer, type OwnerControlServer, } from '../owner-control.js'; import { createOwnerTelemetryRecorder, observabilityRetention, resolveOwnerObservabilityLevel, } from '../observability/index.js'; import { watchParentProcess, type ParentProcessWatchHandle, } from '../parent-process-watch.js'; import { ownerRawWsLogPath } from '../raw-ws-log.js'; import type { ThreadedWsClientConfig } from '../threaded-ws-client.js'; import { presentCanonicalEventForCclEvents, presentCanonicalEventForDesktop, } from '../../pipeline/canonical-event-presentation.js'; import { compactStateForEvents } from '../../pipeline/event-format.js'; import { createClawclawRuntime } from './runtime.js'; import { assembleClawclawPlugins } from './plugins/assembly.js'; import { ClawclawBehaviorCatalog, createClawclawBehaviorControlDriver, type ClawclawRoleFallbackBehaviors, type ResolvedClawclawBehaviorSource, } from './plugins/behavior/index.js'; import { ClawclawMailboxPlugin, ClawclawMailboxService, CompositeClawclawMailboxDriver, ClaudeChannelMailboxAdapter, ClaudeChannelSocketSink, DesktopEventSocketSink, GameSyncPerceptionReportAdapter, GameSyncRuntimeReportAdapter, AgentMailboxCoordinator, clawclawEventRequiresDetails, MailboxEventBatchPump, CCL_EVENTS_MAILBOX_CONSUMER_ID, DESKTOP_IPC_MAILBOX_CONSUMER_ID, MONITOR_MAILBOX_CONSUMER_ID, type AgentMailboxCoordinatorOptions, type ClawclawMailboxDriver, type DesktopEventSocketConfig, } from './plugins/mailbox/index.js'; import { BEHAVIOR_PLUGIN_API_VERSION, resolveClawclawResourceMetadata } from '../../sdk/behavior-plugin/index.js'; import { TRIGGER_PLUGIN_API_VERSION } from '../../sdk/trigger-plugin/index.js'; import { readLocalAgentWorkspaceSnapshot, resolveLocalAgentWorkspaceSnapshot, } from '../../lib/agent-workspace-sync.js'; import { filterInactiveAgentWorkspaceSnapshot } from '../../lib/capability-cloud-presence.js'; import { listAgentWorkspaceBehaviorSources, listAgentWorkspacePerceptionSources, mergeAgentWorkspaceBehaviorSources, mergeAgentWorkspacePerceptionSources, } from '../../lib/agent-workspace-runtime.js'; import { listClawclawTriggerSources } from './plugins/trigger/trigger-source.js'; import { type ClawclawTriggerRegistration, type ResolvedClawclawTriggerSource, } from './plugins/trigger/index.js'; import { clawclawQueueGameId, ClawclawSourcePlugin, normalizeClawclawQueueState, type ClawclawSourceCompletion, type ClawclawSourceStartIntent, } from './plugins/source/index.js'; import { type ClawclawOwnerNotificationHost, } from './notifications.js'; import { discoverLocalCapabilities } from '../../lib/capability-discovery.js'; import { ensureAccountUserDataLayout, getUserDataAccountTriggersDir, } from '../../lib/user-data.js'; const FULL_DIAGNOSTIC_SAMPLE_INTERVAL_MS = 5_000; export interface ClawclawOwnerOptions { profile: AuthProfile; intent: ClawclawSourceStartIntent; resolveStartupIntent?: (client: GameClient, queue: unknown) => Promise; forceExistingRuntime?: boolean; epochPlugins?: RuntimeEpochPlugin, Record>[]; notificationHost?: ClawclawOwnerNotificationHost; /** Desktop Host adapter for this run. */ desktopEvents?: DesktopEventSocketConfig; /** Pushes this Owner's Mailbox batches to the local Claude Channel bridge. */ channelDelivery?: boolean; } export interface ChannelOwnerDeliveryPolicy { enabled: boolean; drainOnNaturalCompletion: boolean; } export type OwnerAgentEventDelivery = 'ccl_events' | 'desktop_ipc'; export function ownerAgentEventPresenter( delivery: OwnerAgentEventDelivery, desktopHost: boolean, ): AgentMailboxCoordinatorOptions['presentEvent'] { return delivery === 'desktop_ipc' || desktopHost ? presentCanonicalEventForDesktop : presentCanonicalEventForCclEvents; } export function channelOwnerDeliveryPolicy( channelDelivery: boolean | undefined, localStopRequested = false, ): ChannelOwnerDeliveryPolicy { const enabled = channelDelivery === true; return { enabled, drainOnNaturalCompletion: enabled && !localStopRequested, }; } /** Submit an existing direct Agent command without wrapping it in Behavior. */ export async function performOwnerAgentAction( runtime: Pick, 'performAction'>, capability: string, action: unknown, expectedScope: { sessionId: string; segmentId: string }, ): Promise { return runtime.performAction( capability, action, expectedScope, { kind: 'agent' }, ); } export interface ClawclawOwnerRuntimeStart { initialQueueState: Record; initialSegment: { kind: string; identity?: string }; mode?: string; resume: boolean; resumeKey?: string; } /** * Derives backend participation continuity from one authoritative Lobby * observation. `resume` permits recovery of a matching unsealed scope after an * unclean process loss; a normally stopped Owner has already sealed its local * scope and the next Owner starts a new one. Physical WebSocket connections are * never restored here. */ export function deriveClawclawOwnerRuntimeStart( queueValue: unknown, intent: ClawclawSourceStartIntent, ): ClawclawOwnerRuntimeStart { const initialQueueState = normalizeClawclawQueueState(queueValue); const status = queueStatus(initialQueueState); const mode = queueMode(initialQueueState); const roomCode = queueRoomCode(initialQueueState); const gameId = clawclawQueueGameId(initialQueueState); if (status === 'in_room') { const switchingRooms = intent.kind === 'join_room' && intent.roomCode !== roomCode; if (!switchingRooms && roomCode) { return { initialQueueState, initialSegment: { kind: 'room', identity: roomCode }, mode: mode ?? 'room', resume: true, resumeKey: roomCode, }; } } if (status === 'allocated' && gameId) { return { initialQueueState, initialSegment: { kind: 'game', identity: gameId }, ...(mode ? { mode } : {}), // Match sessions use game_id as their session key. Room sessions keep // room_code as the session key, but can still match the current game // segment by game_id when /queue/status omits room_code during play. resume: true, ...(isRoomMode(mode) ? roomCode ? { resumeKey: roomCode } : {} : { resumeKey: gameId }), }; } if ( (status === 'queued' || status === 'already_in_queue' || status === 'allocating') && mode ) { return { initialQueueState, initialSegment: { kind: 'matching', identity: mode }, mode, resume: true, }; } return { initialQueueState, initialSegment: { kind: 'bootstrap' }, resume: false, }; } interface OwnerRuntimePointer { release(): void; } const MAILBOX_DRAIN_TIMEOUT_MS = 2_000; const DESKTOP_RESOURCE_LOCALE = 'zh-CN'; const EVENTS_QUERY_BARRIER_TIMEOUT_MS = 10_000; const LOCAL_STOP_FORCE_EXIT_MS = 10_000; type ConfigurationWarning = (code: string, details: Readonly>) => void; export function roleFallbackBehaviors( config: Pick, catalog: Pick, warning: ConfigurationWarning = () => {}, ): ClawclawRoleFallbackBehaviors { const entries = new Map(catalog.list().map(entry => [entry.id, entry])); const result: Record } | undefined> = {}; for (const role of CLAWCLAW_ROLE_IDS) { const behaviorId = config.fallback_behaviors[role]; if (behaviorId === null) continue; const entry = entries.get(behaviorId); if (!entry?.loadable || entry.activationMode === 'automatic_only') { warning('behavior_fallback_unavailable', { role, behavior_id: behaviorId, ...(entry?.activationMode === 'automatic_only' ? { reason: 'strategy_automatic_only' } : {}) }); continue; } result[role] = { behaviorId, input: {} }; } return Object.freeze(result); } export function triggerRegistrations( sources: readonly ResolvedClawclawTriggerSource[], config: Pick, catalog: Pick, warning: ConfigurationWarning = () => {}, ): readonly ClawclawTriggerRegistration[] { const loadableBehaviors = new Set( catalog.list().filter((entry) => entry.loadable).map((entry) => entry.id), ); const overrides = new Map( toTriggerRegistrationOverrides(config.triggers).map((override) => [override.id, override]), ); const disabledTriggers = new Set(config.disabled_triggers); const sourceIds = new Set(sources.map((source) => source.id)); for (const id of overrides.keys()) { if (!sourceIds.has(id)) warning('trigger_source_unavailable', { trigger_id: id }); } return Object.freeze(sources.map((source): ClawclawTriggerRegistration => { const override = overrides.get(source.id); const behavior = override?.behavior ?? source.manifest.defaultBehavior; const requestedEnabled = !disabledTriggers.has(source.id); const enabled = requestedEnabled && source.apiVersion === TRIGGER_PLUGIN_API_VERSION && loadableBehaviors.has(behavior); if (requestedEnabled && !enabled) { warning('trigger_binding_unavailable', { trigger_id: source.id, behavior_id: behavior, api_version: source.apiVersion, }); } return Object.freeze({ source, enabled, ...(override?.input === undefined ? {} : { input: override.input }), ...(override?.behavior === undefined ? {} : { behavior: override.behavior }), ...(override?.behaviorInput === undefined ? {} : { behaviorInput: override.behaviorInput }), ...(override?.reflexPriority === undefined ? {} : { reflexPriority: override.reflexPriority }), ...(override?.cooldownMs === undefined ? {} : { cooldownMs: override.cooldownMs }), ...(override?.rearm === undefined ? {} : { rearm: override.rearm }), ...(override?.maxRuntimeMs === undefined ? {} : { maxRuntimeMs: override.maxRuntimeMs }), }); })); } interface EventsQueryBoundaryResult { ready: RuntimeReadyView; querySeq: number; sourceBoundaryMs: number; pluginReadyMs: number; totalMs: number; } interface PreparedEventsQueryTrace { querySeq: number; ownerStartedAtMs: number; ownerPreparedAtMs: number; } function eventsQueryId(value: unknown): string { if (typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,120}$/.test(value)) return value; return randomUUID(); } function boundedTiming(value: unknown): number | undefined { return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 3_600_000 ? Math.round(value) : undefined; } function ownerExpectedScope( value: unknown, ): Readonly<{ sessionId: string; segmentId: string }> | undefined { if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined; const source = value as Record; if (typeof source.sessionId !== 'string' || typeof source.segmentId !== 'string') return undefined; return { sessionId: source.sessionId, segmentId: source.segmentId }; } function ownerScopeIsCurrent( runtime: Pick, 'publicScope'>, expected: Readonly<{ sessionId: string; segmentId: string }>, ): boolean { const actual = runtime.publicScope(); return actual.sessionId === expected.sessionId && actual.segmentId === expected.segmentId; } function readyRoleForScope( runtime: Pick, 'readReadyView'>, expected: Readonly<{ sessionId: string; segmentId: string }>, ): string | undefined { const ready = runtime.readReadyView(0, 1); if ( ready.scope.sessionId !== expected.sessionId || ready.scope.segmentId !== expected.segmentId ) return undefined; const state = ready.state.state; if (!state || typeof state !== 'object' || Array.isArray(state)) return undefined; const you = (state as Record).you; if (!you || typeof you !== 'object' || Array.isArray(you)) return undefined; const role = (you as Record).role; return typeof role === 'string' ? role : undefined; } function eventsOutputCount(output: Record): number { if (Array.isArray(output.events)) return output.events.length; return output.found === true && output.event && typeof output.event === 'object' ? 1 : 0; } async function waitWithin(promise: Promise, timeoutMs: number, error: string): Promise { let timer: ReturnType | undefined; try { return await Promise.race([ promise, new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error(error)), timeoutMs); timer.unref?.(); }), ]); } finally { if (timer) clearTimeout(timer); } } async function waitForMailboxDrain( broker: MailboxRelayBroker, timeoutMs = MAILBOX_DRAIN_TIMEOUT_MS, ): Promise { const deadline = Date.now() + timeoutMs; while (broker.hasPendingCurrent()) { if (Date.now() >= deadline) return false; await new Promise((resolve) => setTimeout(resolve, 25)); } return true; } export function publishOwnerRuntimePointer( stateDir: string, control: OwnerControlServer, instanceId?: string, ): OwnerRuntimePointer { const path = gameStartRuntimePath(stateDir); const tempPath = `${path}.${process.pid}.tmp`; const value = { schema: 'clawclaw.owner.v1', owner_pid: process.pid, ...(instanceId ? { instance_id: instanceId } : {}), started_at: new Date().toISOString(), control: control.control, control_token: control.token, relay_token: control.relayToken, }; writeFileSync(tempPath, JSON.stringify(value), { encoding: 'utf8', mode: 0o600 }); try { chmodSync(tempPath, 0o600); } catch {} try { renameSync(tempPath, path); } catch (error) { try { unlinkSync(path); renameSync(tempPath, path); } catch { try { unlinkSync(tempPath); } catch {} throw error; } } try { chmodSync(path, 0o600); } catch {} let released = false; return { release: () => { if (released) return; released = true; try { const current = JSON.parse(readFileSync(path, 'utf8')) as Record; if (current.owner_pid === process.pid && current.control?.path === control.control.path) { unlinkSync(path); } } catch {} try { unlinkSync(tempPath); } catch {} }, }; } /** Runs one foreground owner with the explicitly configured Runtime Plugins. */ export async function runClawclawOwner( options: ClawclawOwnerOptions, ): Promise { let lock: OwnerLock | undefined; let telemetry: ReturnType | undefined; let ingressRawLog: ThreadedWsClientConfig['rawLog']; let closeGameSyncTransports: (() => Promise) | undefined; let runtime: ReturnType | undefined; let source: ClawclawSourcePlugin | undefined; let mailbox: ClawclawMailboxPlugin | undefined; let mailboxService: ClawclawMailboxService | undefined; let cclEventsMailbox: AgentMailboxCoordinator | undefined; let desktopMailbox: AgentMailboxCoordinator | undefined; let desktopEventPump: MailboxEventBatchPump | undefined; let channelAdapter: ClaudeChannelMailboxAdapter | undefined; let channelEventPump: MailboxEventBatchPump | undefined; let mailboxBroker: MailboxRelayBroker | undefined; let ownerControl: OwnerControlServer | undefined; let runtimePointer: OwnerRuntimePointer | undefined; let startingControl: ReturnType | undefined; let relayAlive = false; let relayAbort: AbortController | undefined; let relayPromise: Promise | undefined; let parentWatch: ParentProcessWatchHandle | undefined; let diagnosticSampleTimer: ReturnType | undefined; let processTimingSampler: RuntimeProcessTimingSampler | undefined; let localStopRequested = false; let forceExitTimer: ReturnType | undefined; const channelPolicy = channelOwnerDeliveryPolicy(options.channelDelivery); const requestLocalStop = (): void => { if (localStopRequested) return; localStopRequested = true; try { lock?.setPhase('stopping'); } catch {} forceExitTimer = setTimeout(() => process.exit(1), LOCAL_STOP_FORCE_EXIT_MS); forceExitTimer.unref?.(); void source?.submitIntent({ kind: 'stop' }).catch(() => {}); }; const onSignal = (): void => requestLocalStop(); startupMark('owner.entry'); try { lock = await timeStartup('owner.lock', () => acquireOwnerLock(options.profile, { force: options.forceExistingRuntime === true, })); const controlDone = startupSpan('owner.control'); startingControl = createStartingOwnerControl(lock.instanceId, requestLocalStop); ownerControl = await startOwnerControlServer( getProfileRuntimeStateDir(options.profile), startingControl.handle, { get observability() { return telemetry; } }, ); runtimePointer = publishOwnerRuntimePointer( getProfileRuntimeStateDir(options.profile), ownerControl, lock.instanceId, ); parentWatch = watchParentProcess(() => { runtime?.diagnostic('runtime.owner.parent_exited', { parent_pid: parentWatch?.parentPid ?? process.ppid, }, 'warn'); requestLocalStop(); }); process.on('SIGINT', onSignal); process.on('SIGTERM', onSignal); telemetry = createOwnerTelemetryRecorder(options.profile); telemetry.log('info', 'owner.control.started', { transport: ownerControl.control.kind }, { component: 'runtime.owner_control', }); controlDone?.(); const fullDiagnosticsEnabled = resolveOwnerObservabilityLevel() === 'full'; if (fullDiagnosticsEnabled) { const retention = observabilityRetention(); ingressRawLog = { path: ownerRawWsLogPath(getProfileRuntimeStateDir(options.profile)), options: retention }; telemetry.log('info', 'runtime.raw_ws.capture_started', { max_file_bytes: retention.maxFileBytes, retained_files: retention.retainedFiles, }, { component: 'runtime.transport' }); } const client = new GameClient({ lobbyUrl: options.profile.serverUrl, apiKey: options.profile.apiKey, agentName: options.profile.agentName, enableWs: true, gameSyncIngress: { rawLog: ingressRawLog, diagnostic: (name, attributes, severity = 'debug') => telemetry?.log(severity, name, attributes, { component: 'runtime.transport', scope: runtime?.publicScope(), }), }, }); closeGameSyncTransports = () => client.closeGameSyncTransports(); // Validate before starting a participation or attaching any game transport. void client.lobbyHostContext; const initialQueue = options.resolveStartupIntent ? { value: await timeStartup('owner.initial_queue_status', () => client.getQueueStatus('clawclaw')) } : undefined; const resolveIntent = options.resolveStartupIntent; const intent = resolveIntent && initialQueue ? await timeStartup('owner.resolve_participation', () => resolveIntent(client, initialQueue.value)) : options.intent; const assemblyDone = startupSpan('owner.resource_assembly'); const workspaceDir = getWorkspaceDir(); ensureAccountUserDataLayout(workspaceDir, options.profile); const perceptionConfig = readWorkspacePerceptionConfig(); const gameplayConfig = readGameplayConfig(workspaceDir, options.profile); const storedAgentWorkspace = readLocalAgentWorkspaceSnapshot(workspaceDir, options.profile); const agentWorkspace = filterInactiveAgentWorkspaceSnapshot( workspaceDir, options.profile, storedAgentWorkspace ? resolveLocalAgentWorkspaceSnapshot(workspaceDir, options.profile, storedAgentWorkspace) : undefined, ); const configurationWarning: ConfigurationWarning = (code, details) => { telemetry?.log('warn', `runtime.configuration.${code}`, details, { component: 'runtime.behavior', }); }; const disabledBehaviors = new Set(gameplayConfig.disabled_behaviors); const discoveredLocalCapabilities = discoverLocalCapabilities(workspaceDir, options.profile); const agentBehaviorSources = agentWorkspace ? listAgentWorkspaceBehaviorSources(workspaceDir, options.profile, agentWorkspace) : []; const behaviorSources = mergeAgentWorkspaceBehaviorSources( discoveredLocalCapabilities.behaviors .filter(({ source, entry }) => ( entry.selection === 'equipped' && !disabledBehaviors.has(source.id) && !agentWorkspace?.items.strategy.some(item => item.resourceId === entry.hub?.resourceId) )) .map(({ source }) => source), agentBehaviorSources, disabledBehaviors, ); const behaviorSourceById = new Map(behaviorSources.map(source => [source.id,source])); const behaviorCatalog = new ClawclawBehaviorCatalog(behaviorSources); const behaviorEventTypes = [...new Set( behaviorCatalog.list() .filter((entry) => entry.loadable && entry.apiVersion === BEHAVIOR_PLUGIN_API_VERSION) .flatMap((entry) => entry.produces ?? []), )]; const fallbackBehaviors = roleFallbackBehaviors( gameplayConfig, behaviorCatalog, configurationWarning, ); const triggerSources = listClawclawTriggerSources( getUserDataAccountTriggersDir(workspaceDir, options.profile), ); const legacyTriggers = triggerRegistrations( triggerSources, gameplayConfig, behaviorCatalog, configurationWarning, ); const loadableStrategies = new Set(behaviorCatalog.list().filter(entry => entry.loadable).map(entry => entry.id)); const embeddedTriggers = behaviorSources.flatMap(source => { if (!loadableStrategies.has(source.id)) return []; if (source.triggerError) configurationWarning('strategy_trigger_unavailable', { behavior_id: source.id, reason: source.triggerError, }); const trigger = strategyTriggerSource(source); return trigger ? [trigger] : []; }); const disabledPerceptions = new Set(gameplayConfig.disabled_perception_modules); const agentPerceptionSources = agentWorkspace ? listAgentWorkspacePerceptionSources(workspaceDir, options.profile, agentWorkspace) : []; const localPerceptionSources = discoveredLocalCapabilities.perceptions .filter(({ source, entry }) => ( entry.selection === 'equipped' && !disabledPerceptions.has(source.id) && !agentWorkspace?.items.perception.some(item => item.resourceId === entry.hub?.resourceId) )) .map(({ source }) => source); const perceptionSources = mergeAgentWorkspacePerceptionSources( localPerceptionSources, agentPerceptionSources, disabledPerceptions, ); const perceptionModules = [ ...localPerceptionSources.map(({ id }) => id), ...agentPerceptionSources.map(({ id }) => id), ].filter((id, index, values) => values.indexOf(id) === index); const assembly = assembleClawclawPlugins(client, { epochPlugins: options.epochPlugins, perception: { ...perceptionConfig.perception, modules: perceptionModules, moduleSources: perceptionSources, diagnosticsEnabled: fullDiagnosticsEnabled, }, behaviorCatalog, behaviorDiagnosticsEnabled: fullDiagnosticsEnabled, triggerDiagnosticsEnabled: fullDiagnosticsEnabled, fallbackBehaviors, behaviorEventTypes, triggers: legacyTriggers, embeddedPerceptions: embeddedTriggers, }); await assembly.behavior.setIdleMs(gameplayConfig.idle_ms); const epochPlugins = assembly.plugins; mailbox = assembly.mailbox; assemblyDone?.(); const runtimeStart = deriveClawclawOwnerRuntimeStart( initialQueue ? initialQueue.value : await timeStartup('owner.initial_queue_status', () => client.getQueueStatus('clawclaw')), intent, ); const reflexControl = new BehaviorReflexControl(assembly.modules, assembly.behavior, behaviorCatalog, () => runtime!.publicScope(), embeddedTriggers); const runtimeDone = startupSpan('owner.runtime_init'); runtime = createClawclawRuntime(options.profile, { processingCadence: createClawclawProcessingCadence(readRuntimeCycleIntervalMs()), initialSegment: runtimeStart.initialSegment, mode: runtimeStart.mode, resume: runtimeStart.resume, resumeKey: runtimeStart.resumeKey, observability: telemetry, runtimeEpochPlugins: epochPlugins, visualEventDelivery: perceptionConfig.events.delivery, visualEventTypes: assembly.perception.produces.events, behaviorEventTypes: assembly.behavior.produces?.events ?? [], perceptionEventTypes: assembly.modules?.produces.events, }); runtimeDone?.(); const deferredShort = new DeferredMeetingShortStrategy(runtime, assembly.behavior, request => { const source = behaviorSourceById.get(request.behavior); if (!source) return undefined; normalizeBehaviorInput(request.input, source.inputs, { allowedKeys: ['timeout_ms', 'duration_ms'] }); return resolveClawclawResourceMetadata(source, 'zh-CN'); }); assembly.behavior.attachDeferredShortControl(deferredShort); if (fullDiagnosticsEnabled) { processTimingSampler = new RuntimeProcessTimingSampler(); const sample = (): void => { try { const memory = process.memoryUsage(); const heap = getHeapStatistics(); const behaviorStatus = assembly.behavior.status(); const effectiveBehaviorId = behaviorStatus.current?.behaviorId ?? behaviorStatus.stack.long?.behaviorId ?? behaviorStatus.stack.fallback?.behaviorId; const effectiveBehavior = effectiveBehaviorId ? behaviorSourceById.get(effectiveBehaviorId) : undefined; telemetry?.log('debug', 'runtime.diagnostics.sample', { sample_interval_ms: FULL_DIAGNOSTIC_SAMPLE_INTERVAL_MS, node_version: process.version, process_platform: process.platform, process_arch: process.arch, process_uptime_seconds: Math.round(process.uptime()), process_timing: processTimingSampler?.sample(), process_memory: { rss_bytes: memory.rss, heap_total_bytes: memory.heapTotal, heap_used_bytes: memory.heapUsed, external_bytes: memory.external, array_buffers_bytes: memory.arrayBuffers, heap_size_limit_bytes: heap.heap_size_limit, }, scheduler: runtime?.runtimeEpochDiagnosticSnapshot(), retained_records: runtime?.runtimeRetainedRecordCounts(), persistence: runtime?.runtimePersistenceDiagnostics(), detail_capture: telemetry?.detailStats(), behavior: { ...assembly.behavior.diagnosticSnapshot(), effective_source: effectiveBehavior ? { id: effectiveBehavior.id, execution: effectiveBehavior.execution, every_ticks: effectiveBehavior.everyTicks, source: effectiveBehavior.management.source, managed_by: effectiveBehavior.management.managedBy, resource_id: effectiveBehavior.management.resourceId ?? null, version_id: effectiveBehavior.management.versionId ?? null, resolution: effectiveBehavior.management.resolution ?? null, file: effectiveBehavior.sourcePath.split(/[\\/]/).at(-1) ?? null, } : null, }, perception: assembly.perception.diagnosticSnapshot(), trigger: assembly.trigger?.diagnosticSnapshot(), }, { component: 'runtime.diagnostics', scope: runtime?.publicScope(), }); } catch { // Full diagnostics must remain observational and never affect gameplay. } }; sample(); diagnosticSampleTimer = setInterval(sample, FULL_DIAGNOSTIC_SAMPLE_INTERVAL_MS); diagnosticSampleTimer.unref?.(); } if (!isMailboxRepository(runtime.repository)) { throw new Error('The configured Runtime repository does not support durable Mailbox delivery.'); } const mailboxRepository = runtime.repository; const perceptionSourceById = new Map([...perceptionSources, ...embeddedTriggers].map(source => [source.id, source])); const perceptionReportAdapter = new GameSyncPerceptionReportAdapter({ producerPluginIds: [assembly.perception.id, assembly.reminders.id, ...(assembly.modules ? [assembly.modules.id] : [])], descriptor: id => { const source = perceptionSourceById.get(id); return source ? { ...resolveClawclawResourceMetadata({ ...source.manifest, display: source.display }, client.gameSyncLocale), perceptionId: id } : undefined; }, send: (reports) => client.reportGameSyncPerceptions(reports), diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes), }); const runtimeReportAdapter = new GameSyncRuntimeReportAdapter({ snapshot: ready => { const view = runtime!.readReadyView(0, 1); if (view.epochSeq !== ready.epochSeq || view.scope.segmentId !== ready.scope.segmentId) return null; const state = view.state.state; const status = view.state.stateStatus; if (!state?.game_id || status.connectionState !== 'connected' || !status.connectionId || status.terminal || state.phase === 'game_over' || state.phase === 'settling') return null; const locale = client.gameSyncLocale; return { gameId: String(state.game_id), connectionId: status.connectionId, resources: { perceivers: [...assembly.perception.localizedModuleDescriptors(locale), ...assembly.reminders.localizedModuleDescriptors(locale), ...(assembly.modules?.localizedModuleDescriptors(locale) ?? [])].sort((a, b) => a.id.localeCompare(b.id)), strategies: behaviorCatalog.list().filter(entry => entry.loadable).map(entry => resolveClawclawResourceMetadata(behaviorSourceById.get(entry.id)!, locale)).sort((a, b) => a.id.localeCompare(b.id)), } }; }, send: (report, gameId, connectionId) => client.reportGameSyncRuntime(report, gameId, connectionId), diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes), }); cclEventsMailbox = new AgentMailboxCoordinator({ repository: mailboxRepository, readyView: () => runtime!.readReadyView(0, 1), presentEvent: ownerAgentEventPresenter('ccl_events', !!options.desktopEvents), compactState: compactStateForEvents, admitEvent: isClawclawAgentNotification, eventFilter: clawclawEventRequiresDetails, delegatedMonitorConsumerId: MONITOR_MAILBOX_CONSUMER_ID, consumerId: CCL_EVENTS_MAILBOX_CONSUMER_ID, adapter: { id: 'clawclaw.mailbox.adapter.ccl-events', acknowledgement: 'explicit', consumerId: CCL_EVENTS_MAILBOX_CONSUMER_ID, }, diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes), }); mailboxService = new ClawclawMailboxService({ notificationOnly: true, repository: mailboxRepository, readyView: () => runtime!.readReadyView(0, 1), agentMailbox: cclEventsMailbox, consumerId: MONITOR_MAILBOX_CONSUMER_ID, delegatedDetailsConsumerId: CCL_EVENTS_MAILBOX_CONSUMER_ID, monitorEnabled: !!options.notificationHost, diagnostic: (name, attributes, severity) => runtime?.diagnostic(name, attributes, severity), }); const mailboxDrivers: ClawclawMailboxDriver[] = [ runtimeReportAdapter, perceptionReportAdapter, mailboxService, cclEventsMailbox, ]; if (options.desktopEvents) { desktopMailbox = new AgentMailboxCoordinator({ admitEvent: isClawclawAgentNotification, repository: mailboxRepository, readyView: () => runtime!.readReadyView(0, 1), presentEvent: ownerAgentEventPresenter('desktop_ipc', true), compactState: () => null, consumerId: DESKTOP_IPC_MAILBOX_CONSUMER_ID, diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes), }); const desktopSink = new DesktopEventSocketSink({ ...options.desktopEvents, activeResources: () => ({ locale: DESKTOP_RESOURCE_LOCALE, strategy: (() => { const stack = assembly.behavior.status().stack; const behaviorId = stack.long?.behaviorId ?? stack.fallback?.behaviorId; const source = behaviorId ? behaviorSourceById.get(behaviorId) : undefined; return source ? resolveClawclawResourceMetadata(source, DESKTOP_RESOURCE_LOCALE) : null; })(), perceptions: [...assembly.perception.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE), ...assembly.reminders.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE), ...(assembly.modules?.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE) ?? [])], }), eventDescriptors: () => assembly.perception .localizedEventDescriptors(DESKTOP_RESOURCE_LOCALE) .map((descriptor) => ({ type: descriptor.type, perception_id: descriptor.perceptionId, name: descriptor.name, description: descriptor.description, })), onConnected: () => desktopEventPump?.retryNow(), diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes), }); desktopEventPump = new MailboxEventBatchPump({ adapter: { id: 'clawclaw.mailbox.adapter.desktop-ipc', acknowledgement: 'explicit', consumerId: DESKTOP_IPC_MAILBOX_CONSUMER_ID, }, source: { prepare: () => { const result = desktopMailbox!.prepareEvents({ deliveryVia: 'desktop_ipc', ownerIdPrefix: 'desktop_ipc', }); if (startupTraceEnabled() && result.deliveryToken && result.batch.events.some(event => { const type = typeof event === 'string' ? event.split(' | ', 1)[0].trim() : event.type; return type === 'joined' || type === 'match_start'; })) startupMark('match.mailbox_prepared'); return result; }, renew: (deliveryToken) => desktopMailbox!.renew(deliveryToken), ack: (deliveryToken, level) => desktopMailbox!.ack(deliveryToken, level), release: (deliveryToken) => desktopMailbox!.release(deliveryToken), }, sink: desktopSink, diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes), }); mailboxDrivers.push(desktopMailbox, desktopEventPump); desktopSink.start(); } assembly.behavior.attachDriver(createClawclawBehaviorControlDriver(runtime)); if (channelPolicy.enabled) { channelAdapter = new ClaudeChannelMailboxAdapter({ notificationOnly: true, repository: mailboxRepository, readyView: () => runtime!.readReadyView(0, 1), diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes), }); const channelSink = new ClaudeChannelSocketSink({ onConnected: () => channelEventPump?.retryNow(), diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes), }); channelEventPump = new MailboxEventBatchPump({ source: { prepare: () => channelAdapter!.prepare(), renew: (deliveryToken) => channelAdapter!.renew(deliveryToken), ack: (deliveryToken, level) => channelAdapter!.ack(deliveryToken, level), release: (deliveryToken) => channelAdapter!.release(deliveryToken), }, sink: channelSink, diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes), }); mailboxDrivers.push(channelAdapter, channelEventPump); channelSink.start(); } mailbox.attachDriver(new CompositeClawclawMailboxDriver(mailboxDrivers)); const ownerSource = new ClawclawSourcePlugin({ client, profile: options.profile, initialIntent: intent, initialQueueState: runtimeStart.initialQueueState, }); source = ownerSource; let eventsQueryBarrier: Promise | undefined; let eventsQuerySequence = 0; const preparedEventsQueryTraces = new Map(); const readyViewAfterEventsQueryBoundary = (queryId: string, querySeq: number) => { if (eventsQueryBarrier) return eventsQueryBarrier; const requestId = queryId; const startedAt = Date.now(); const operation = (async () => { let epochSeq: number | undefined; try { const acceptance = await ownerSource.submitEventsQueryBoundary(requestId); const acceptedAt = Date.now(); epochSeq = acceptance.epoch.epochSeq; runtime!.diagnostic('runtime.events_query.boundary_accepted', { query_seq: querySeq, epoch_seq: epochSeq, source_boundary_ms: acceptedAt - startedAt, }); const ready = await waitWithin( runtime!.waitForEpochReadyView(epochSeq), EVENTS_QUERY_BARRIER_TIMEOUT_MS, 'events_query_barrier_timeout', ); runtime!.diagnostic('runtime.events_query.boundary_ready', { query_seq: querySeq, epoch_seq: ready.epochSeq, event_watermark: ready.eventWatermark, source_boundary_ms: acceptedAt - startedAt, plugin_ready_ms: Date.now() - acceptedAt, duration_ms: Date.now() - startedAt, }); return { ready, querySeq, sourceBoundaryMs: acceptedAt - startedAt, pluginReadyMs: Date.now() - acceptedAt, totalMs: Date.now() - startedAt, }; } catch (error) { runtime!.diagnostic('runtime.events_query.boundary_failed', { query_seq: querySeq, ...(epochSeq === undefined ? {} : { epoch_seq: epochSeq }), duration_ms: Date.now() - startedAt, error: error instanceof Error ? error.message : String(error), }, 'warn'); throw error; } })(); eventsQueryBarrier = operation.finally(() => { eventsQueryBarrier = undefined; }); return eventsQueryBarrier; }; if (options.notificationHost) { mailboxBroker = new MailboxRelayBroker( mailboxRepository, 'short', MONITOR_MAILBOX_CONSUMER_ID, ); relayAbort = new AbortController(); relayAlive = true; // Mirror the Claude Code Host Monitor token bucket so stdout writes never // exceed the rate the Host will actually deliver (capacity 10, refill // 1/2s). Writes the gate denies are nack'ed back to pending and reach the // agent on a later poll or via `ccl events` — never silently dropped. const monitorRateGate = new HostMonitorWriteGate(); relayPromise = runStdoutMailboxRelay({ request: async (type, payload) => { if (type === 'mailbox_claim') mailboxService?.prepareMonitor(); return mailboxBroker?.handle({ type, ...payload }) ?? null; }, emit: (payload) => options.notificationHost!.emit(payload), compose: (payloads) => mailboxService!.composeMonitor(payloads), rateGate: monitorRateGate, isOwnerAlive: () => relayAlive, mode: 'short', signal: relayAbort.signal, }).catch((error) => { runtime?.diagnostic('runtime.mailbox.host_relay_failed', { error: error instanceof Error ? error.message : String(error), }, 'error'); }); } startingControl.setHandler(async (request, context) => { if (context.principal === 'host_relay') { if (request.type === 'mailbox_claim') mailboxService?.prepareMonitor(); return mailboxBroker?.handle(request) ?? { ok: false, error: 'mailbox_monitor_unavailable' }; } if (context.principal !== 'master') return { ok: false, error: 'owner_request_not_supported' }; if (request.type === 'mailbox_claim' || request.type === 'mailbox_ack' || request.type === 'mailbox_nack') { if (request.type === 'mailbox_claim') mailboxService?.prepareMonitor(); return mailboxBroker?.handle(request) ?? { ok: false, error: 'mailbox_monitor_unavailable' }; } if (request.type === 'mailbox_events_prepare') { const ownerStartedAtMs = Date.now(); const queryId = eventsQueryId(request.query_id); const querySeq = ++eventsQuerySequence; const eventType = typeof request.event_type === 'string' ? request.event_type : undefined; const mode = request.mode === 'backlog' ? 'backlog' : 'current'; const queryKind = eventType ? 'latest_by_type' : mode === 'backlog' ? 'unread_backlog' : 'unread_current'; let stage = 'query_boundary'; try { const boundary = !eventType && mode === 'current' ? await readyViewAfterEventsQueryBoundary(queryId, querySeq) : undefined; const mailboxStartedAtMs = Date.now(); stage = 'mailbox_prepare'; const prepared = await mailboxService!.prepareEventsWhenAvailable({ ...(eventType ? { eventType } : {}), mode, }, boundary?.ready); const ownerPreparedAtMs = Date.now(); for (const [token, trace] of preparedEventsQueryTraces) { if (ownerPreparedAtMs - trace.ownerPreparedAtMs > 60_000) { preparedEventsQueryTraces.delete(token); } } if (prepared.deliveryToken) { preparedEventsQueryTraces.set(prepared.deliveryToken, { querySeq, ownerStartedAtMs, ownerPreparedAtMs, }); } const state = prepared.output.state; const stateRecord = state && typeof state === 'object' ? state as Record : undefined; runtime!.diagnostic('runtime.events_query.prepared', { query_seq: querySeq, query_kind: queryKind, ...(eventType ? { event_type: eventType } : {}), boundary_used: !!boundary, ...(boundary ? { boundary_query_seq: boundary.querySeq, boundary_shared: boundary.querySeq !== querySeq, source_boundary_ms: boundary.sourceBoundaryMs, plugin_ready_ms: boundary.pluginReadyMs, boundary_total_ms: boundary.totalMs, ready_epoch_seq: boundary.ready.epochSeq, event_watermark: boundary.ready.eventWatermark, } : {}), mailbox_prepare_ms: ownerPreparedAtMs - mailboxStartedAtMs, owner_total_ms: ownerPreparedAtMs - ownerStartedAtMs, event_count: eventsOutputCount(prepared.output), delivery_token_present: !!prepared.deliveryToken, ...(typeof stateRecord?.phase === 'string' ? { phase: stateRecord.phase } : {}), ...(typeof stateRecord?.tick === 'number' ? { tick: stateRecord.tick } : {}), }, 'info'); return { ok: true, type: 'mailbox_events_prepare', query_id: queryId, output: prepared.output, ...(prepared.deliveryToken ? { delivery_token: prepared.deliveryToken } : {}), }; } catch (error) { runtime!.diagnostic('runtime.events_query.prepare_failed', { query_seq: querySeq, query_kind: queryKind, ...(eventType ? { event_type: eventType } : {}), stage, duration_ms: Date.now() - ownerStartedAtMs, error: error instanceof Error ? error.message : String(error), }, 'warn'); throw error; } } if (request.type === 'mailbox_events_ack') { const ackStartedAtMs = Date.now(); const token = typeof request.delivery_token === 'string' ? request.delivery_token : ''; const trace = preparedEventsQueryTraces.get(token); preparedEventsQueryTraces.delete(token); const accepted = mailboxService!.ackEvents(token); runtime!.diagnostic('runtime.events_query.client_completed', { ...(trace ? { query_seq: trace.querySeq } : {}), accepted, ...(trace ? { prepared_to_ack_ms: ackStartedAtMs - trace.ownerPreparedAtMs, owner_observed_total_ms: Date.now() - trace.ownerStartedAtMs, } : {}), ...(boundedTiming(request.client_elapsed_ms) === undefined ? {} : { client_elapsed_before_ack_ms: boundedTiming(request.client_elapsed_ms), }), ...(boundedTiming(request.prepare_rpc_ms) === undefined ? {} : { prepare_rpc_ms: boundedTiming(request.prepare_rpc_ms), }), ...(boundedTiming(request.stdout_write_ms) === undefined ? {} : { stdout_write_ms: boundedTiming(request.stdout_write_ms), }), ...(boundedTiming(request.output_characters) === undefined ? {} : { output_characters: boundedTiming(request.output_characters), }), ...(boundedTiming(request.output_bytes) === undefined ? {} : { output_bytes: boundedTiming(request.output_bytes), }), ack_processing_ms: Date.now() - ackStartedAtMs, }, accepted ? 'info' : 'warn'); return accepted ? { ok: true, type: 'mailbox_events_ack' } : { ok: false, error: 'mailbox_delivery_not_found' }; } if (request.type === 'mailbox_events_release') { const releaseStartedAtMs = Date.now(); const token = typeof request.delivery_token === 'string' ? request.delivery_token : ''; const trace = preparedEventsQueryTraces.get(token); preparedEventsQueryTraces.delete(token); const released = mailboxService!.releaseEvents(token); runtime!.diagnostic('runtime.events_query.client_aborted', { ...(trace ? { query_seq: trace.querySeq } : {}), released, outcome: typeof request.outcome === 'string' ? request.outcome : 'released', ...(trace ? { prepared_to_release_ms: releaseStartedAtMs - trace.ownerPreparedAtMs, owner_observed_total_ms: Date.now() - trace.ownerStartedAtMs, } : {}), ...(boundedTiming(request.client_elapsed_ms) === undefined ? {} : { client_elapsed_before_release_ms: boundedTiming(request.client_elapsed_ms), }), ...(boundedTiming(request.prepare_rpc_ms) === undefined ? {} : { prepare_rpc_ms: boundedTiming(request.prepare_rpc_ms), }), release_processing_ms: Date.now() - releaseStartedAtMs, }, 'warn'); return released ? { ok: true, type: 'mailbox_events_release' } : { ok: false, error: 'mailbox_delivery_not_found' }; } if (request.type === 'snapshot') { const ready = runtime!.readReadyView(0, 1); return { ok: true, type: 'snapshot', scope: ready.scope, state: ready.state.state, summary: ready.state.state, state_status: ready.state.stateStatus, ready: { epoch_seq: ready.epochSeq, frame_seq: ready.frameSeq, event_commit_seq: ready.eventWatermark, }, }; } if (request.type === 'action') { const capability = typeof request.capability === 'string' ? request.capability : ''; const expected = request.expected_scope; if ( !capability || !expected || typeof expected.sessionId !== 'string' || typeof expected.segmentId !== 'string' ) return { ok: false, error: 'invalid_action_request' }; const result = await performOwnerAgentAction( runtime!, capability, request.action, { sessionId: expected.sessionId, segmentId: expected.segmentId }, ); return { ok: true, type: 'action', result }; } if (request.type === 'perception_status') { return { ok: true, type: request.type, status: [...Object.entries(BUILTIN_PERCEPTION_NAMES).map(([id, name]) => ({ id: `${BUILTIN_PERCEPTION_PREFIX}${id}`, name, mandatory: true, configurable: false, outcome: runtime!.readReadyView().pluginOutcomes[`${BUILTIN_PERCEPTION_PREFIX}${id}`]?.outcome, })).filter(item => !request.perception || item.id === request.perception), ...(assembly.modules?.status(request.perception) ?? [])] }; } if (request.type === 'perception_update') { const expected = ownerExpectedScope(request.expected_scope); if (!expected || !request.input || typeof request.input !== 'object' || Array.isArray(request.input) || typeof request.perception !== 'string') return { ok: false, type: request.type, error: 'invalid_perception_control_request' }; if (runtime!.currentSegment().kind !== 'game') return { ok: false, type: request.type, error: 'no_active_game' }; if (!ownerScopeIsCurrent(runtime!,expected)) return { ok: false, type: request.type, error: 'stale_runtime_scope' }; try { if (request.perception.startsWith(BUILTIN_PERCEPTION_PREFIX)) throw Error('builtin_perception_readonly'); if (!assembly.modules) throw Error('perception_not_found'); const result = assembly.modules.configure(request.perception,request.input,() => ownerScopeIsCurrent(runtime!,expected)); return { ok: true, type: request.type, result }; } catch (error) { return { ok: false, type: request.type, error: error instanceof Error ? error.message : 'perception_control_failed' }; } } if (request.type === 'behavior_watch' || request.type === 'behavior_unwatch' || request.type === 'behavior_update') { if (runtime!.currentSegment().kind !== 'game') { return { ok: false, type: request.type, error: 'no_active_game' }; } const expected = ownerExpectedScope(request.expected_scope); const behavior = typeof request.behavior === 'string' ? request.behavior.trim() : ''; const activationId = typeof request.activation_id === 'string' ? request.activation_id.trim() : ''; const patch = request.type === 'behavior_unwatch' ? {} : request.input; if (!expected || !patch || typeof patch !== 'object' || Array.isArray(patch) || (request.type === 'behavior_update' ? (Boolean(behavior) === Boolean(activationId)) : (!behavior || !!activationId))) { return { ok: false, type: request.type, error: 'invalid_behavior_control_request' }; } if (!ownerScopeIsCurrent(runtime!, expected)) return { ok: false, type: request.type, error: 'stale_runtime_scope' }; try { if (activationId) { const activation = await assembly.behavior.updateInput(activationId, patch, () => ownerScopeIsCurrent(runtime!, expected)); return { ok: true, type: request.type, updated: true, activation }; } const operation = request.type === 'behavior_watch' ? 'enable' : request.type === 'behavior_unwatch' ? 'disable' : 'update'; const result = await reflexControl.apply(operation, behavior, patch, expected); return { ok: true, type: request.type, result }; } catch (error) { return { ok: false, type: request.type, error: error instanceof Error ? error.message : 'behavior_control_failed' }; } } if (request.type === 'behavior_start') { const expected = ownerExpectedScope(request.expected_scope); const behavior = typeof request.behavior === 'string' ? request.behavior.trim() : ''; const layer = request.layer === 'long' || request.layer === 'short' ? request.layer : undefined; const behaviorInput = request.input; const maxRuntimeMs = request.max_runtime_ms; if ( !expected || !behavior || !layer || !behaviorInput || typeof behaviorInput !== 'object' || Array.isArray(behaviorInput) || (maxRuntimeMs !== undefined && ( !Number.isSafeInteger(maxRuntimeMs) || maxRuntimeMs <= 0 || maxRuntimeMs > 120_000 )) ) return { ok: false, type: 'behavior_start', error: 'invalid_behavior_start_request' }; return deferredShort.start({ expectedScope: expected, behavior, layer, input: behaviorInput, ...(maxRuntimeMs === undefined ? {} : { maxRuntimeMs }), }); } if (request.type === 'behavior_status') { const id = typeof request.behavior === 'string' ? request.behavior : undefined; const pending = deferredShort.status(id); return { ok: true, type: 'behavior_status', status: { ...reflexControl.view(id), ...(pending ? { pending_short: pending } : {}), } }; } if (request.type === 'behavior_cancel') { const expected = ownerExpectedScope(request.expected_scope); if (!expected) return { ok: false, type: 'behavior_cancel', error: 'invalid_behavior_cancel_request' }; if (!ownerScopeIsCurrent(runtime!, expected)) { return { ok: false, type: 'behavior_cancel', error: 'stale_runtime_scope' }; } const requestedId = typeof request.activation_id === 'string' ? request.activation_id.trim() : assembly.behavior.status().current?.activationId ?? deferredShort.status()?.request_id; if (requestedId && deferredShort.cancel(requestedId)) { return { ok: true, type: 'behavior_cancel', cancelled: true, request_id: requestedId }; } if (!requestedId) { return { ok: true, type: 'behavior_cancel', cancelled: false }; } const stack = assembly.behavior.status().stack; const known = [stack.long, stack.short, stack.reflex] .some((activation) => activation?.activationId === requestedId); if (!known) { return { ok: true, type: 'behavior_cancel', cancelled: false, activation_id: requestedId }; } await assembly.behavior.cancel(requestedId, 'cancelled_by_agent'); return { ok: true, type: 'behavior_cancel', cancelled: true, activation_id: requestedId }; } if (request.type === 'behavior_fallback') { const expected = ownerExpectedScope(request.expected_scope); const role = typeof request.role === 'string' ? request.role : ''; if ( !expected || !(CLAWCLAW_ROLE_IDS as readonly string[]).includes(role) || (request.action !== 'set' && request.action !== 'clear') ) return { ok: false, type: 'behavior_fallback', error: 'invalid_behavior_fallback_request' }; if (!ownerScopeIsCurrent(runtime!, expected)) { return { ok: false, type: 'behavior_fallback', error: 'stale_runtime_scope' }; } const latest = readGameplayConfig(workspaceDir, options.profile); const selected = latest.fallback_behaviors[role as keyof typeof latest.fallback_behaviors]; const error = request.action === 'set' && selected && behaviorCatalog.activationError(selected); if (error) return { ok: false, type: 'behavior_fallback', error }; const currentRole = readyRoleForScope(runtime!, expected); if (currentRole === role) { await assembly.behavior.noteAgentActivity(); } await assembly.behavior.configureFallbackBehaviors(roleFallbackBehaviors( latest, behaviorCatalog, configurationWarning, ), currentRole); return { ok: true, type: 'behavior_fallback', role, fallback: selected, }; } if (request.type === 'behavior_idle') { const expected = ownerExpectedScope(request.expected_scope); if ( !expected || !Number.isSafeInteger(request.idle_ms) || request.idle_ms < 0 || request.idle_ms > 60_000 ) return { ok: false, type: 'behavior_idle', error: 'invalid_behavior_idle_request' }; if (!ownerScopeIsCurrent(runtime!, expected)) { return { ok: false, type: 'behavior_idle', error: 'stale_runtime_scope' }; } const latest = readGameplayConfig(workspaceDir, options.profile); await assembly.behavior.setIdleMs(latest.idle_ms); return { ok: true, type: 'behavior_idle', idle_ms: latest.idle_ms }; } if (request.type === 'trigger_configure') { const expected = ownerExpectedScope(request.expected_scope); if (!expected || typeof request.trigger !== 'string' || !request.trigger.trim()) { return { ok: false, type: 'trigger_configure', error: 'invalid_trigger_configure_request' }; } if (!ownerScopeIsCurrent(runtime!, expected)) { return { ok: false, type: 'trigger_configure', error: 'stale_runtime_scope' }; } const latest = readGameplayConfig(workspaceDir, options.profile); const currentTriggerSources = listClawclawTriggerSources( getUserDataAccountTriggersDir(workspaceDir, options.profile), ); if (!currentTriggerSources.some((source) => source.id === request.trigger)) { return { ok: false, type: 'trigger_configure', error: 'trigger_source_unavailable' }; } if (!assembly.trigger) return { ok: false, type: request.type, error: 'trigger_runtime_restart_required' }; assembly.trigger.configure(triggerRegistrations( currentTriggerSources, latest, behaviorCatalog, configurationWarning, )); return { ok: true, type: 'trigger_configure', trigger: request.trigger, config: latest.triggers[request.trigger] ?? null, }; } if (request.type === 'quit' || request.type === 'leave') { await ownerSource.submitIntent({ kind: 'leave' }); return { ok: true, type: request.type }; } if (request.type === 'training_mode') { if (!isTrainingRoomMode(request.room_type)) { return { ok: false, type: request.type, error: 'invalid_training_room_type' }; } const result = await ownerSource.submitIntent({ kind: 'training_mode', roomType: request.room_type, }); return { ok: true, type: request.type, result }; } if (request.type === 'training_role_lock') { if (!isTrainingRole(request.role)) { return { ok: false, type: request.type, error: 'invalid_training_role', roles: [...CLAWCLAW_ROLE_IDS] }; } const result = await ownerSource.submitIntent({ kind: 'training_role_lock', role: request.role, }); return { ok: true, type: request.type, role: request.role, result }; } if (request.type === 'training_role_clear') { const result = await ownerSource.submitIntent({ kind: 'training_role_clear' }); return { ok: true, type: request.type, role: null, result }; } return { ok: false, error: 'owner_request_not_supported' }; }); if (localStopRequested) return { reason: 'stopped' }; startupMark('owner.source_start'); const startingRuntime = runtime; await timeStartup('owner.runtime_start', () => startingRuntime.start()); await timeStartup('owner.source_attach', () => startingRuntime.startSourcePlugin(ownerSource)); await desktopEventPump?.flush(); await channelEventPump?.flush(); if (localStopRequested) await ownerSource.submitIntent({ kind: 'stop' }); if (!localStopRequested) lock.setPhase('ready'); options.notificationHost?.markMailboxReady(); const completion = await source.waitForCompletion(); await runtime.flush(); await mailboxService.flush(); await cclEventsMailbox.flush(); await desktopMailbox?.flush(); await desktopEventPump?.drain(); if (channelOwnerDeliveryPolicy(options.channelDelivery, localStopRequested).drainOnNaturalCompletion) { await channelAdapter!.flush(); await channelEventPump!.drain(); runtime.diagnostic('runtime.channel.shutdown_drained', { bounded_by: 'current_delivery_attempt', }); } if (mailboxBroker && !(await waitForMailboxDrain(mailboxBroker))) { runtime.diagnostic('runtime.shutdown.mailbox_drain_incomplete', { timeout_ms: MAILBOX_DRAIN_TIMEOUT_MS, }, 'warn'); } return completion; } finally { if (diagnosticSampleTimer) clearInterval(diagnosticSampleTimer); processTimingSampler?.stop(); process.off('SIGINT', onSignal); process.off('SIGTERM', onSignal); if (forceExitTimer) clearTimeout(forceExitTimer); parentWatch?.stop(); relayAlive = false; relayAbort?.abort(new Error('owner_stopping')); await relayPromise; try { try { await ownerControl?.close(); } finally { runtimePointer?.release(); await runtime?.close(); } } finally { try { await closeGameSyncTransports?.(); await telemetry?.closeWithin(2_000).catch(() => false); } finally { lock?.release(); } } } }