import { randomUUID } from 'node:crypto'; import type { ClawclawResolvedResourceMetadata } from '../../sdk/behavior-plugin/index.js'; import type { Runtime } from '../framework/runtime.js'; import type { OwnerControlResponse } from '../owner-control.js'; import type { ClawclawBehaviorPlugin } from './plugins/behavior/behavior-plugin.js'; type StartRuntime = Pick; type BehaviorStarter = Pick; type DeferredStartRuntime = StartRuntime & Pick & { readReadyView(): Pick, 'state'>; }; interface BehaviorStartRequest { expectedScope: Readonly<{ sessionId: string; segmentId: string }>; behavior: string; layer: 'long' | 'short'; input: Readonly>; maxRuntimeMs?: number; } function startRejection(runtime: StartRuntime, request: BehaviorStartRequest): OwnerControlResponse | undefined { const actual = runtime.publicScope(); const expected = request.expectedScope; if (actual.sessionId !== expected.sessionId || actual.segmentId !== expected.segmentId) { return { ok: false, type: 'behavior_start', error: 'stale_runtime_scope' }; } if (runtime.currentSegment().kind !== 'game') { return { ok: false, type: 'behavior_start', error: 'no_active_game' }; } // Admission reads accepted Source state, not the potentially older Ready view. const { state, stateStatus } = runtime.readState(); const scope = stateStatus.scope; const inScope = scope?.sessionId === expected.sessionId && scope.segmentId === expected.segmentId; let code: string; let message: string; if (inScope && (state?.phase === 'game_over' || state?.phase === 'settling')) { code = 'GAME_ENDED'; message = `The game has ended. Strategy '${request.behavior}' was not started.`; } else if (inScope && state?.you?.is_alive === false) { code = 'PLAYER_DEAD'; message = `The player is dead. Strategy '${request.behavior}' was not started.`; } else if (!inScope || stateStatus.status !== 'fresh' || state?.you?.is_alive !== true) { code = 'GAME_STATE_UNAVAILABLE'; message = `Current player state is unavailable. Strategy '${request.behavior}' was not started.`; } else { // A living player's strategy may still wait for a meeting or another layer. return undefined; } return { ok: false, type: 'behavior_start', error: code, code, message }; } /** Game-specific admission for explicit strategy starts; GAR owns activation mechanics. */ export async function startOwnerBehavior( runtime: StartRuntime, behavior: BehaviorStarter, request: BehaviorStartRequest, canStart: () => boolean = () => true, ): Promise { let rejection: OwnerControlResponse | undefined; const isCurrent = (): boolean => { rejection = startRejection(runtime, request); if (!rejection && !canStart()) { rejection = { ok: false, type: 'behavior_start', error: 'deferred_strategy_not_ready' }; } return rejection === undefined; }; if (!isCurrent()) return rejection!; try { const options = { source: 'agent' as const, // The existing GAR guard runs in its control queue after async preparation, // before an activation is created or an existing strategy is replaced. isCurrent, ...(request.maxRuntimeMs === undefined ? {} : { maxRuntimeMs: request.maxRuntimeMs }), }; const activation = request.layer === 'long' ? await behavior.startLong(request.behavior, request.input, options) : await behavior.startShort(request.behavior, request.input, options); return { ok: true, type: 'behavior_start', status: 'accepted', activation }; } catch (error) { return rejection ?? { ok: false, type: 'behavior_start', error: error instanceof Error ? error.message : String(error), }; } } /** One explicit short selection per game. GAR still owns actual activations. */ export class DeferredMeetingShortStrategy { private requestVersion = 0; private pending?: { request: BehaviorStartRequest; requestId: string; display: ClawclawResolvedResourceMetadata; starting: boolean; }; constructor( private readonly runtime: DeferredStartRuntime, private readonly behavior: BehaviorStarter & Pick, private readonly resolveDisplay: (request: BehaviorStartRequest) => ClawclawResolvedResourceMetadata | undefined, ) {} async start(request: BehaviorStartRequest): Promise { const rejection = startRejection(this.runtime, request); if (rejection) return rejection; const error = this.behavior.startError(request.behavior); if (error) return { ok: false, type: 'behavior_start', error }; if (request.layer !== 'short') return startOwnerBehavior(this.runtime, this.behavior, request); const version = ++this.requestVersion; const inMeeting = () => this.runtime.readState().state?.phase === 'meeting'; if (!inMeeting()) { this.pending = undefined; const result = await startOwnerBehavior(this.runtime, this.behavior, request, () => version === this.requestVersion && !inMeeting()); if (version !== this.requestVersion || result.error !== 'deferred_strategy_not_ready' || !inMeeting()) return result; const latestRejection = startRejection(this.runtime, request); if (latestRejection) return latestRejection; } try { const display = this.resolveDisplay(request); if (!display) return { ok: false, type: 'behavior_start', error: 'behavior_not_found' }; this.pending = { request: structuredClone(request), requestId: randomUUID(), display, starting: false }; return { ok: true, type: 'behavior_start', status: 'queued', pending: this.status() }; } catch (error) { return { ok: false, type: 'behavior_start', error: error instanceof Error ? error.message : String(error) }; } } status(behaviorId?: string) { const pending = this.currentPending(); if (!pending || (behaviorId && pending.request.behavior !== behaviorId)) return undefined; return { request_id: pending.requestId, behavior: pending.request.behavior, layer: 'short' as const, status: pending.starting ? 'starting' : 'waiting_for_wandering', }; } display(): ClawclawResolvedResourceMetadata | undefined { return this.currentPending()?.display; } cancel(requestId: string): boolean { if (this.currentPending()?.requestId !== requestId) return false; this.pending = undefined; return true; } afterReady(): void { const pending = this.currentPending(); if (!pending || pending.starting || this.runtime.readState().state?.phase !== 'wandering' || this.runtime.readReadyView().state.state?.phase !== 'wandering') return; pending.starting = true; void this.activate(pending).catch(error => { this.runtime.diagnostic('behavior.deferred_short.failed', { behavior_id: pending.request.behavior, error: error instanceof Error ? error.message : String(error), }, 'warn'); }); } private currentPending() { const pending = this.pending; if (!pending) return undefined; const rejection = startRejection(this.runtime, pending.request); if (rejection && rejection.code !== 'GAME_STATE_UNAVAILABLE') { this.pending = undefined; return undefined; } return pending; } private async activate(pending: NonNullable): Promise { const canStart = () => this.pending === pending && this.runtime.readState().state?.phase === 'wandering'; const result = await startOwnerBehavior(this.runtime, this.behavior, pending.request, canStart); if (this.pending !== pending) { // Cancellation or replacement can arrive while the new runner starts. const activationId = result.ok && result.activation?.activationId; if (typeof activationId === 'string') await this.behavior.cancel(activationId, 'deferred_short_superseded'); return; } if (result.error === 'deferred_strategy_not_ready' || result.code === 'GAME_STATE_UNAVAILABLE') { pending.starting = false; return; } this.pending = undefined; if (!result.ok) { this.runtime.diagnostic('behavior.deferred_short.failed', { behavior_id: pending.request.behavior, error: result.error, }, 'warn'); } } }