@modelprofile.com/flexharness-agent 11.3.1 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,75 +3,50 @@ import type { TAgentEvent } from './smartagent.events.js';
3
3
  const SNAPSHOT_SCHEMA_VERSION = 2 as const;
4
4
  const ARCHIVE_SCHEMA_VERSION = 2 as const;
5
5
 
6
- interface IAgentEventSnapshotBase {
6
+ export interface IAgentEventSnapshot {
7
+ schemaVersion: 2;
7
8
  sessionId: string;
8
9
  revision: number;
9
10
  updatedAt: number;
10
11
  events: TAgentEvent[];
11
12
  }
12
13
 
13
- /** Legacy schema-1 snapshot contract used by IAgentEventStore. */
14
- export interface IAgentEventSnapshot extends IAgentEventSnapshotBase {
15
- schemaVersion: 1;
16
- }
17
-
18
- export interface IAgentEventSnapshotV2 extends IAgentEventSnapshotBase {
14
+ export interface IAgentEventArchive {
19
15
  schemaVersion: 2;
20
- }
21
-
22
- export type TAgentEventSnapshot = IAgentEventSnapshot | IAgentEventSnapshotV2;
23
-
24
- interface IAgentEventArchiveBase {
25
16
  sessionId: string;
26
17
  archiveId: string;
27
18
  createdAt: number;
28
19
  events: TAgentEvent[];
29
20
  }
30
21
 
31
- /** Legacy schema-1 archive contract used by IAgentEventStore. */
32
- export interface IAgentEventArchive extends IAgentEventArchiveBase {
33
- schemaVersion: 1;
34
- }
35
-
36
- export interface IAgentEventArchiveV2 extends IAgentEventArchiveBase {
37
- schemaVersion: 2;
22
+ /**
23
+ * How a session's event log changed since the store's last save. A store applies it with
24
+ * `applyAgentEventChange`: removals first, then replacements, then appends.
25
+ */
26
+ export interface IAgentEventChange {
27
+ /** IDs of stored events a context compaction archived. */
28
+ remove: string[];
29
+ /** Stored events replaced by ID, such as a provisional tool result the model's response committed. */
30
+ replace: TAgentEvent[];
31
+ /** Events committed since the last save, in order. */
32
+ append: TAgentEvent[];
38
33
  }
39
34
 
40
- export type TAgentEventArchive = IAgentEventArchive | IAgentEventArchiveV2;
41
-
42
- /** Legacy custom-store contract. It must read and write schema 1 only. */
35
+ /**
36
+ * Persists a session's event log. `save` writes a change against `expectedRevision` and returns
37
+ * the new revision; the first save of a session expects revision 0. `load` returns the whole log.
38
+ */
43
39
  export interface IAgentEventStore {
44
40
  load(sessionId: string): Promise<IAgentEventSnapshot | undefined>;
45
41
  save(
46
42
  sessionId: string,
47
- events: readonly TAgentEvent[],
43
+ change: IAgentEventChange,
48
44
  expectedRevision: number,
49
45
  ): Promise<number>;
50
46
  archive?(archive: IAgentEventArchive): Promise<void>;
51
47
  loadArchive?(sessionId: string, archiveId: string): Promise<IAgentEventArchive | undefined>;
52
48
  }
53
49
 
54
- /** Schema-2 capability required for persisted transactional generations. */
55
- export interface IAgentEventStoreV2 {
56
- readonly eventSchemaVersion: 2;
57
- load(sessionId: string): Promise<TAgentEventSnapshot | undefined>;
58
- save(
59
- sessionId: string,
60
- events: readonly TAgentEvent[],
61
- expectedRevision: number,
62
- ): Promise<number>;
63
- archive?(archive: IAgentEventArchiveV2): Promise<void>;
64
- loadArchive?(sessionId: string, archiveId: string): Promise<TAgentEventArchive | undefined>;
65
- }
66
-
67
- export type TAgentEventStore = IAgentEventStore | IAgentEventStoreV2;
68
-
69
- export const isAgentEventStoreV2 = (
70
- store: TAgentEventStore | undefined,
71
- ): store is IAgentEventStoreV2 => !!store
72
- && 'eventSchemaVersion' in store
73
- && store.eventSchemaVersion === 2;
74
-
75
50
  type TUnknownRecord = Record<string, unknown>;
76
51
 
77
52
  const AGENT_EVENT_TYPES = new Set<string>([
@@ -433,6 +408,146 @@ const assertArchivedTransactions = (value: unknown, path: string): void => {
433
408
  }
434
409
  };
435
410
 
411
+ const assertAgentEvent: (
412
+ eventValue: unknown,
413
+ eventPath: string,
414
+ conversationOnly: boolean,
415
+ ) => asserts eventValue is TUnknownRecord & { id: string; sequence?: number } = (
416
+ eventValue: unknown,
417
+ eventPath: string,
418
+ conversationOnly: boolean,
419
+ ): void => {
420
+ assertRecord(eventValue, eventPath);
421
+ assertNonEmptyString(eventValue.id, `${eventPath}.id`);
422
+ assertTimestamp(eventValue.timestamp, `${eventPath}.timestamp`);
423
+ if (eventValue.sequence !== undefined) {
424
+ assertPositiveInteger(eventValue.sequence, `${eventPath}.sequence`);
425
+ }
426
+ if (eventValue.parentIds !== undefined) {
427
+ assertStringArray(eventValue.parentIds, `${eventPath}.parentIds`);
428
+ }
429
+ for (const field of ['causationId', 'generationId', 'inferenceId'] as const) {
430
+ if (eventValue[field] !== undefined) {
431
+ assertNonEmptyString(eventValue[field], `${eventPath}.${field}`);
432
+ }
433
+ }
434
+ assertNonEmptyString(eventValue.type, `${eventPath}.type`);
435
+ if (!AGENT_EVENT_TYPES.has(eventValue.type)) validationError(`${eventPath}.type`, 'is invalid.');
436
+ if (conversationOnly && !AGENT_CONVERSATION_EVENT_TYPES.has(eventValue.type)) {
437
+ validationError(`${eventPath}.type`, 'must be a conversation event.');
438
+ }
439
+ switch (eventValue.type) {
440
+ case 'system-message':
441
+ if (!hasOwn(eventValue, 'content')) validationError(`${eventPath}.content`, 'is required.');
442
+ assertMessageContent(eventValue.content, `${eventPath}.content`, 'system');
443
+ assertProviderOptions(eventValue.providerOptions, `${eventPath}.providerOptions`);
444
+ break;
445
+ case 'user-message':
446
+ case 'assistant-message':
447
+ if (!hasOwn(eventValue, 'content')) validationError(`${eventPath}.content`, 'is required.');
448
+ assertMessageContent(eventValue.content, `${eventPath}.content`, eventValue.type === 'user-message'
449
+ ? 'user'
450
+ : 'assistant');
451
+ assertProviderOptions(eventValue.providerOptions, `${eventPath}.providerOptions`);
452
+ if (eventValue.type === 'user-message' && eventValue.inputId !== undefined) {
453
+ assertNonEmptyString(eventValue.inputId, `${eventPath}.inputId`);
454
+ }
455
+ break;
456
+ case 'tool-call':
457
+ assertNonEmptyString(eventValue.toolCallId, `${eventPath}.toolCallId`);
458
+ assertNonEmptyString(eventValue.toolName, `${eventPath}.toolName`);
459
+ if (!hasOwn(eventValue, 'input')) validationError(`${eventPath}.input`, 'is required.');
460
+ if (eventValue.providerExecuted !== undefined && typeof eventValue.providerExecuted !== 'boolean') {
461
+ validationError(`${eventPath}.providerExecuted`, 'must be a boolean when provided.');
462
+ }
463
+ assertProviderOptions(eventValue.providerOptions, `${eventPath}.providerOptions`);
464
+ break;
465
+ case 'tool-result':
466
+ assertNonEmptyString(eventValue.toolCallId, `${eventPath}.toolCallId`);
467
+ assertNonEmptyString(eventValue.toolName, `${eventPath}.toolName`);
468
+ if (eventValue.executionIntentId !== undefined) {
469
+ assertNonEmptyString(eventValue.executionIntentId, `${eventPath}.executionIntentId`);
470
+ }
471
+ assertOptionalString(eventValue.error, `${eventPath}.error`);
472
+ if (
473
+ eventValue.responseMessageCommitted !== undefined
474
+ && typeof eventValue.responseMessageCommitted !== 'boolean'
475
+ ) {
476
+ validationError(`${eventPath}.responseMessageCommitted`, 'must be a boolean when provided.');
477
+ }
478
+ if (eventValue.modelOutput !== undefined) {
479
+ assertToolResultOutput(eventValue.modelOutput, `${eventPath}.modelOutput`);
480
+ }
481
+ assertProviderOptions(eventValue.providerOptions, `${eventPath}.providerOptions`);
482
+ assertProviderOptions(eventValue.messageProviderOptions, `${eventPath}.messageProviderOptions`);
483
+ break;
484
+ case 'runtime-event':
485
+ assertRecord(eventValue.event, `${eventPath}.event`);
486
+ assertNonEmptyString(eventValue.event.type, `${eventPath}.event.type`);
487
+ if (eventValue.modelVisible !== undefined && typeof eventValue.modelVisible !== 'boolean') {
488
+ validationError(`${eventPath}.modelVisible`, 'must be a boolean when provided.');
489
+ }
490
+ break;
491
+ case 'model-message':
492
+ assertModelMessage(eventValue.message, `${eventPath}.message`);
493
+ break;
494
+ case 'generation-begun':
495
+ assertRequiredGenerationId(eventValue, eventPath);
496
+ assertNonEmptyString(eventValue.claimTokenDigest, `${eventPath}.claimTokenDigest`);
497
+ break;
498
+ case 'generation-execution-started':
499
+ case 'generation-execution-completed':
500
+ assertRequiredGenerationId(eventValue, eventPath);
501
+ break;
502
+ case 'generation-outcome':
503
+ assertRequiredGenerationId(eventValue, eventPath);
504
+ if (
505
+ eventValue.outcome !== 'accepted'
506
+ && eventValue.outcome !== 'rejected'
507
+ && eventValue.outcome !== 'interrupted'
508
+ ) validationError(`${eventPath}.outcome`, 'is invalid.');
509
+ assertOptionalString(eventValue.reason, `${eventPath}.reason`);
510
+ if (eventValue.stopped !== undefined && (
511
+ eventValue.stopped !== true || eventValue.outcome !== 'interrupted'
512
+ )) validationError(`${eventPath}.stopped`, 'is only valid as true on an interrupted outcome.');
513
+ break;
514
+ case 'tool-execution-intent':
515
+ assertRequiredGenerationId(eventValue, eventPath);
516
+ assertNonEmptyString(eventValue.toolCallId, `${eventPath}.toolCallId`);
517
+ assertNonEmptyString(eventValue.toolName, `${eventPath}.toolName`);
518
+ if (!hasOwn(eventValue, 'input')) validationError(`${eventPath}.input`, 'is required.');
519
+ break;
520
+ case 'tool-execution-reconciliation':
521
+ assertRequiredGenerationId(eventValue, eventPath);
522
+ assertNonEmptyString(eventValue.intentId, `${eventPath}.intentId`);
523
+ assertNonEmptyString(eventValue.toolCallId, `${eventPath}.toolCallId`);
524
+ assertNonEmptyString(eventValue.toolName, `${eventPath}.toolName`);
525
+ if (
526
+ eventValue.resolution !== 'executed'
527
+ && eventValue.resolution !== 'not-executed'
528
+ && eventValue.resolution !== 'abandoned-unknown'
529
+ ) validationError(`${eventPath}.resolution`, 'is invalid.');
530
+ assertOptionalString(eventValue.error, `${eventPath}.error`);
531
+ if (eventValue.modelOutput !== undefined) {
532
+ assertToolResultOutput(eventValue.modelOutput, `${eventPath}.modelOutput`);
533
+ }
534
+ break;
535
+ case 'context-compaction':
536
+ if (eventValue.automatic !== undefined && eventValue.automatic !== true) {
537
+ validationError(`${eventPath}.automatic`, 'must be true when present.');
538
+ }
539
+ assertStringArray(eventValue.coveredEventIds, `${eventPath}.coveredEventIds`);
540
+ validateAgentEvents(eventValue.replacementEvents, `${eventPath}.replacementEvents`, true);
541
+ if (eventValue.archivedTransactions !== undefined) {
542
+ assertArchivedTransactions(
543
+ eventValue.archivedTransactions,
544
+ `${eventPath}.archivedTransactions`,
545
+ );
546
+ }
547
+ break;
548
+ }
549
+ };
550
+
436
551
  const validateAgentEvents = (
437
552
  value: unknown,
438
553
  path: string,
@@ -443,150 +558,24 @@ const validateAgentEvents = (
443
558
  let priorSequence = 0;
444
559
  for (const [index, eventValue] of value.entries()) {
445
560
  const eventPath = `${path}[${index}]`;
446
- assertRecord(eventValue, eventPath);
447
- assertNonEmptyString(eventValue.id, `${eventPath}.id`);
561
+ assertAgentEvent(eventValue, eventPath, conversationOnly);
448
562
  if (eventIds.has(eventValue.id)) validationError(path, 'must not contain duplicate event IDs.');
449
563
  eventIds.add(eventValue.id);
450
- assertTimestamp(eventValue.timestamp, `${eventPath}.timestamp`);
451
564
  if (eventValue.sequence !== undefined) {
452
- assertPositiveInteger(eventValue.sequence, `${eventPath}.sequence`);
453
565
  if (eventValue.sequence <= priorSequence) {
454
566
  validationError(`${eventPath}.sequence`, 'must be strictly monotonic.');
455
567
  }
456
568
  priorSequence = eventValue.sequence;
457
569
  }
458
- if (eventValue.parentIds !== undefined) {
459
- assertStringArray(eventValue.parentIds, `${eventPath}.parentIds`);
460
- }
461
- for (const field of ['causationId', 'generationId', 'inferenceId'] as const) {
462
- if (eventValue[field] !== undefined) {
463
- assertNonEmptyString(eventValue[field], `${eventPath}.${field}`);
464
- }
465
- }
466
- assertNonEmptyString(eventValue.type, `${eventPath}.type`);
467
- if (!AGENT_EVENT_TYPES.has(eventValue.type)) validationError(`${eventPath}.type`, 'is invalid.');
468
- if (conversationOnly && !AGENT_CONVERSATION_EVENT_TYPES.has(eventValue.type)) {
469
- validationError(`${eventPath}.type`, 'must be a conversation event.');
470
- }
471
- switch (eventValue.type) {
472
- case 'system-message':
473
- if (!hasOwn(eventValue, 'content')) validationError(`${eventPath}.content`, 'is required.');
474
- assertMessageContent(eventValue.content, `${eventPath}.content`, 'system');
475
- assertProviderOptions(eventValue.providerOptions, `${eventPath}.providerOptions`);
476
- break;
477
- case 'user-message':
478
- case 'assistant-message':
479
- if (!hasOwn(eventValue, 'content')) validationError(`${eventPath}.content`, 'is required.');
480
- assertMessageContent(eventValue.content, `${eventPath}.content`, eventValue.type === 'user-message'
481
- ? 'user'
482
- : 'assistant');
483
- assertProviderOptions(eventValue.providerOptions, `${eventPath}.providerOptions`);
484
- if (eventValue.type === 'user-message' && eventValue.inputId !== undefined) {
485
- assertNonEmptyString(eventValue.inputId, `${eventPath}.inputId`);
486
- }
487
- break;
488
- case 'tool-call':
489
- assertNonEmptyString(eventValue.toolCallId, `${eventPath}.toolCallId`);
490
- assertNonEmptyString(eventValue.toolName, `${eventPath}.toolName`);
491
- if (!hasOwn(eventValue, 'input')) validationError(`${eventPath}.input`, 'is required.');
492
- if (eventValue.providerExecuted !== undefined && typeof eventValue.providerExecuted !== 'boolean') {
493
- validationError(`${eventPath}.providerExecuted`, 'must be a boolean when provided.');
494
- }
495
- assertProviderOptions(eventValue.providerOptions, `${eventPath}.providerOptions`);
496
- break;
497
- case 'tool-result':
498
- assertNonEmptyString(eventValue.toolCallId, `${eventPath}.toolCallId`);
499
- assertNonEmptyString(eventValue.toolName, `${eventPath}.toolName`);
500
- if (eventValue.executionIntentId !== undefined) {
501
- assertNonEmptyString(eventValue.executionIntentId, `${eventPath}.executionIntentId`);
502
- }
503
- assertOptionalString(eventValue.error, `${eventPath}.error`);
504
- if (
505
- eventValue.responseMessageCommitted !== undefined
506
- && typeof eventValue.responseMessageCommitted !== 'boolean'
507
- ) {
508
- validationError(`${eventPath}.responseMessageCommitted`, 'must be a boolean when provided.');
509
- }
510
- if (eventValue.modelOutput !== undefined) {
511
- assertToolResultOutput(eventValue.modelOutput, `${eventPath}.modelOutput`);
512
- }
513
- assertProviderOptions(eventValue.providerOptions, `${eventPath}.providerOptions`);
514
- assertProviderOptions(eventValue.messageProviderOptions, `${eventPath}.messageProviderOptions`);
515
- break;
516
- case 'runtime-event':
517
- assertRecord(eventValue.event, `${eventPath}.event`);
518
- assertNonEmptyString(eventValue.event.type, `${eventPath}.event.type`);
519
- if (eventValue.modelVisible !== undefined && typeof eventValue.modelVisible !== 'boolean') {
520
- validationError(`${eventPath}.modelVisible`, 'must be a boolean when provided.');
521
- }
522
- break;
523
- case 'model-message':
524
- assertModelMessage(eventValue.message, `${eventPath}.message`);
525
- break;
526
- case 'generation-begun':
527
- assertRequiredGenerationId(eventValue, eventPath);
528
- assertNonEmptyString(eventValue.claimTokenDigest, `${eventPath}.claimTokenDigest`);
529
- break;
530
- case 'generation-execution-started':
531
- case 'generation-execution-completed':
532
- assertRequiredGenerationId(eventValue, eventPath);
533
- break;
534
- case 'generation-outcome':
535
- assertRequiredGenerationId(eventValue, eventPath);
536
- if (
537
- eventValue.outcome !== 'accepted'
538
- && eventValue.outcome !== 'rejected'
539
- && eventValue.outcome !== 'interrupted'
540
- ) validationError(`${eventPath}.outcome`, 'is invalid.');
541
- assertOptionalString(eventValue.reason, `${eventPath}.reason`);
542
- if (eventValue.stopped !== undefined && (
543
- eventValue.stopped !== true || eventValue.outcome !== 'interrupted'
544
- )) validationError(`${eventPath}.stopped`, 'is only valid as true on an interrupted outcome.');
545
- break;
546
- case 'tool-execution-intent':
547
- assertRequiredGenerationId(eventValue, eventPath);
548
- assertNonEmptyString(eventValue.toolCallId, `${eventPath}.toolCallId`);
549
- assertNonEmptyString(eventValue.toolName, `${eventPath}.toolName`);
550
- if (!hasOwn(eventValue, 'input')) validationError(`${eventPath}.input`, 'is required.');
551
- break;
552
- case 'tool-execution-reconciliation':
553
- assertRequiredGenerationId(eventValue, eventPath);
554
- assertNonEmptyString(eventValue.intentId, `${eventPath}.intentId`);
555
- assertNonEmptyString(eventValue.toolCallId, `${eventPath}.toolCallId`);
556
- assertNonEmptyString(eventValue.toolName, `${eventPath}.toolName`);
557
- if (
558
- eventValue.resolution !== 'executed'
559
- && eventValue.resolution !== 'not-executed'
560
- && eventValue.resolution !== 'abandoned-unknown'
561
- ) validationError(`${eventPath}.resolution`, 'is invalid.');
562
- assertOptionalString(eventValue.error, `${eventPath}.error`);
563
- if (eventValue.modelOutput !== undefined) {
564
- assertToolResultOutput(eventValue.modelOutput, `${eventPath}.modelOutput`);
565
- }
566
- break;
567
- case 'context-compaction':
568
- if (eventValue.automatic !== undefined && eventValue.automatic !== true) {
569
- validationError(`${eventPath}.automatic`, 'must be true when present.');
570
- }
571
- assertStringArray(eventValue.coveredEventIds, `${eventPath}.coveredEventIds`);
572
- validateAgentEvents(eventValue.replacementEvents, `${eventPath}.replacementEvents`, true);
573
- if (eventValue.archivedTransactions !== undefined) {
574
- assertArchivedTransactions(
575
- eventValue.archivedTransactions,
576
- `${eventPath}.archivedTransactions`,
577
- );
578
- }
579
- break;
580
- }
581
570
  }
582
571
  return value as TAgentEvent[];
583
572
  };
584
573
 
585
- /** Validates and returns a canonical schema-2 Agent event snapshot. */
586
- export const validateAgentEventSnapshotV2 = (
574
+ /** Validates and returns a canonical Agent event snapshot. */
575
+ export const validateAgentEventSnapshot = (
587
576
  value: unknown,
588
577
  expectedSessionId?: string,
589
- ): IAgentEventSnapshotV2 => {
578
+ ): IAgentEventSnapshot => {
590
579
  assertRecord(value, 'Agent event snapshot');
591
580
  if (value.schemaVersion !== SNAPSHOT_SCHEMA_VERSION) {
592
581
  validationError('Agent event snapshot schemaVersion', 'must be 2.');
@@ -598,15 +587,15 @@ export const validateAgentEventSnapshotV2 = (
598
587
  assertPositiveInteger(value.revision, 'Agent event snapshot revision');
599
588
  assertTimestamp(value.updatedAt, 'Agent event snapshot updatedAt');
600
589
  validateAgentEvents(value.events, 'Agent event snapshot events');
601
- return value as unknown as IAgentEventSnapshotV2;
590
+ return value as unknown as IAgentEventSnapshot;
602
591
  };
603
592
 
604
- /** Validates and returns a canonical schema-2 Agent event archive. */
605
- export const validateAgentEventArchiveV2 = (
593
+ /** Validates and returns a canonical Agent event archive. */
594
+ export const validateAgentEventArchive = (
606
595
  value: unknown,
607
596
  expectedSessionId?: string,
608
597
  expectedArchiveId?: string,
609
- ): IAgentEventArchiveV2 => {
598
+ ): IAgentEventArchive => {
610
599
  assertRecord(value, 'Agent event archive');
611
600
  if (value.schemaVersion !== ARCHIVE_SCHEMA_VERSION) {
612
601
  validationError('Agent event archive schemaVersion', 'must be 2.');
@@ -621,7 +610,80 @@ export const validateAgentEventArchiveV2 = (
621
610
  }
622
611
  assertTimestamp(value.createdAt, 'Agent event archive createdAt');
623
612
  validateAgentEvents(value.events, 'Agent event archive events');
624
- return value as unknown as IAgentEventArchiveV2;
613
+ return value as unknown as IAgentEventArchive;
614
+ };
615
+
616
+ const CHANGE_KEYS = new Set(['remove', 'replace', 'append']);
617
+
618
+ /**
619
+ * Checks the shape of an event-log change: valid events, and no event ID twice across its lists.
620
+ * It does not compare the change with a stored log; `applyAgentEventChange` does.
621
+ */
622
+ export const assertAgentEventChange: (
623
+ value: unknown,
624
+ ) => asserts value is IAgentEventChange = (value: unknown): void => {
625
+ const path = 'Agent event change';
626
+ assertRecord(value, path);
627
+ const unknownKey = Object.keys(value).find((key) => !CHANGE_KEYS.has(key));
628
+ if (unknownKey !== undefined) validationError(`${path} ${unknownKey}`, 'is not supported.');
629
+ assertStringArray(value.remove, `${path} remove`);
630
+ const eventIds = new Set<string>(value.remove);
631
+ if (!Array.isArray(value.replace)) validationError(`${path} replace`, 'must be an array.');
632
+ for (const [index, event] of (value.replace as unknown[]).entries()) {
633
+ assertAgentEvent(event, `${path} replace[${index}]`, false);
634
+ if (eventIds.has(event.id)) validationError(`${path} replace[${index}].id`, 'is already in the change.');
635
+ eventIds.add(event.id);
636
+ }
637
+ for (const [index, event] of validateAgentEvents(value.append, `${path} append`).entries()) {
638
+ if (eventIds.has(event.id)) validationError(`${path} append[${index}].id`, 'is already in the change.');
639
+ }
640
+ };
641
+
642
+ /**
643
+ * Applies `change` to a stored event log and returns the new log; neither input is modified. It
644
+ * rejects a change that does not fit the log: a removed or replaced ID the log lacks, a
645
+ * replacement of another type or sequence, or an appended sequence that does not follow the
646
+ * log's last one. The change's shape is `assertAgentEventChange`'s to check; an appended ID the
647
+ * log already holds is left to the snapshot validation.
648
+ */
649
+ export const applyAgentEventChange = (
650
+ events: readonly TAgentEvent[],
651
+ change: IAgentEventChange,
652
+ ): TAgentEvent[] => {
653
+ const path = 'Agent event change';
654
+ let next: TAgentEvent[];
655
+ if (change.remove.length > 0) {
656
+ const removed = new Set(change.remove);
657
+ next = events.filter((event) => !removed.has(event.id));
658
+ if (events.length - next.length !== removed.size) {
659
+ const missingId = change.remove.find((id) => !events.some((event) => event.id === id));
660
+ validationError(`${path} remove`, `names "${missingId}", which is not stored.`);
661
+ }
662
+ } else {
663
+ next = events.slice();
664
+ }
665
+ for (const replacement of change.replace) {
666
+ let index = next.length - 1;
667
+ while (index >= 0 && next[index].id !== replacement.id) index--;
668
+ if (index < 0) validationError(`${path} replace`, `names "${replacement.id}", which is not stored.`);
669
+ const stored = next[index];
670
+ if (stored.type !== replacement.type || stored.sequence !== replacement.sequence) {
671
+ validationError(`${path} replace`, `must keep the type and sequence of "${replacement.id}".`);
672
+ }
673
+ next[index] = replacement;
674
+ }
675
+ if (change.append.length > 0) {
676
+ let lastSequence = 0;
677
+ for (let index = next.length - 1; index >= 0 && !lastSequence; index--) {
678
+ lastSequence = next[index].sequence ?? 0;
679
+ }
680
+ const firstSequence = change.append.find((event) => event.sequence !== undefined)?.sequence;
681
+ if (firstSequence !== undefined && firstSequence <= lastSequence) {
682
+ validationError(`${path} append`, `must follow the stored sequence ${lastSequence}.`);
683
+ }
684
+ for (const event of change.append) next.push(event);
685
+ }
686
+ return next;
625
687
  };
626
688
 
627
689
  export class AgentEventStoreConflictError extends Error {
@@ -642,43 +704,47 @@ export class AgentEventStoreConflictError extends Error {
642
704
 
643
705
  export const clone = <TValue>(value: TValue): TValue => structuredClone(value);
644
706
 
645
- export const createSnapshot = (
707
+ /** The snapshot `change` makes of `current`, validated in full. The change is cloned first. */
708
+ export const createChangedSnapshot = (
646
709
  sessionId: string,
647
- revision: number,
648
- events: readonly TAgentEvent[],
649
- ): IAgentEventSnapshotV2 => ({
650
- schemaVersion: SNAPSHOT_SCHEMA_VERSION,
651
- sessionId,
652
- revision,
653
- updatedAt: Date.now(),
654
- events: clone([...events]),
655
- });
656
-
657
- export class InMemoryAgentEventStore implements IAgentEventStoreV2 {
658
- public readonly eventSchemaVersion = 2 as const;
659
- private readonly snapshots = new Map<string, TAgentEventSnapshot>();
660
- private readonly archives = new Map<string, TAgentEventArchive>();
661
-
662
- public async load(sessionId: string): Promise<TAgentEventSnapshot | undefined> {
710
+ current: IAgentEventSnapshot | undefined,
711
+ change: IAgentEventChange,
712
+ ): IAgentEventSnapshot => {
713
+ assertAgentEventChange(change);
714
+ return validateAgentEventSnapshot({
715
+ schemaVersion: SNAPSHOT_SCHEMA_VERSION,
716
+ sessionId,
717
+ revision: (current?.revision ?? 0) + 1,
718
+ updatedAt: Date.now(),
719
+ events: applyAgentEventChange(current?.events ?? [], clone(change)),
720
+ }, sessionId);
721
+ };
722
+
723
+ export class InMemoryAgentEventStore implements IAgentEventStore {
724
+ private readonly snapshots = new Map<string, IAgentEventSnapshot>();
725
+ private readonly archives = new Map<string, IAgentEventArchive>();
726
+
727
+ public async load(sessionId: string): Promise<IAgentEventSnapshot | undefined> {
663
728
  const snapshot = this.snapshots.get(sessionId);
664
729
  return snapshot ? clone(snapshot) : undefined;
665
730
  }
666
731
 
667
732
  public async save(
668
733
  sessionId: string,
669
- events: readonly TAgentEvent[],
734
+ change: IAgentEventChange,
670
735
  expectedRevision: number,
671
736
  ): Promise<number> {
672
- const actualRevision = this.snapshots.get(sessionId)?.revision ?? 0;
737
+ const current = this.snapshots.get(sessionId);
738
+ const actualRevision = current?.revision ?? 0;
673
739
  if (actualRevision !== expectedRevision) {
674
740
  throw new AgentEventStoreConflictError(sessionId, expectedRevision, actualRevision);
675
741
  }
676
- const revision = expectedRevision + 1;
677
- this.snapshots.set(sessionId, createSnapshot(sessionId, revision, events));
678
- return revision;
742
+ const snapshot = createChangedSnapshot(sessionId, current, change);
743
+ this.snapshots.set(sessionId, snapshot);
744
+ return snapshot.revision;
679
745
  }
680
746
 
681
- public async archive(archive: IAgentEventArchiveV2): Promise<void> {
747
+ public async archive(archive: IAgentEventArchive): Promise<void> {
682
748
  const nextArchive = clone(archive);
683
749
  const key = `${archive.sessionId}\n${archive.archiveId}`;
684
750
  const existing = this.archives.get(key);
@@ -696,7 +762,7 @@ export class InMemoryAgentEventStore implements IAgentEventStoreV2 {
696
762
  public async loadArchive(
697
763
  sessionId: string,
698
764
  archiveId: string,
699
- ): Promise<TAgentEventArchive | undefined> {
765
+ ): Promise<IAgentEventArchive | undefined> {
700
766
  const archive = this.archives.get(`${sessionId}\n${archiveId}`);
701
767
  return archive ? clone(archive) : undefined;
702
768
  }