File size: 28,763 Bytes
4e23b01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
import { produce } from 'immer';

import { BugIndicatingError } from '#/_base/errors/errors';
import { onUnexpectedError } from '#/_base/errors/unexpectedError';
import { ILogService } from '#/_base/log/log';
import { Service } from '#/_base/di/service';
import { toDisposable, type IDisposable } from '#/_base/di/lifecycle';
import { type CollectionView } from '#/_base/di/collection';
import { LifecycleScope } from '#/app/scopes';
import { ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { AgentSpaceImpl, type AgentSpaceHost } from '#/agent/agentContext/agentSpace';
import { IAgentBlobService } from '#/agent/blob/agentBlobService';
import { IAgentScopeContext } from '#/agent/scopeContext/scopeContext';
import { IAgentStateService } from '#/agent/state/agentState';
import {
  event2FromRecord,
  type AgentDomainTrait,
  type Event2,
  type Event2Class,
} from '#/app/event/event2';
import { IEventBus } from '#/app/event/eventBus';
import type { ContentPart } from '#human/llm/message';
import { OrderedHookSlot } from '#/hooks';
import { IWireService } from '#/wire/wire';
import { WireError, WireErrors } from '#/wire/errors';
import { isHumanRecordType } from '#/wire/human';
import { AGENT_SWITCHED_TYPE } from '#/wire/tree/index';
import type { PartsTransformer } from '#/wire/record';

import {
  AgentModelContribution,
  agentModelDefinitions,
  type AgentModel,
  type AgentModelDefinition,
} from './agentModel';
import { IEventDispatcher, type DurableAgentRuntimeParticipant, type RestorePhase } from './eventDispatcher';
import { StateError, StateErrors } from './errors';
import {
  expandedModelAppliers,
  expandedRuntimeFolds,
  type EventApplier,
  type StateFold,
  type FoldContext,
  type ReplayableStateKey,
} from './state';
import {
  EventStateContribution,
  foldEventStateContributions,
  type EventStateContributionRecord,
  type FoldedEventStateRegistry,
} from './stateContribution';

const MAX_DRAIN = 100;

const UNREPORTED_WIRE_RECORD_TYPES: ReadonlySet<string> = new Set([
  'staleGuard.recorded',
  'staleGuard.cleared',
  AGENT_SWITCHED_TYPE,
  'context.undone',
]);

export class CycleError extends StateError {
  constructor(readonly depth: number, readonly eventTypes: readonly string[]) {
    super(
      StateErrors.codes.STATE_CYCLE,
      `Event dispatch cascade exceeded MAX_DRAIN (${depth}); possible event cycle`,
      { details: { depth, eventTypes: eventTypes.slice(0, 20) } },
    );
    this.name = 'CycleError';
  }
}

interface StateMeta {
  checkpoints: unknown[];
}

interface QueuedEvent {
  readonly event: Event2<any>;
  readonly resolve: () => void;
  readonly reject: (error: unknown) => void;
}

interface PreparedFold {
  readonly key: ReplayableStateKey<any>;
  readonly meta: StateMeta;
  readonly ctx: FoldContextImpl;
  readonly next: any;
}

type ParticipantApplier = (
  state: any,
  event: Event2<any>,
  ctx: FoldContextImpl,
) => unknown;

interface ParticipantAttachment {
  readonly id: string;
  readonly appliers: ReadonlyMap<Event2Class<any, any>, ParticipantApplier>;
  readonly meta: StateMeta;
  readonly undoable: boolean;
  readonly initial: unknown;
  readonly getState: () => any;
  readonly commit: (state: any) => void;
}

interface PreparedParticipant {
  readonly attachment: ParticipantAttachment;
  readonly ctx: FoldContextImpl;
  readonly next: any;
}

class FoldContextImpl implements FoldContext {
  pendingCheckpoint = false;
  pendingClear = false;
  pendingUndo: number | undefined;

  constructor(
    private readonly owner: EventDispatcherService,
    readonly silent: boolean,
  ) {}

  checkpoint(): void {
    if (!this.silent) return;
    this.pendingCheckpoint = true;
  }

  clearCheckpoints(): void {
    if (!this.silent) return;
    this.pendingClear = true;
  }

  undoToCheckpoint(count: number): void {
    if (!this.silent) return;
    this.pendingUndo = count;
  }

  emit(event: Event2<any>): void {
    if (this.silent) return;
    this.owner.enqueue(event);
  }
}

function sanitizePendingUndo(ctx: FoldContextImpl, meta: StateMeta): void {
  if (
    ctx.pendingUndo !== undefined &&
    (!Number.isSafeInteger(ctx.pendingUndo) ||
      ctx.pendingUndo <= 0 ||
      meta.checkpoints.length < ctx.pendingUndo)
  ) {
    ctx.pendingUndo = undefined;
  }
}

export class EventDispatcherService extends Service implements IEventDispatcher {
  declare readonly _serviceBrand: undefined;

  readonly hooks: IEventDispatcher['hooks'] = {
    onDidRestore: new OrderedHookSlot(),
  };

  private readonly metas = new Map<ReplayableStateKey<any>, StateMeta>();
  private folded: FoldedEventStateRegistry;

  private activeModelDefs = new Map<string, AgentModelDefinition<any, any>>();
  private readonly withdrawnModelIds = new Set<string>();
  private modelTargets = new Map<string, readonly AgentModelDefinition<any, any>[]>();
  private readonly modelAttachments = new Map<
    AgentModelDefinition<any, any>,
    ParticipantAttachment
  >();
  private readonly participantTargets = new Map<string, ParticipantAttachment[]>();
  private readonly participantAttachments = new Map<string, ParticipantAttachment>();

  private readonly spaceHost: AgentSpaceHost = {
    isActiveModelDefinition: (definition) =>
      this.activeModelDefs.get(definition.id) === definition,
    registerModel: (definition, model) => this.registerModel(definition, model),
    dispatchModelEvent: (event) => this.dispatch(event),
    readLegacyState: (key) => this.agentState.get(key),
  };

  restorePhase: RestorePhase = 'new';
  private dispatching = false;
  private disposed = false;
  private queue: QueuedEvent[] = [];
  private drainDepth = 0;
  private didRunRestoreHooks = false;
  private lateAttachments: Array<{
    readonly participant: DurableAgentRuntimeParticipant;
    readonly resolve: (disposable: IDisposable) => void;
    readonly reject: (error: unknown) => void;
  }> = [];

  constructor(
    @IWireService private readonly wire: IWireService,
    @IEventBus private readonly eventBus: IEventBus,
    @IAgentScopeContext private readonly agentScope: IAgentScopeContext | undefined,
    @IAgentBlobService private readonly blobService: IAgentBlobService,
    @IAgentStateService private readonly agentState: IAgentStateService,
    @ILogService private readonly logger: ILogService,
    @EventStateContribution view: CollectionView<EventStateContributionRecord>,
    @AgentModelContribution modelView: CollectionView<AgentModelDefinition<any, any>>,
  ) {
    super();
    this.folded = this.foldContributions(view);
    this._register(
      view.onDidChange(() => {
        this.folded = this.foldContributions(view);
      }),
    );
    this._register(
      this.agentState.onDidContributeReplayable((key) => {
        if (this.restorePhase !== 'new') {
          throw new BugIndicatingError(
            `Replayable state '${key.name}' contributed while the event dispatcher is in phase '${this.restorePhase}'; replayable state owners must contribute before restore`,
          );
        }
        this.folded = this.foldContributions(view);
      }),
    );
    this._register(
      this.agentState.onDidWithdrawReplayable((key) => {
        this.metas.delete(key);
        this.folded = this.foldContributions(view);
      }),
    );
    this.refoldModels(modelView.items);
    this._register(
      modelView.onDidChange(({ added, removed }) => {
        for (const definition of removed) {
          this.withdrawnModelIds.add(definition.id);
          const attachment = this.modelAttachments.get(definition);
          if (attachment !== undefined) {
            this.modelAttachments.delete(definition);
            this.detachParticipant(attachment);
            this.space()?.retireModel(definition);
          }
        }
        for (const definition of added) {
          this.withdrawnModelIds.delete(definition.id);
        }
        this.refoldModels(modelView.items);
        this.materializeUndoableModels();
      }),
    );
    this.space()?._attachHost(this.spaceHost);
    this.materializeUndoableModels();
  }

  private space(): AgentSpaceImpl | undefined {
    const space = this.agentScope?.agentContext.space;
    return space instanceof AgentSpaceImpl ? space : undefined;
  }

  private foldContributions(
    view: CollectionView<EventStateContributionRecord>,
  ): FoldedEventStateRegistry {
    return foldEventStateContributions(view.items, this.agentState.replayableKeys());
  }

  attach(participant: DurableAgentRuntimeParticipant): IDisposable {
    if (this.restorePhase !== 'new') {
      throw new BugIndicatingError(
        `Agent runtime participant '${participant.id}' attached while the event dispatcher is in phase '${this.restorePhase}'; durable runtime owners must attach before restore`,
      );
    }
    const attachment = this.buildParticipantAttachment(participant);
    this.attachParticipant(attachment);
    return toDisposable(() => { this.detachParticipant(attachment); });
  }

  async attachLate(participant: DurableAgentRuntimeParticipant): Promise<IDisposable> {
    if (this.restorePhase === 'restoring') {
      return new Promise<IDisposable>((resolve, reject) => {
        this.lateAttachments.push({ participant, resolve, reject });
      });
    }
    if (this.restorePhase !== 'ready') {
      throw new BugIndicatingError(
        `Agent runtime participant '${participant.id}' late-attached while the event dispatcher is in phase '${this.restorePhase}'; late attach requires a restored dispatcher`,
      );
    }
    return this.attachLateNow(participant);
  }

  private async attachLateNow(participant: DurableAgentRuntimeParticipant): Promise<IDisposable> {
    if (this.disposed) {
      throw new Error(`Agent runtime participant '${participant.id}' late-attached to a disposed event dispatcher`);
    }
    const attachment = this.buildParticipantAttachment(participant);
    this.dispatching = true;
    try {
      await this.wire.flush();
      const stream = participant.undoable
        ? this.wire.readRestorable()
        : this.wire.readJournal();
      for await (const record of stream) {
        if (record.type === 'metadata') continue;
        const cls = this.folded.events.get(record.type);
        if (cls === undefined) continue;
        let eventRecord = record;
        if (cls.agentDomain) {
          if (this.agentScope === undefined) continue;
          const recordAgentId = record['agentId'];
          if (recordAgentId === undefined) eventRecord = { ...record, agentId: this.agentScope.agentId };
          else if (recordAgentId !== this.agentScope.agentId) continue;
        }
        const event = event2FromRecord(cls, eventRecord);
        if (event === undefined) continue;
        const applier = attachment.appliers.get(event.constructor as Event2Class);
        if (applier === undefined) continue;
        const ctx = new FoldContextImpl(this, true);
        const next = produce(
          attachment.getState(),
          (draft: any) => applier(draft, event, ctx),
        );
        if (ctx.pendingUndo !== undefined && next !== attachment.getState()) {
          throw new BugIndicatingError(
            `Fold of event '${event.type}' on durable participant '${attachment.id}' both mutates and undoes to a checkpoint`,
          );
        }
        sanitizePendingUndo(ctx, attachment.meta);
        this.commitParticipant(attachment, ctx, next);
      }
      this.attachParticipant(attachment);
      this.drainQueue();
    } catch (error) {
      for (const entry of this.queue.splice(0)) entry.reject(error);
      throw error;
    } finally {
      this.queue.length = 0;
      this.dispatching = false;
      this.drainDepth = 0;
    }
    return toDisposable(() => { this.detachParticipant(attachment); });
  }

  private buildParticipantAttachment(
    participant: DurableAgentRuntimeParticipant,
  ): ParticipantAttachment {
    const base = new Map<Event2Class<any, any>, StateFold<any, any>>();
    for (const cls of participant.events) base.set(cls, participant.transition);
    const folds = expandedRuntimeFolds(participant.id, participant.undoable, base);
    const appliers = new Map<Event2Class<any, any>, ParticipantApplier>();
    for (const [cls, fold] of folds) {
      appliers.set(cls, (state, event, ctx) => fold(state, event, ctx));
    }
    return {
      id: participant.id,
      appliers,
      meta: { checkpoints: [] },
      undoable: participant.undoable,
      initial: participant.getState(),
      getState: () => participant.getState(),
      commit: (state) => { participant.commit(state); },
    };
  }

  private attachParticipant(attachment: ParticipantAttachment): void {
    if (this.participantAttachments.has(attachment.id)) {
      throw new BugIndicatingError(`Durable participant '${attachment.id}' is already attached`);
    }
    this.participantAttachments.set(attachment.id, attachment);
    for (const cls of attachment.appliers.keys()) {
      const list = this.participantTargets.get(cls.type) ?? [];
      list.push(attachment);
      this.participantTargets.set(cls.type, list);
    }
  }

  private detachParticipant(attachment: ParticipantAttachment): void {
    if (this.participantAttachments.get(attachment.id) !== attachment) return;
    this.participantAttachments.delete(attachment.id);
    for (const cls of attachment.appliers.keys()) {
      const list = this.participantTargets.get(cls.type);
      if (list === undefined) continue;
      const next = list.filter((candidate) => candidate !== attachment);
      if (next.length === 0) this.participantTargets.delete(cls.type);
      else this.participantTargets.set(cls.type, next);
    }
  }

  private refoldModels(records: readonly AgentModelDefinition<any, any>[]): void {
    const defs = new Map<string, AgentModelDefinition<any, any>>();
    for (const definition of agentModelDefinitions()) {
      if (!this.withdrawnModelIds.has(definition.id)) defs.set(definition.id, definition);
    }
    for (const definition of records) defs.set(definition.id, definition);
    this.activeModelDefs = defs;
    this.rebuildModelTargets();
  }

  private rebuildModelTargets(): void {
    const targets = new Map<string, AgentModelDefinition<any, any>[]>();
    const add = (type: string, definition: AgentModelDefinition<any, any>): void => {
      const list = targets.get(type);
      if (list === undefined) {
        targets.set(type, [definition]);
        return;
      }
      if (!list.includes(definition)) list.push(definition);
    };
    const domainOwners = new Map<string, AgentModelDefinition<any, any>>();
    for (const definition of this.activeModelDefs.values()) {
      for (const cls of definition.events) {
        const owner = domainOwners.get(cls.type);
        if (owner !== undefined && owner !== definition) {
          throw new BugIndicatingError(
            `Event '${cls.type}' is applied by both agent models '${owner.id}' and '${definition.id}'`,
          );
        }
        domainOwners.set(cls.type, definition);
        add(cls.type, definition);
      }
    }
    for (const [definition, attachment] of this.modelAttachments) {
      if (this.activeModelDefs.get(definition.id) !== definition) continue;
      for (const cls of attachment.appliers.keys()) add(cls.type, definition);
    }
    this.modelTargets = targets;
  }

  private materializeUndoableModels(): void {
    const space = this.space();
    if (space === undefined) return;
    for (const definition of this.activeModelDefs.values()) {
      if (!definition.undoable || this.modelAttachments.has(definition)) continue;
      space.ensureModel(definition);
    }
  }

  private registerModel(
    definition: AgentModelDefinition<any, any>,
    model: AgentModel<any>,
  ): void {
    if (this.modelAttachments.has(definition)) return;
    const domainAppliers = new Map<Event2Class<any, any>, EventApplier>();
    for (const [cls, applier] of model._appliersTable()) {
      domainAppliers.set(cls, (event) => applier.call(model, event));
    }
    const customUndo =
      model.onUndo === undefined ? undefined : (count: number): void => model.onUndo!(count);
    const expanded = expandedModelAppliers(
      definition.id,
      definition.undoable,
      domainAppliers,
      customUndo,
    );
    const appliers = new Map<Event2Class<any, any>, ParticipantApplier>();
    for (const [cls, applier] of expanded) {
      appliers.set(cls, (state, event, ctx) => {
        model._enterWindow(state, ctx);
        let windowResult: ReturnType<AgentModel<any>['_exitWindow']>;
        try {
          applier(event, ctx);
        } finally {
          windowResult = model._exitWindow();
        }
        return windowResult.replaced ? windowResult.replacement : undefined;
      });
    }
    const attachment: ParticipantAttachment = {
      id: definition.id,
      appliers,
      meta: { checkpoints: [] },
      undoable: definition.undoable,
      initial: model._state(),
      getState: () => model._state(),
      commit: (state) => { model._commitState(state); },
    };
    this.attachParticipant(attachment);
    this.modelAttachments.set(definition, attachment);
    this.rebuildModelTargets();
  }

  private materializeModel(definition: AgentModelDefinition<any, any>): ParticipantAttachment {
    const space = this.space();
    if (space === undefined) {
      throw new BugIndicatingError(
        `Agent model '${definition.id}' cannot materialize without an agent space`,
      );
    }
    space.ensureModel(definition);
    const attachment = this.modelAttachments.get(definition);
    if (attachment === undefined) {
      throw new BugIndicatingError(`Agent model '${definition.id}' failed to attach`);
    }
    return attachment;
  }

  dispatch(event: Event2<any>): Promise<void> {
    const cls = event.constructor as Event2Class;
    if (
      cls.agentDomain &&
      (this.agentScope === undefined ||
        (event as Event2<any> & AgentDomainTrait).agentId !== this.agentScope.agentId)
    ) {
      return Promise.reject(
        new Error(`Agent event '${event.type}' does not match dispatcher lifecycle context`),
      );
    }
    if (this.dispatching) {
      return new Promise<void>((resolve, reject) => {
        this.queue.push({ event, resolve, reject });
      });
    }
    this.dispatching = true;
    try {
      this.runDispatch(event);
      this.drainQueue();
      return Promise.resolve();
    } catch (error) {
      for (const entry of this.queue.splice(0)) {
        entry.reject(error);
      }
      return Promise.reject(error);
    } finally {
      this.queue.length = 0;
      this.dispatching = false;
      this.drainDepth = 0;
    }
  }

  private drainQueue(): void {
    while (this.queue.length > 0) {
      if (++this.drainDepth > MAX_DRAIN) {
        throw new CycleError(
          this.drainDepth,
          this.queue.map((entry) => entry.event.type),
        );
      }
      const entry = this.queue.shift()!;
      try {
        this.runDispatch(entry.event);
        entry.resolve();
      } catch (error) {
        entry.reject(error);
        throw error;
      }
    }
  }

  enqueue(event: Event2<any>): void {
    this.queue.push({
      event,
      resolve: () => {},
      reject: (error: unknown) => onUnexpectedError(error),
    });
  }

  private runDispatch(event: Event2<any>): void {
    this.executeEvent(event, false);
  }

  private executeEvent(event: Event2<any>, silent: boolean, replayUndoable?: boolean): void {
    const folds = this.folded.folds.get(event.type);
    const prepared: PreparedFold[] = [];
    if (folds !== undefined) {
      for (const { key, fold } of folds) {
        if (
          replayUndoable !== undefined &&
          (key.replayable.undoable !== undefined) !== replayUndoable
        ) {
          continue;
        }
        const meta = this.ensureMeta(key);
        const ctx = new FoldContextImpl(this, silent);
        const next = produce(
          this.agentState.get(key),
          (draft: any) => fold(draft, event, ctx),
        );
        if (ctx.pendingUndo !== undefined && next !== this.agentState.get(key)) {
          throw new BugIndicatingError(
            `Fold of event '${event.type}' on state '${key.name}' both mutates and undoes to a checkpoint`,
          );
        }
        sanitizePendingUndo(ctx, meta);
        prepared.push({ key, meta, ctx, next });
      }
    }
    const modelTargets = this.modelTargets.get(event.type);
    if (modelTargets !== undefined) {
      for (const definition of modelTargets) {
        if (replayUndoable !== undefined && definition.undoable !== replayUndoable) continue;
        if (!this.modelAttachments.has(definition)) this.materializeModel(definition);
      }
    }
    const participantTargets = this.participantTargets.get(event.type);
    const preparedParticipants: PreparedParticipant[] = [];
    if (participantTargets !== undefined) {
      for (const attachment of participantTargets) {
        if (replayUndoable !== undefined && attachment.undoable !== replayUndoable) continue;
        const applier = attachment.appliers.get(event.constructor as Event2Class);
        if (applier === undefined) continue;
        const ctx = new FoldContextImpl(this, silent);
        const next = produce(
          attachment.getState(),
          (draft: any) => applier(draft, event, ctx),
        );
        if (ctx.pendingUndo !== undefined && next !== attachment.getState()) {
          throw new BugIndicatingError(
            `Fold of event '${event.type}' on durable participant '${attachment.id}' both mutates and undoes to a checkpoint`,
          );
        }
        sanitizePendingUndo(ctx, attachment.meta);
        preparedParticipants.push({ attachment, ctx, next });
      }
    }
    for (const p of prepared) {
      this.commit(p.key, p.meta, p.ctx, p.next);
    }
    for (const p of preparedParticipants) {
      this.commitParticipant(p.attachment, p.ctx, p.next);
    }
    if (silent) return;
    const cls = event.constructor as Event2Class;
    if (cls.durable) {
      const dehydrator = folds?.find(({ key }) => key.replayable.blobs !== undefined)?.key
        .replayable.blobs?.dehydrate;
      this.wire.appendRecord(event.serialize(), dehydrator);
    }
    if (cls.observable && !this.disposed) {
      this.eventBus.publish(event, this.agentScope?.agentContext);
    }
  }

  override dispose(): void {
    this.disposed = true;
    const pending = this.lateAttachments.splice(0);
    if (pending.length > 0) {
      const error = new Error('Event dispatcher disposed while a late attach was pending');
      for (const entry of pending) entry.reject(error);
    }
    this.space()?._detachHost(this.spaceHost);
    super.dispose();
  }

  private commit(
    key: ReplayableStateKey<any>,
    meta: StateMeta,
    ctx: FoldContextImpl,
    next: any,
  ): void {
    if (ctx.pendingUndo !== undefined) {
      const targetIndex = meta.checkpoints.length - ctx.pendingUndo;
      const snapshot = meta.checkpoints[targetIndex]!;
      this.agentState.set(key, snapshot);
      meta.checkpoints.length = targetIndex;
      return;
    }
    this.agentState.set(key, next);
    if (ctx.pendingClear) {
      meta.checkpoints.length = 0;
    }
    if (ctx.pendingCheckpoint) {
      meta.checkpoints.push(next);
    }
  }

  private commitParticipant(
    attachment: ParticipantAttachment,
    ctx: FoldContextImpl,
    next: any,
  ): void {
    const meta = attachment.meta;
    if (ctx.pendingUndo !== undefined) {
      const targetIndex = meta.checkpoints.length - ctx.pendingUndo;
      const snapshot = meta.checkpoints[targetIndex]!;
      attachment.commit(snapshot);
      meta.checkpoints.length = targetIndex;
      return;
    }
    attachment.commit(next);
    if (ctx.pendingClear) {
      meta.checkpoints.length = 0;
    }
    if (ctx.pendingCheckpoint) {
      meta.checkpoints.push(next);
    }
  }

  private ensureMeta(key: ReplayableStateKey<any>): StateMeta {
    let meta = this.metas.get(key);
    if (meta === undefined) {
      meta = { checkpoints: [] };
      this.metas.set(key, meta);
    }
    return meta;
  }

  async restore(): Promise<void> {
    if (this.restorePhase === 'restoring') {
      throw new BugIndicatingError(
        `Agent state restore called while phase is ${this.restorePhase}`,
      );
    }
    const rerun = this.restorePhase !== 'new';
    this.restorePhase = 'restoring';
    if (rerun) this.dispatching = true;
    try {
      if (rerun) {
        await this.wire.flush();
        this.resetReplayState();
      }
      await this.replayRecords(true);
      await this.replayRecords(false);
      await this.rehydrateStates();
      this.restorePhase = 'ready';
      if (!this.didRunRestoreHooks) {
        await this.hooks.onDidRestore.run({});
        this.didRunRestoreHooks = true;
      }
      if (rerun) {
        this.drainQueue();
      }
      await this.drainLateAttachments();
    } catch (error) {
      this.restorePhase = 'failed';
      for (const pending of this.lateAttachments.splice(0)) pending.reject(error);
      if (rerun) {
        for (const entry of this.queue.splice(0)) entry.reject(error);
      }
      throw error;
    } finally {
      if (rerun) {
        this.queue.length = 0;
        this.dispatching = false;
        this.drainDepth = 0;
      }
    }
  }

  private async drainLateAttachments(): Promise<void> {
    for (const pending of this.lateAttachments.splice(0)) {
      try {
        pending.resolve(await this.attachLateNow(pending.participant));
      } catch (error) {
        pending.reject(error);
      }
    }
  }

  private resetReplayState(): void {
    for (const key of this.agentState.replayableKeys()) {
      this.agentState.set(key, key.initial());
    }
    for (const attachment of this.participantAttachments.values()) {
      attachment.commit(attachment.initial);
      attachment.meta.checkpoints.length = 0;
    }
    this.metas.clear();
  }

  private async replayRecords(undoable: boolean): Promise<void> {
    const stream = undoable ? this.wire.readRestorable() : this.wire.readJournal();
    let recordIndex = 0;
    for await (const record of stream) {
      if (record.type === 'metadata') continue;
      const cls = this.folded.events.get(record.type);
      if (cls === undefined) {
        if (
          !undoable &&
          !UNREPORTED_WIRE_RECORD_TYPES.has(record.type) &&
          !isHumanRecordType(record.type)
        ) {
          this.reportSkippedRecord(record.type, recordIndex, false);
        }
        recordIndex++;
        continue;
      }
      let eventRecord = record;
      if (cls.agentDomain) {
        if (this.agentScope === undefined) {
          if (!undoable) this.reportSkippedRecord(record.type, recordIndex, true);
          recordIndex++;
          continue;
        }
        const recordAgentId = record['agentId'];
        if (recordAgentId === undefined) {
          eventRecord = { ...record, agentId: this.agentScope.agentId };
        } else if (recordAgentId !== this.agentScope.agentId) {
          if (!undoable) this.reportSkippedRecord(record.type, recordIndex, true);
          recordIndex++;
          continue;
        }
      }
      const event = event2FromRecord(cls, eventRecord);
      if (event === undefined) {
        if (!undoable) this.reportSkippedRecord(record.type, recordIndex, true);
        recordIndex++;
        continue;
      }
      this.executeEvent(event, true, undoable);
      recordIndex++;
    }
  }

  private reportSkippedRecord(type: string, index: number, malformed: boolean): void {
    const message = malformed
      ? `Malformed wire record type '${type}' skipped during restore`
      : `Unknown wire record type '${type}' skipped during restore`;
    if (malformed) {
      onUnexpectedError(
        new WireError(WireErrors.codes.WIRE_UNKNOWN_RECORD, message, { details: { type, index } }),
      );
      return;
    }
    this.logger.warn(message, { code: WireErrors.codes.WIRE_UNKNOWN_RECORD, type, index });
  }

  private async rehydrateStates(): Promise<void> {
    const transform: PartsTransformer = (parts) =>
      this.blobService.loadParts(parts as readonly ContentPart[]) as Promise<readonly unknown[]>;
    for (const key of this.folded.states) {
      const codec = key.replayable.blobs;
      if (codec?.rehydrate === undefined) continue;
      this.agentState.set(key, Object.freeze(await codec.rehydrate(this.agentState.get(key), transform)));
    }
  }

  async flush(): Promise<void> {
    await this.wire.flush();
  }
}

registerScopedService(
  LifecycleScope.Agent,
  IEventDispatcher,
  EventDispatcherService,
  ScopeActivation.OnScopeCreated,
  'state',
);