@itphx/synth-shared 0.9.0 → 0.10.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.
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { MessageRole, GlobalRole, ProjectRole, StatusMessageType, PROJECT_ICON_KEYS, PROJECT_COLOR_KEYS, } from '../types/index.js';
2
+ import { MessageRole, GlobalRole, ProjectRole, StatusMessageType, PROJECT_ICON_KEYS, PROJECT_COLOR_KEYS, isKnownScope, isWebhookEventPattern, } from '../types/index.js';
3
3
  import { ToolCapability } from '../types/tools.js';
4
4
  export const messageRoleSchema = z.nativeEnum(MessageRole);
5
5
  export const globalRoleSchema = z.nativeEnum(GlobalRole);
@@ -66,6 +66,9 @@ export const sessionSettingsSchema = z.object({
66
66
  // === Скиллы (AD-046 §4.5) ===
67
67
  skills: z.array(z.string()).optional(),
68
68
  skillsDisabled: z.array(z.string()).optional(),
69
+ // === Микро-слой (AD-035/AD-084) ===
70
+ /** AD-084: per-session гейт decision-уровня микро-каскада (undefined → config.decision.enabled). */
71
+ decisionFirst: z.boolean().optional(),
69
72
  });
70
73
  export const sessionCreateSchema = z.object({
71
74
  name: z.string().min(1).max(200).optional(),
@@ -418,3 +421,374 @@ export const projectSkillUpdateSchema = z.object({
418
421
  enabled: z.array(z.string()).optional(),
419
422
  defaultOn: z.array(z.string()).optional(),
420
423
  });
424
+ // --- Внешние события (AD-089) ---
425
+ /** AD-089: схема идентичности отправителя внешнего события. */
426
+ export const eventIdentitySchema = z.object({
427
+ principalId: z.string().optional(),
428
+ chatKey: z.string().optional(),
429
+ threadKey: z.string().optional(),
430
+ roles: z.array(z.string()).optional(),
431
+ });
432
+ /** AD-089: схема нормализованного внешнего события (`payload` не типизируется). */
433
+ export const synthEventSchema = z.object({
434
+ id: z.string().min(1),
435
+ source: z.string().min(1),
436
+ type: z.string().min(1),
437
+ payload: z.unknown(),
438
+ identity: eventIdentitySchema.default({}),
439
+ dedupKey: z.string().min(1),
440
+ ts: z.string().min(1),
441
+ });
442
+ /** AD-089: режимы доставки `EventBinding` (без `drop`). */
443
+ const eventDeliveryModeSchema = z.enum(['bound', 'ephemeral', 'queue']);
444
+ /** AD-089: схема устойчивой привязки внешнего адреса к сессии/шаблону. */
445
+ export const eventBindingSchema = z.object({
446
+ id: z.string().min(1),
447
+ source: z.string().min(1),
448
+ chatKey: z.string().optional(),
449
+ threadKey: z.string().optional(),
450
+ sessionId: z.string().optional(),
451
+ mode: eventDeliveryModeSchema,
452
+ agentTemplate: z.string().optional(),
453
+ project: z.string().optional(),
454
+ });
455
+ /** AD-089: схема запроса создания/привязки сессии — единый funnel. */
456
+ export const sessionRequestSchema = z.object({
457
+ initiator: z.enum(['user', 'agent', 'external', 'system']),
458
+ intent: z.enum(['explicit', 'event']),
459
+ projectId: z.string().optional(),
460
+ parentId: z.string().optional(),
461
+ agentTemplate: z.string().optional(),
462
+ mode: eventDeliveryModeSchema.optional(),
463
+ ttl: z.string().optional(),
464
+ title: z.string().optional(),
465
+ icon: projectIconKeySchema.optional(),
466
+ color: projectColorKeySchema.optional(),
467
+ engine: z.enum(['synth', 'opencode', 'cline']).optional(),
468
+ sessionOrigin: z.enum(['user', 'fork', 'subagent']).optional(),
469
+ // Настройки сессии валидируются собственной схемой при создании; здесь —
470
+ // толерантный контейнер, чтобы не дублировать SessionSettings.
471
+ settings: z.unknown().optional(),
472
+ sourceEventId: z.string().optional(),
473
+ dedupKey: z.string().optional(),
474
+ });
475
+ /**
476
+ * AD-089: вход приёма внешнего события (`POST /api/v2/events`). `id`/`dedupKey`/`ts`
477
+ * нормализуются `EventIngress`, поэтому здесь опциональны.
478
+ */
479
+ export const eventIngestSchema = z.object({
480
+ source: z.string().min(1),
481
+ type: z.string().min(1),
482
+ payload: z.unknown().optional(),
483
+ identity: eventIdentitySchema.optional(),
484
+ dedupKey: z.string().optional(),
485
+ ts: z.string().optional(),
486
+ });
487
+ /** AD-089: вход upsert биндинга (`POST /api/v2/events/bindings`) — без `id`. */
488
+ export const eventBindingInputSchema = z.object({
489
+ source: z.string().min(1),
490
+ chatKey: z.string().optional(),
491
+ threadKey: z.string().optional(),
492
+ sessionId: z.string().optional(),
493
+ mode: eventDeliveryModeSchema,
494
+ agentTemplate: z.string().optional(),
495
+ project: z.string().optional(),
496
+ });
497
+ /**
498
+ * AD-089/AD-052: метаданные API-ключа привязки для приёма событий.
499
+ * Секрет (`key`) и его хеш здесь отсутствуют — наружу не отдаются.
500
+ */
501
+ export const eventBindingApiKeySchema = z.object({
502
+ id: z.string().min(1),
503
+ bindingId: z.string().min(1),
504
+ label: z.string().min(1),
505
+ description: z.string().optional(),
506
+ rateLimitPerMinute: z.number().int().min(0).optional(),
507
+ createdBy: z.string().min(1),
508
+ createdAt: z.string().min(1),
509
+ lastUsedAt: z.string().optional(),
510
+ prefix: z.string().min(1),
511
+ // AD-052 (задел): срок действия / отзыв ключа.
512
+ expiresAt: z.string().optional(),
513
+ revokedAt: z.string().optional(),
514
+ });
515
+ /** AD-089/AD-052: тело создания API-ключа привязки — обязательная уникальная `label`. */
516
+ export const eventBindingApiKeyCreateSchema = z.object({
517
+ label: z.string().min(1),
518
+ description: z.string().optional(),
519
+ expiresAt: z.string().optional(),
520
+ rateLimitPerMinute: z.number().int().min(0).optional(),
521
+ });
522
+ /**
523
+ * AD-089/AD-052: тело обновления API-ключа привязки. Все поля опциональны;
524
+ * `null` для `description`/`expiresAt`/`rateLimitPerMinute` — сброс значения.
525
+ */
526
+ export const eventBindingApiKeyUpdateSchema = z.object({
527
+ label: z.string().min(1).optional(),
528
+ description: z.string().nullable().optional(),
529
+ expiresAt: z.string().nullable().optional(),
530
+ rateLimitPerMinute: z.number().int().min(0).nullable().optional(),
531
+ });
532
+ /** AD-089: ответ создания ключа — метаданные + plaintext-секрет (единожды). */
533
+ export const eventBindingApiKeyCreatedSchema = eventBindingApiKeySchema.extend({
534
+ key: z.string().min(1),
535
+ });
536
+ /**
537
+ * AD-089: вход `POST /events` при аутентификации API-ключом привязки. Как
538
+ * `eventIngestSchema`, но `source` опционален — источник берётся из привязки.
539
+ */
540
+ export const eventKeyIngestSchema = eventIngestSchema.partial({ source: true });
541
+ // --- Service-key (AD-052, этап I) ---
542
+ /**
543
+ * AD-052: каталог скоупов service-key + wildcard-семейства. Глобальный `*` не
544
+ * принимается (`isKnownScope`).
545
+ */
546
+ export const serviceScopeSchema = z
547
+ .string()
548
+ .min(1)
549
+ .refine((value) => isKnownScope(value), { message: 'Неизвестный scope' });
550
+ const serviceScopesSchema = z.array(serviceScopeSchema).min(1);
551
+ /**
552
+ * AD-052: метаданные service-key (ответы API). Секрет (`key`) и его хеш здесь
553
+ * отсутствуют — наружу не отдаются (в списке — `prefix`).
554
+ */
555
+ export const serviceApiKeySchema = z.object({
556
+ id: z.string().min(1),
557
+ label: z.string().min(1),
558
+ description: z.string().optional(),
559
+ roles: z.array(globalRoleSchema),
560
+ scopes: z.array(z.string().min(1)),
561
+ allowedProjects: z.array(z.string().min(1)).optional(),
562
+ rateLimitPerMinute: z.number().int().min(0).optional(),
563
+ expiresAt: z.string().optional(),
564
+ revokedAt: z.string().optional(),
565
+ createdBy: z.string().min(1),
566
+ createdAt: z.string().min(1),
567
+ lastUsedAt: z.string().optional(),
568
+ prefix: z.string().min(1),
569
+ });
570
+ /** AD-052: тело создания service-key. `roles` не заданы — дефолт хранилища. */
571
+ export const serviceApiKeyCreateSchema = z.object({
572
+ label: z.string().min(1),
573
+ description: z.string().optional(),
574
+ roles: z.array(globalRoleSchema).optional(),
575
+ scopes: serviceScopesSchema,
576
+ allowedProjects: z.array(z.string().min(1)).optional(),
577
+ rateLimitPerMinute: z.number().int().min(0).optional(),
578
+ expiresAt: z.string().optional(),
579
+ });
580
+ /**
581
+ * AD-052: тело обновления service-key. Все поля опциональны; `null` для
582
+ * `description`/`allowedProjects`/`rateLimitPerMinute`/`expiresAt` — сброс.
583
+ */
584
+ export const serviceApiKeyUpdateSchema = z.object({
585
+ label: z.string().min(1).optional(),
586
+ description: z.string().nullable().optional(),
587
+ roles: z.array(globalRoleSchema).optional(),
588
+ scopes: serviceScopesSchema.optional(),
589
+ allowedProjects: z.array(z.string().min(1)).nullable().optional(),
590
+ rateLimitPerMinute: z.number().int().min(0).nullable().optional(),
591
+ expiresAt: z.string().nullable().optional(),
592
+ });
593
+ /** AD-052: ответ создания service-key — метаданные + plaintext-секрет (единожды). */
594
+ export const serviceApiKeyCreatedSchema = serviceApiKeySchema.extend({
595
+ key: z.string().min(1),
596
+ });
597
+ // --- Webhooks (AD-052, этап II) ---
598
+ /** AD-052 (этап II): паттерн события подписки — exact либо `prefix.*`. */
599
+ export const webhookEventPatternSchema = z
600
+ .string()
601
+ .min(1)
602
+ .refine((value) => isWebhookEventPattern(value), { message: 'Некорректный паттерн события' });
603
+ /** AD-052 (этап II): целевой URL — только http/https (SSRF-политика — в core). */
604
+ export const webhookUrlSchema = z
605
+ .string()
606
+ .url()
607
+ .refine((value) => /^https?:\/\//i.test(value), { message: 'URL должен быть http(s)' });
608
+ /**
609
+ * AD-052 (этап II): метаданные подписки (ответы API). Секрет (`secret`) и его
610
+ * хеш здесь отсутствуют — наружу не отдаются (в списке — `secretPrefix`).
611
+ */
612
+ export const webhookSubscriptionSchema = z.object({
613
+ id: z.string().min(1),
614
+ label: z.string().min(1),
615
+ description: z.string().optional(),
616
+ url: webhookUrlSchema,
617
+ events: z.array(webhookEventPatternSchema),
618
+ enabled: z.boolean(),
619
+ secretPrefix: z.string().min(1),
620
+ createdBy: z.string().min(1),
621
+ createdAt: z.string().min(1),
622
+ lastDeliveryAt: z.string().optional(),
623
+ lastStatus: z.enum(['ok', 'failed']).optional(),
624
+ disabledAt: z.string().optional(),
625
+ });
626
+ /** AD-052 (этап II): тело создания подписки. `enabled` не задан — активна. */
627
+ export const webhookSubscriptionCreateSchema = z.object({
628
+ label: z.string().min(1),
629
+ description: z.string().optional(),
630
+ url: webhookUrlSchema,
631
+ events: z.array(webhookEventPatternSchema).optional(),
632
+ enabled: z.boolean().optional(),
633
+ });
634
+ /**
635
+ * AD-052 (этап II): тело обновления подписки. Все поля опциональны; `null` для
636
+ * `description` — сброс.
637
+ */
638
+ export const webhookSubscriptionUpdateSchema = z.object({
639
+ label: z.string().min(1).optional(),
640
+ description: z.string().nullable().optional(),
641
+ url: webhookUrlSchema.optional(),
642
+ events: z.array(webhookEventPatternSchema).optional(),
643
+ enabled: z.boolean().optional(),
644
+ });
645
+ /** AD-052 (этап II): ответ создания/ротации подписки — метаданные + секрет (единожды). */
646
+ export const webhookSubscriptionCreatedSchema = webhookSubscriptionSchema.extend({
647
+ secret: z.string().min(1),
648
+ });
649
+ /** AD-052 (этап II): запись журнала доставки. */
650
+ export const webhookDeliverySchema = z.object({
651
+ id: z.string().min(1),
652
+ subscriptionId: z.string().min(1),
653
+ eventType: z.string().min(1),
654
+ status: z.enum(['ok', 'failed', 'pending']),
655
+ attempts: z.number().int().min(0),
656
+ responseStatus: z.number().int().optional(),
657
+ error: z.string().optional(),
658
+ createdAt: z.string().min(1),
659
+ completedAt: z.string().optional(),
660
+ });
661
+ /** AD-051/AD-089: цель расписания (дискриминированный союз по `mode`). */
662
+ export const scheduleTargetSchema = z.discriminatedUnion('mode', [
663
+ z.object({ mode: z.literal('bound'), sessionId: z.string().min(1) }),
664
+ z.object({
665
+ mode: z.literal('ephemeral'),
666
+ agentTemplate: z.string().optional(),
667
+ project: z.string().optional(),
668
+ ttl: z.string().optional(),
669
+ }),
670
+ z.object({ mode: z.literal('queue'), sessionId: z.string().min(1) }),
671
+ ]);
672
+ /**
673
+ * AD-089: цель правила маршрутизации — дискриминированный союз по `mode`
674
+ * (семантика та же, что у `scheduleTargetSchema`).
675
+ */
676
+ export const eventRouteTargetSchema = z.discriminatedUnion('mode', [
677
+ z.object({ mode: z.literal('bound'), sessionId: z.string().min(1) }),
678
+ z.object({
679
+ mode: z.literal('ephemeral'),
680
+ agentTemplate: z.string().optional(),
681
+ project: z.string().optional(),
682
+ ttl: z.string().optional(),
683
+ }),
684
+ z.object({ mode: z.literal('queue'), sessionId: z.string().min(1) }),
685
+ // AD-089 (auto-bind): цель закрепляет внешний адрес за сессией (binding создаёт Router).
686
+ z.object({
687
+ mode: z.literal('bind'),
688
+ agentTemplate: z.string().optional(),
689
+ project: z.string().optional(),
690
+ }),
691
+ ]);
692
+ /** AD-089: условие срабатывания правила (AND по заполненным полям). */
693
+ export const eventRouteMatchSchema = z.object({
694
+ source: z.string().optional(),
695
+ type: z.string().optional(),
696
+ chatKey: z.string().optional(),
697
+ threadKey: z.string().optional(),
698
+ principalId: z.string().optional(),
699
+ label: z.string().optional(),
700
+ keywords: z.array(z.string()).optional(),
701
+ });
702
+ /** AD-089: полная сущность правила маршрутизации событий (ответы API). */
703
+ export const eventRouteRuleSchema = z.object({
704
+ id: z.string().min(1),
705
+ name: z.string().optional(),
706
+ priority: z.number().int().default(0),
707
+ enabled: z.boolean().default(true),
708
+ match: eventRouteMatchSchema,
709
+ target: eventRouteTargetSchema,
710
+ });
711
+ /** AD-089: вход создания/обновления правила (`upsert`) — без `id`. */
712
+ export const eventRouteRuleInputSchema = z.object({
713
+ name: z.string().optional(),
714
+ priority: z.number().int().default(0),
715
+ enabled: z.boolean().default(true),
716
+ match: eventRouteMatchSchema,
717
+ target: eventRouteTargetSchema,
718
+ });
719
+ /**
720
+ * AD-089: тело upsert-запроса правила — вход + необязательный `id` (обновление
721
+ * существующего правила; отсутствие — создание нового `rule_<uuid>`).
722
+ */
723
+ export const eventRouteRuleUpsertSchema = eventRouteRuleInputSchema.extend({
724
+ id: z.string().optional(),
725
+ });
726
+ /**
727
+ * AD-051/AD-089: ровно одно из `cron` / `every` задано. Пустые строки
728
+ * трактуются как отсутствие поля.
729
+ */
730
+ function refineScheduleTrigger(val, ctx) {
731
+ const hasCron = typeof val.cron === 'string' && val.cron.trim().length > 0;
732
+ const hasEvery = typeof val.every === 'string' && val.every.trim().length > 0;
733
+ if (hasCron === hasEvery) {
734
+ ctx.addIssue({
735
+ code: z.ZodIssueCode.custom,
736
+ message: 'Ровно одно из полей cron/every должно быть задано',
737
+ path: ['cron'],
738
+ });
739
+ }
740
+ }
741
+ /** AD-051/AD-089: вход создания/обновления расписания (`ScheduleInput`). */
742
+ export const scheduleInputSchema = z
743
+ .object({
744
+ name: z.string().min(1),
745
+ enabled: z.boolean().default(true),
746
+ cron: z.string().optional(),
747
+ every: z.string().optional(),
748
+ target: scheduleTargetSchema,
749
+ prompt: z.string().optional(),
750
+ payload: z.record(z.unknown()).optional(),
751
+ ownerId: z.string().optional(),
752
+ catchUp: z.enum(['skip', 'once']).optional(),
753
+ })
754
+ .superRefine(refineScheduleTrigger);
755
+ /** AD-051/AD-089: полная сущность расписания (ответы API). */
756
+ export const scheduleSchema = z
757
+ .object({
758
+ id: z.string().min(1),
759
+ name: z.string().min(1),
760
+ enabled: z.boolean(),
761
+ cron: z.string().optional(),
762
+ every: z.string().optional(),
763
+ target: scheduleTargetSchema,
764
+ prompt: z.string().optional(),
765
+ payload: z.record(z.unknown()).optional(),
766
+ ownerId: z.string().optional(),
767
+ catchUp: z.enum(['skip', 'once']).optional(),
768
+ createdAt: z.string().min(1),
769
+ updatedAt: z.string().min(1),
770
+ lastRunAt: z.string().optional(),
771
+ nextRunAt: z.string().optional(),
772
+ lastStatus: z.enum(['ok', 'error', 'skipped']).optional(),
773
+ lastError: z.string().optional(),
774
+ })
775
+ .superRefine(refineScheduleTrigger);
776
+ /** AD-051: триггер срабатывания расписания в Job-истории. */
777
+ export const scheduleJobTriggerSchema = z.enum(['cron', 'manual', 'catchup']);
778
+ /** AD-051: запись Job-истории (ответы `GET /api/v2/schedules/:id/jobs`). */
779
+ export const scheduleJobSchema = z.object({
780
+ id: z.string().min(1),
781
+ scheduleId: z.string().min(1),
782
+ scheduleName: z.string(),
783
+ trigger: scheduleJobTriggerSchema,
784
+ status: z.enum(['ok', 'error', 'skipped']),
785
+ startedAt: z.string().min(1),
786
+ finishedAt: z.string().min(1),
787
+ durationMs: z.number(),
788
+ target: scheduleTargetSchema,
789
+ dedupKey: z.string().optional(),
790
+ decision: z.enum(['bound', 'queue', 'ephemeral', 'bind', 'drop']).optional(),
791
+ reason: z.string().optional(),
792
+ sessionId: z.string().optional(),
793
+ error: z.string().optional(),
794
+ });