@happyvertical/smrt-types 0.51.32 → 0.51.33

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.
package/dist/index.d.ts CHANGED
@@ -1,1728 +1,17 @@
1
- /**
2
- * Lifecycle status of an {@link AccessRequest} — the "request access / join the
3
- * waitlist" identity primitive that captures a prospective user from a public
4
- * form before they become a real `User`.
5
- *
6
- * Operators triage `REQUESTED` records, then either decline them or approve and
7
- * **graduate** them into a `User` (optionally attached to a tenant).
8
- *
9
- * State machine:
10
- * ```
11
- * REQUESTED ──approve──> APPROVED ──graduate──> GRADUATED
12
- * │ │
13
- * ├──decline──> DECLINED ┘ (decline also valid from APPROVED)
14
- * └──cancel───> CANCELED
15
- * ```
16
- *
17
- * @example
18
- * ```typescript
19
- * if (request.status === AccessRequestStatus.APPROVED) {
20
- * await service.graduateAccessRequest(request.id, { by: operatorId });
21
- * }
22
- * ```
23
- *
24
- * @see {@link UserStatus} for the account-level status set when a request graduates
25
- */
26
- export declare enum AccessRequestStatus {
27
- /** Open request awaiting operator triage (the default on creation) */
28
- REQUESTED = "requested",
29
- /** Operator approved the request; ready to graduate into a User */
30
- APPROVED = "approved",
31
- /** Operator declined the request */
32
- DECLINED = "declined",
33
- /** Request was graduated into a real User (terminal) */
34
- GRADUATED = "graduated",
35
- /** Request was canceled before a decision (terminal) */
36
- CANCELED = "canceled"
37
- }
38
-
39
- /**
40
- * Shared AI usage tracking types for SMRT.
41
- *
42
- * These types are intentionally provider-agnostic so SMRT can normalize
43
- * telemetry emitted by the underlying AI SDK into a stable internal shape.
44
- */
45
- /**
46
- * Normalized token usage information for an AI call.
47
- */
48
- export declare interface AiTokenUsage {
49
- /** Number of input tokens consumed by the request */
50
- promptTokens?: number;
51
- /** Number of output tokens produced by the response */
52
- completionTokens?: number;
53
- /** Total tokens consumed across the call */
54
- totalTokens?: number;
55
- }
56
-
57
- /**
58
- * Grouping dimensions supported by summary helpers.
59
- */
60
- export declare type AiUsageGroupBy = 'provider' | 'model' | 'class' | 'tenant' | 'operation' | 'day';
61
-
62
- /**
63
- * Callback interface for handling normalized AI usage events.
64
- */
65
- export declare interface AiUsageHandler {
66
- /**
67
- * Handle a normalized AI usage event.
68
- */
69
- handle(event: SmrtAiUsageEvent): Promise<void>;
70
- }
71
-
72
- /**
73
- * Options for listing raw AI usage records from persistence.
74
- */
75
- export declare interface AiUsageListOptions {
76
- /** Only include records on or after this timestamp */
77
- since?: Date;
78
- /** Only include records before or at this timestamp */
79
- until?: Date;
80
- /** Filter by provider */
81
- provider?: string;
82
- /** Filter by model */
83
- model?: string;
84
- /** Filter by operation */
85
- operation?: string;
86
- /** Filter by SMRT class name */
87
- className?: string;
88
- /** Filter by tenant ID */
89
- tenantId?: string | null;
90
- /** Maximum number of rows to return */
91
- limit?: number;
92
- /** Number of rows to skip */
93
- offset?: number;
94
- /** Sort order */
95
- orderBy?: 'timestamp DESC' | 'timestamp ASC';
96
- }
97
-
98
- /**
99
- * In-memory snapshot returned by the collector.
100
- */
101
- export declare interface AiUsageSnapshot {
102
- /** Usage aggregated by "provider:model" */
103
- byModel: Record<string, AiUsageStats>;
104
- /** Usage aggregated by "className:operation" */
105
- byClass: Record<string, AiUsageStats>;
106
- /** Total number of calls observed by the collector */
107
- totalCalls: number;
108
- /** Collector start time in epoch milliseconds */
109
- startTime: number;
110
- }
111
-
112
- /**
113
- * Aggregated statistics bucket for AI usage reporting.
114
- */
115
- export declare interface AiUsageStats {
116
- /** Number of calls represented in the bucket */
117
- callCount: number;
118
- /** Sum of prompt/input tokens */
119
- promptTokens: number;
120
- /** Sum of completion/output tokens */
121
- completionTokens: number;
122
- /** Sum of total tokens */
123
- totalTokens: number;
124
- /** Sum of durations in milliseconds */
125
- totalDuration: number;
126
- /** Sum of estimated costs in USD */
127
- estimatedCost: number;
128
- /** Timestamp of the most recent event in epoch milliseconds */
129
- lastUsed: number;
130
- }
131
-
132
- /**
133
- * Options for summarized AI usage queries.
134
- */
135
- export declare interface AiUsageSummaryOptions extends Omit<AiUsageListOptions, 'limit' | 'offset' | 'orderBy'> {
136
- /** Dimension to group summary buckets by */
137
- groupBy?: AiUsageGroupBy;
138
- }
139
-
140
- /**
141
- * Fully resolved capability classification for one declared action.
142
- *
143
- * **Fail-closed rule**: an undeclared capability resolves to
144
- * `{ effect: 'destructive', idempotent: false, openWorld: true }` — the most
145
- * restrictive exposure a policy can select. Every classifier in the mirror
146
- * (core's generator, smrt-web's legacy fallback, and any future declaration
147
- * site) MUST apply this exact default rather than inventing its own.
148
- *
149
- * **CRUD is fixed** and never overridden by a declaration:
150
- * - `list` / `get` → `{ effect: 'read', idempotent: true, openWorld: false }`
151
- * - `create` → `{ effect: 'write', idempotent: false, openWorld: false }`
152
- * - `update` → `{ effect: 'write', idempotent: true, openWorld: false }`
153
- * - `delete` → `{ effect: 'destructive', idempotent: true, openWorld: false }`
154
- *
155
- * Anything else (a custom action, a view intent, a playbook step) resolves
156
- * through an explicit {@link CapabilityDeclaration}, defaulted per-field by
157
- * the fail-closed rule above.
158
- */
159
- export declare interface CapabilityClassification {
160
- effect: CapabilityEffect;
161
- /** Whether repeating the action with the same arguments is safe. */
162
- idempotent: boolean;
163
- /** Whether the action may interact outside the SMRT application. */
164
- openWorld: boolean;
165
- }
166
-
167
- /**
168
- * An author-supplied, partial classification. Any field a declaration omits
169
- * resolves through the fail-closed rule documented on
170
- * {@link CapabilityClassification}, never through a CRUD- or name-based guess.
171
- */
172
- export declare type CapabilityDeclaration = Partial<CapabilityClassification>;
173
-
174
- /**
175
- * One capability classification contract shared by every WebMCP declaration
176
- * site (#2587). This module intentionally has no runtime code.
177
- *
178
- * Core classifies every canonical model tool at build time
179
- * (`packages/core/src/generators/tool-schema.ts`) and emits the resolved
180
- * `effect` / `idempotent` / `openWorld` on each `webMcpToolDefinitions` entry.
181
- * smrt-web's browser registrar trusts that emitted metadata for canonical
182
- * definitions instead of recomputing it, and keeps its own CRUD switch only
183
- * as the fail-closed fallback for legacy definitions that carry no metadata.
184
- * View intents (#2588) classify by this same contract where they are
185
- * declared; playbook steps (#2589) inherit classification from the model
186
- * operation they reference and never classify anything themselves.
187
- *
188
- * `smrt-web` cannot import this package — its dependency-DAG guardrails keep
189
- * it free of every `@happyvertical/*` dependency (see its AGENTS.md) — so its
190
- * `WebMcpToolEffect` mirrors {@link CapabilityEffect} structurally rather than
191
- * importing it, the same way `data-query.ts` mirrors this package's bounded
192
- * query envelope there. `smrt-core`'s `ToolEffect` (`src/registry/types.ts`)
193
- * DOES alias {@link CapabilityEffect} directly, since core already depends on
194
- * this package.
195
- */
196
- /**
197
- * Browser/agent-visible effect classification for a generated capability.
198
- * `'read'` never mutates; `'write'` mutates within the application;
199
- * `'destructive'` may remove or irreversibly change data.
200
- */
201
- export declare type CapabilityEffect = 'read' | 'write' | 'destructive';
202
-
203
- /** One typed predicate. `in` and `notIn` require a non-empty value array. */
204
- export declare interface DataQueryCondition {
205
- kind: 'condition';
206
- field: DataQueryFieldId;
207
- operator: DataQueryFilterOperator;
208
- value: DataQueryScalar | DataQueryScalar[];
209
- }
210
-
211
- export declare interface DataQueryConsistency {
212
- /** Prefer the adapter's most recently available data. */
213
- mode: DataQueryConsistencyMode;
214
- /** Optional RFC 3339 instant requested by a time-travel capable adapter. */
215
- asOf?: string;
216
- }
217
-
218
- /** Read consistency requested by a caller; adapters decide whether they support it. */
219
- export declare type DataQueryConsistencyMode = 'eventual' | 'snapshot';
220
-
221
- /** Cursor values are opaque to callers and bound to a normalized query. */
222
- export declare interface DataQueryCursorPage {
223
- kind: 'cursor';
224
- after?: string;
225
- limit: number;
226
- }
227
-
228
- /** A bounded request for one declared facet. */
229
- export declare interface DataQueryFacetRequest {
230
- field: DataQueryFieldId;
231
- limit: number;
232
- }
233
-
234
- export declare interface DataQueryFacetResult {
235
- field: DataQueryFieldId;
236
- values: DataQueryFacetValue[];
237
- truncated: boolean;
238
- }
239
-
240
- /** A bounded facet value/count pair. */
241
- export declare interface DataQueryFacetValue {
242
- value: DataQueryScalar;
243
- count: number;
244
- }
245
-
246
- /** An explicitly declared query field and its capability allowlist. */
247
- export declare interface DataQueryFieldDescriptor {
248
- id: DataQueryFieldId;
249
- type: 'string' | 'number' | 'boolean' | 'datetime' | 'json';
250
- projectable?: boolean;
251
- sortable?: boolean;
252
- facetable?: boolean;
253
- filterOperators?: DataQueryFilterOperator[];
254
- }
255
-
256
- /** A stable, adapter-defined field identifier. It is never a property path. */
257
- export declare type DataQueryFieldId = string;
258
-
259
- /** Bounded, recursive filter expression with explicit boolean semantics. */
260
- export declare type DataQueryFilter = DataQueryCondition | {
261
- kind: 'all' | 'any';
262
- filters: DataQueryFilter[];
263
- } | {
264
- kind: 'not';
265
- filter: DataQueryFilter;
266
- };
267
-
268
- /** Operators map to an adapter's allowlisted, typed predicate implementation. */
269
- export declare type DataQueryFilterOperator = 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'notIn' | 'like';
270
-
271
- /** Freshness metadata is declarative; it does not grant access to a snapshot. */
272
- export declare interface DataQueryFreshness {
273
- state: 'fresh' | 'stale' | 'unknown';
274
- asOf?: string;
275
- }
276
-
277
- /** Offset pagination is explicit so callers cannot smuggle arbitrary bounds. */
278
- export declare interface DataQueryOffsetPage {
279
- kind: 'offset';
280
- offset: number;
281
- limit: number;
282
- }
283
-
284
- export declare type DataQueryPage = DataQueryOffsetPage | DataQueryCursorPage;
285
-
286
- /**
287
- * Canonical data-query request.
288
- *
289
- * A request id correlates transport logs and results only; it is intentionally
290
- * excluded from the semantic query fingerprint. The query does not contain
291
- * authority, raw database expressions, property paths, functions, or a
292
- * transport-specific filter object.
293
- */
294
- export declare interface DataQueryRequest {
295
- version: 1;
296
- requestId: string;
297
- mode: 'rows' | 'count' | 'facets';
298
- projection?: DataQueryFieldId[];
299
- filter?: DataQueryFilter;
300
- sort?: DataQuerySort[];
301
- page?: DataQueryPage;
302
- consistency?: DataQueryConsistency;
303
- facets?: DataQueryFacetRequest[];
304
- }
305
-
306
- /**
307
- * Normalized adapter result. `queryFingerprint` identifies the semantic query
308
- * (not the request id or page cursor), while pagination state stays explicit.
309
- */
310
- export declare interface DataQueryResult {
311
- version: 1;
312
- requestId: string;
313
- queryFingerprint: string;
314
- identityField: DataQueryFieldId;
315
- rows: DataQueryRow[];
316
- page?: {
317
- kind: 'offset';
318
- limit: number;
319
- offset: number;
320
- hasMore: boolean;
321
- } | {
322
- kind: 'cursor';
323
- limit: number;
324
- nextCursor?: string;
325
- hasMore: boolean;
326
- };
327
- total: DataQueryTotal;
328
- facets?: DataQueryFacetResult[];
329
- freshness: DataQueryFreshness;
330
- warnings: string[];
331
- truncated: boolean;
332
- }
333
-
334
- /** Rows use JSON-safe values; adapters must project only declared fields. */
335
- export declare type DataQueryRow = Record<string, unknown>;
336
-
337
- /**
338
- * Transport-neutral, bounded data-query contract (#2444).
339
- *
340
- * This module intentionally has no runtime code. The core package owns
341
- * normalization, policy enforcement, canonical fingerprints, and result
342
- * validation; browser, REST, MCP, WebMCP, ContentList, and report adapters
343
- * share these serializable shapes without importing a server runtime.
344
- *
345
- * Authority is deliberately absent. A query can name only adapter-declared
346
- * field ids and operators; tenant, principal, SQL, relationship paths, and
347
- * execution details belong to the authenticated adapter, never this envelope.
348
- */
349
- /** JSON scalar values accepted in predicates, facets, and normalized rows. */
350
- export declare type DataQueryScalar = string | number | boolean | null;
351
-
352
- /**
353
- * Per-adapter execution policy. It is trusted adapter configuration, never
354
- * client input, and therefore carries the field allowlists the normalizer
355
- * applies to requests and returned rows.
356
- */
357
- export declare interface DataQuerySchema {
358
- version: 1;
359
- identityField: DataQueryFieldId;
360
- fields: DataQueryFieldDescriptor[];
361
- defaultPageLimit?: number;
362
- maxPageLimit?: number;
363
- maxResultBytes?: number;
364
- defaultSort?: DataQuerySort[];
365
- supports?: {
366
- cursorPagination?: boolean;
367
- consistency?: boolean;
368
- facets?: boolean;
369
- };
370
- }
371
-
372
- /** Deterministic sort precedence; earlier terms take precedence. */
373
- export declare interface DataQuerySort {
374
- field: DataQueryFieldId;
375
- direction: DataQuerySortDirection;
376
- }
377
-
378
- export declare type DataQuerySortDirection = 'asc' | 'desc';
379
-
380
- /** How a returned total was obtained, including the absence of a total. */
381
- export declare type DataQueryTotal = {
382
- kind: 'exact';
383
- value: number;
384
- asOf?: string;
385
- } | {
386
- kind: 'estimated';
387
- value: number;
388
- asOf?: string;
389
- } | {
390
- kind: 'unavailable';
391
- reason?: string;
392
- };
393
-
394
- export declare interface DataSurfaceActionDescriptor {
395
- id: string;
396
- label: string;
397
- description?: string;
398
- sensitivity?: DataSurfaceSensitivity;
399
- selectionScopes: DataSurfaceSelectionScope[];
400
- requiresConfirmation?: boolean;
401
- /** Optional column dependencies used by field-policy adapters. */
402
- columnIds?: string[];
403
- }
404
-
405
- /** Preview/apply is a contract only here; server-side adapters execute it. */
406
- export declare interface DataSurfaceActionRequest {
407
- version: 1;
408
- requestId: string;
409
- identity: DataSurfaceIdentity;
410
- actionId: string;
411
- phase: 'preview' | 'apply';
412
- selection: DataSurfaceSelectionReference;
413
- payload?: DataSurfaceJsonValue;
414
- /** Opaque confirmation produced by a prior preview, never an authority. */
415
- confirmationToken?: string;
416
- }
417
-
418
- export declare interface DataSurfaceActionResult {
419
- version: 1;
420
- requestId: string;
421
- identity: DataSurfaceIdentity;
422
- actionId: string;
423
- phase: 'preview' | 'apply';
424
- ok: boolean;
425
- reason?: string;
426
- confirmationToken?: string;
427
- details?: DataSurfaceJsonObject;
428
- }
429
-
430
- /** Serializable outcome for one server-resolved row in an action. */
431
- export declare interface DataSurfaceActionRowOutcome {
432
- rowId: DataSurfaceRowId;
433
- status: 'accepted' | 'skipped' | 'failed';
434
- reason?: string;
435
- metadata?: DataSurfaceJsonObject;
436
- }
437
-
438
- /**
439
- * Canonical wire request for principal-bound server adapters. A preview can
440
- * omit the idempotency key; apply requires it at the server boundary.
441
- */
442
- export declare interface DataSurfaceActionWireRequest extends DataSurfaceActionRequest {
443
- expectedRevision: number;
444
- idempotencyKey?: string;
445
- }
446
-
447
- export declare type DataSurfaceColumnCapability = 'read' | 'search' | 'filter' | 'sort' | 'project';
448
-
449
- export declare interface DataSurfaceColumnDescriptor {
450
- id: string;
451
- label: string;
452
- description?: string;
453
- sensitivity?: DataSurfaceSensitivity;
454
- capabilities: DataSurfaceColumnCapability[];
455
- /** Domain field identity; never accepted as a request path. */
456
- fieldName?: string;
457
- /** Effective policy visibility, when a domain adapter supplies one. */
458
- visibility?: DataSurfaceColumnVisibility;
459
- /** Stable policy order; domain column ids remain unchanged. */
460
- order?: number;
461
- /** Structural columns are preserved even when field policy narrows data columns. */
462
- role?: DataSurfaceColumnRole;
463
- /** Responsive adapters consume this without importing DataTable types. */
464
- responsivePriority?: number;
465
- /** Per-operation operator allowlists, narrowed by policy adapters. */
466
- operators?: DataSurfaceColumnOperators;
467
- /** Explicit aliases for adapters that mirror the canonical query schema. */
468
- searchOperators?: string[];
469
- filterOperators?: string[];
470
- sortOperators?: string[];
471
- /** Explicit readability is useful when read capability is policy-gated. */
472
- readable?: boolean;
473
- }
474
-
475
- /** Operator allowlists are intentionally strings: #2444 owns query semantics. */
476
- export declare interface DataSurfaceColumnOperators {
477
- search?: string[];
478
- filter?: string[];
479
- sort?: string[];
480
- }
481
-
482
- /** A domain-neutral column role. Adapters use roles to protect structural columns. */
483
- export declare type DataSurfaceColumnRole = 'data' | 'status' | 'computed' | 'row-key' | 'selection' | 'action';
484
-
485
- /** Presentation tier emitted by policy-aware domain adapters. */
486
- export declare type DataSurfaceColumnVisibility = 'basic' | 'advanced' | 'hidden';
487
-
488
- export declare type DataSurfaceCommandExecution = {
489
- ok: false;
490
- } | undefined;
491
-
492
- export declare type DataSurfaceCommandFailureReason = 'not_found' | 'unsupported' | 'stale_revision' | 'idempotency_conflict' | 'denied' | 'execution_failed' | 'non_monotonic_revision';
493
-
494
- export declare interface DataSurfaceCommandResult {
495
- ok: boolean;
496
- commandId: string;
497
- identity: DataSurfaceIdentity;
498
- revision?: number;
499
- snapshot?: DataSurfaceSnapshot;
500
- reason?: DataSurfaceCommandFailureReason;
501
- }
502
-
503
- /** Public, serializable discovery metadata for a mounted data surface. */
504
- export declare interface DataSurfaceDescriptor {
505
- version: 1;
506
- identity: DataSurfaceIdentity;
507
- /** Version of the domain adapter's descriptor and view-state schema. */
508
- schemaVersion: number;
509
- label: string;
510
- description?: string;
511
- /** Stable row-identity column, including when it is not visibly rendered. */
512
- rowKey: string;
513
- columns: DataSurfaceColumnDescriptor[];
514
- query: DataSurfaceQueryCapabilities;
515
- controls: DataSurfaceVisibleControl[];
516
- actions: DataSurfaceActionDescriptor[];
517
- limits: DataSurfaceLimits;
518
- }
519
-
520
- /** Stable address for one mounted instance, never an authority boundary. */
521
- export declare interface DataSurfaceIdentity {
522
- surfaceId: string;
523
- kind: DataSurfaceKind;
524
- subject?: DataSurfaceSubject;
525
- }
526
-
527
- export declare type DataSurfaceJsonObject = {
528
- [key: string]: DataSurfaceJsonValue;
529
- };
530
-
531
- /**
532
- * Transport-neutral data-surface contracts.
533
- *
534
- * These declarations describe bounded browser/server action envelopes and
535
- * mounted-surface metadata. They carry neither authority nor execution:
536
- * authenticated adapters own both.
537
- */
538
- export declare type DataSurfaceJsonPrimitive = string | number | boolean | null;
539
-
540
- export declare type DataSurfaceJsonValue = DataSurfaceJsonPrimitive | DataSurfaceJsonValue[] | {
541
- [key: string]: DataSurfaceJsonValue;
542
- };
543
-
544
- export declare type DataSurfaceKind = 'table' | 'list' | 'report' | 'custom';
545
-
546
- /** Per-surface limits; generic envelopes use DATA_SURFACE_MAX_REQUEST_BYTES. */
547
- export declare interface DataSurfaceLimits {
548
- maxQueryRows: number;
549
- maxQueryBytes: number;
550
- maxSelectionSize: number;
551
- }
552
-
553
- export declare interface DataSurfaceQueryCapabilities {
554
- modes: DataSurfaceQueryMode[];
555
- /** Explicit allowlist; field paths are not accepted in requests. */
556
- projectableColumnIds: string[];
557
- /** Explicit allowlists for non-projection query operations. */
558
- searchableColumnIds?: string[];
559
- filterableColumnIds?: string[];
560
- sortableColumnIds?: string[];
561
- }
562
-
563
- /** #2444 owns the canonical query language; this declares only its bounds. */
564
- export declare type DataSurfaceQueryMode = 'rows' | 'count' | 'facets';
565
-
566
- /**
567
- * This intentionally contains only bounded read shape. #2444 adds the
568
- * canonical filters, ordering, cursors, totals, and normalized result details.
569
- */
570
- export declare type DataSurfaceQueryRequest = {
571
- version: 1;
572
- requestId: string;
573
- identity: DataSurfaceIdentity;
574
- kind: 'rows';
575
- limit: number;
576
- cursor?: string;
577
- projection?: string[];
578
- } | {
579
- version: 1;
580
- requestId: string;
581
- identity: DataSurfaceIdentity;
582
- kind: 'count';
583
- } | {
584
- version: 1;
585
- requestId: string;
586
- identity: DataSurfaceIdentity;
587
- kind: 'facets';
588
- columnId: string;
589
- limit: number;
590
- };
591
-
592
- /** Bounded read result shapes; #2444 owns their canonical query semantics. */
593
- export declare type DataSurfaceQueryResult = (DataSurfaceQueryResultBase & {
594
- kind: 'rows';
595
- rowKey: string;
596
- rows: DataSurfaceJsonObject[];
597
- hasMore: boolean;
598
- truncated: boolean;
599
- nextCursor?: string;
600
- }) | (DataSurfaceQueryResultBase & {
601
- kind: 'count';
602
- count: number;
603
- }) | (DataSurfaceQueryResultBase & {
604
- kind: 'facets';
605
- columnId: string;
606
- facets: Array<{
607
- value: DataSurfaceJsonPrimitive;
608
- count: number;
609
- }>;
610
- truncated: boolean;
611
- });
612
-
613
- declare interface DataSurfaceQueryResultBase {
614
- version: 1;
615
- requestId: string;
616
- identity: DataSurfaceIdentity;
617
- revision: number;
618
- }
619
-
620
- /** Runtime-only handle supplied by a mounted renderer or controller. */
621
- export declare interface DataSurfaceRegistration {
622
- descriptor: DataSurfaceDescriptor;
623
- getSnapshot: () => DataSurfaceSnapshotState;
624
- execute?: (command: DataSurfaceVisibleCommand) => DataSurfaceCommandExecution | Promise<DataSurfaceCommandExecution>;
625
- /**
626
- * A host-owned redaction boundary. It cannot change identity or revision and
627
- * the registry validates its output before exposing it.
628
- */
629
- redact?: (snapshot: DataSurfaceSnapshot) => DataSurfaceSnapshot;
630
- }
631
-
632
- export declare interface DataSurfaceRegistry {
633
- register(registration: DataSurfaceRegistration): () => void;
634
- unregister(identity: DataSurfaceIdentity): void;
635
- list(): DataSurfaceDescriptor[];
636
- inspect(identity: DataSurfaceIdentity): DataSurfaceSnapshot | undefined;
637
- execute(command: DataSurfaceVisibleCommand): Promise<DataSurfaceCommandResult>;
638
- validateQuery(request: DataSurfaceQueryRequest): DataSurfaceValidationResult;
639
- validateAction(request: DataSurfaceActionRequest): DataSurfaceValidationResult;
640
- subscribe(listener: (event: DataSurfaceRegistryEvent) => void): () => void;
641
- }
642
-
643
- export declare interface DataSurfaceRegistryEvent {
644
- type: 'registered' | 'unregistered' | 'command';
645
- sequence: number;
646
- identity: DataSurfaceIdentity;
647
- revision: number;
648
- command?: DataSurfaceVisibleCommand;
649
- result?: DataSurfaceCommandResult;
650
- }
651
-
652
- export declare type DataSurfaceRowId = string | number;
653
-
654
- export declare type DataSurfaceSelectionReference = {
655
- scope: 'current-page';
656
- } | {
657
- scope: 'explicit-ids';
658
- rowIds: DataSurfaceRowId[];
659
- } | {
660
- scope: 'all-matching';
661
- queryFingerprint: string;
662
- };
663
-
664
- export declare type DataSurfaceSelectionScope = 'current-page' | 'explicit-ids' | 'all-matching';
665
-
666
- export declare type DataSurfaceSensitivity = 'public' | 'personal' | 'sensitive' | 'secret';
667
-
668
- /** Deterministic inspect/result envelope. It intentionally has no timestamp. */
669
- export declare interface DataSurfaceSnapshot {
670
- version: 1;
671
- descriptor: DataSurfaceDescriptor;
672
- revision: number;
673
- state: DataSurfaceJsonObject;
674
- selection: DataSurfaceSelectionReference | null;
675
- }
676
-
677
- /** Input supplied by a mounted renderer/controller, before registry wrapping. */
678
- export declare interface DataSurfaceSnapshotState {
679
- revision: number;
680
- state: DataSurfaceJsonObject;
681
- selection?: DataSurfaceSelectionReference | null;
682
- }
683
-
684
- export declare interface DataSurfaceSubject {
685
- type: string;
686
- id: string;
687
- label?: string;
688
- }
689
-
690
- export declare type DataSurfaceValidationReason = 'not_found' | 'unsupported' | 'invalid_request' | 'limit_exceeded' | 'projection_not_allowed' | 'selection_not_supported' | 'confirmation_required';
691
-
692
- export declare interface DataSurfaceValidationResult {
693
- ok: boolean;
694
- reason?: DataSurfaceValidationReason;
695
- }
696
-
697
- /** A browser-visible state transition, not a server-side query or mutation. */
698
- export declare interface DataSurfaceVisibleCommand {
699
- version: 1;
700
- commandId: string;
701
- identity: DataSurfaceIdentity;
702
- expectedRevision: number;
703
- controlId: string;
704
- payload?: DataSurfaceJsonValue;
705
- }
706
-
707
- export declare interface DataSurfaceVisibleControl {
708
- /** Stable command name accepted by the mounted surface. */
709
- id: string;
710
- label: string;
711
- description?: string;
712
- }
713
-
714
- /**
715
- * The package's declared agent-addressable surface beyond its generated model
716
- * tools (#2591).
717
- *
718
- * Omitted entirely when a package declares no intents, playbooks, or
719
- * diagnostics, so an artifact for a package with none stays byte-identical to
720
- * what it emitted before this field existed.
721
- */
722
- export declare interface DomainKnowledgeAgentSurface {
723
- intents: DomainKnowledgeViewIntent[];
724
- playbooks: DomainKnowledgePlaybook[];
725
- diagnostics: DomainKnowledgeAgentSurfaceDiagnostic[];
726
- }
727
-
728
- /**
729
- * A declaration the scanner recognized but could not emit.
730
- *
731
- * Recorded rather than dropped: the whole point of emitting the agent surface
732
- * is that "what can an agent do here" has one answer, and an invisible
733
- * declaration would quietly make that answer wrong. Every message names
734
- * `useWebMcpTool`, the escape hatch for a genuinely computed tool set.
735
- */
736
- export declare interface DomainKnowledgeAgentSurfaceDiagnostic {
737
- code: string;
738
- helper: 'defineIntent' | 'definePlaybook';
739
- message: string;
740
- /** Declaring module, relative to the package root, in POSIX form. */
741
- sourceFile: string;
742
- line?: number;
743
- column?: number;
744
- }
745
-
746
- /** Per-object configuration controlling domain-knowledge generation and exposure. */
747
- export declare interface DomainKnowledgeConfig {
748
- enabled?: boolean;
749
- api?: {
750
- /**
751
- * Generate HTTP knowledge routes. Disabled by default; prefer CLI/MCP for
752
- * agent workflows unless this is a guarded dev/admin endpoint.
753
- */
754
- enabled?: boolean;
755
- basePath?: string;
756
- includeDocs?: boolean;
757
- includePrompts?: boolean;
758
- /**
759
- * Require dev mode or admin locals for HTTP knowledge access. Setting this
760
- * to false makes the route public and should only be used when sanitized
761
- * anonymous schema/surface metadata is acceptable.
762
- */
763
- requireAdmin?: boolean;
764
- };
765
- includeDocs?: boolean;
766
- includePrompts?: boolean;
767
- tags?: string[];
768
- summary?: string;
769
- risks?: string[];
770
- }
771
-
772
- /** A field retained in the curated agent-facing object shape. */
773
- export declare interface DomainKnowledgeField {
774
- name: string;
775
- type: string;
776
- required?: boolean;
777
- related?: string;
778
- columnType?: string;
779
- default?: unknown;
780
- constraints?: DomainKnowledgeFieldConstraints;
781
- readonly?: boolean;
782
- transient?: boolean;
783
- }
784
-
785
- /** Validation constraints retained in the curated agent-facing field shape. */
786
- export declare interface DomainKnowledgeFieldConstraints {
787
- min?: number;
788
- max?: number;
789
- minLength?: number;
790
- maxLength?: number;
791
- pattern?: string;
792
- }
793
-
794
- /** Result of a domain-knowledge freshness check (stale references, error/warning counts). */
795
- export declare interface DomainKnowledgeFreshnessResult {
796
- ok: boolean;
797
- checkedAt: string;
798
- artifactPath?: string;
799
- issueCount: number;
800
- errorCount: number;
801
- warningCount: number;
802
- issues: Array<{
803
- severity: 'error' | 'warning';
804
- code: string;
805
- message: string;
806
- file?: string;
807
- packageName?: string;
808
- }>;
809
- }
810
-
811
- /** The package-level domain-knowledge artifact (`smrt-knowledge.json`) — the agent/developer contract. */
812
- export declare interface DomainKnowledgeManifest {
813
- schemaVersion: 1;
814
- /** True when generation removed sensitive fields before projecting objects. */
815
- sensitiveFieldsExcluded?: true;
816
- generatedAt: string;
817
- packageName?: string;
818
- packageVersion?: string;
819
- sourceManifestPath?: string;
820
- agentDocPath?: string;
821
- sourceHashes: Record<string, string>;
822
- exports: string[];
823
- dependencies: Record<string, string>;
824
- smrtDependencies: string[];
825
- sdkDependencies: string[];
826
- tags: string[];
827
- summary?: string;
828
- risks: string[];
829
- objects: DomainKnowledgeObject[];
830
- surfaces: DomainKnowledgeSurface[];
831
- prompts: Array<{
832
- filePath: string;
833
- key?: string;
834
- }>;
835
- relationshipsV2: {
836
- foreignKeyFields: number;
837
- crossPackageRefFields: number;
838
- junctionCollections: number;
839
- hierarchicalObjects: number;
840
- polymorphicAssociations: number;
841
- uuidColumns: number;
842
- };
843
- agentDoc?: string;
844
- /** Sibling module docs linked from `AGENTS.md`; omitted when the package links none. */
845
- moduleDocs?: DomainKnowledgeModuleDoc[];
846
- /**
847
- * Declared view intents and playbooks (#2591). Omitted when the package
848
- * declares none, so this field is additive to schema version 1.
849
- *
850
- * This is deliberately a knowledge-artifact field and not a runtime-manifest
851
- * field: `manifest.json` stays runtime-focused, and the agent-addressable
852
- * surface is an agent/developer contract.
853
- */
854
- agentSurface?: DomainKnowledgeAgentSurface;
855
- }
856
-
857
- /** Additive structured signature; `methods: string[]` remains the compatibility surface. */
858
- export declare interface DomainKnowledgeMethodSignature {
859
- name: string;
860
- async?: boolean;
861
- static?: boolean;
862
- params?: string[];
863
- returns?: string;
864
- }
865
-
866
- /**
867
- * A sibling module doc linked from a package's `AGENTS.md` (#2108).
868
- *
869
- * Oversized package docs are split by module into `packages/<pkg>/agents/<module>.md`
870
- * rather than nested `AGENTS.md` files, because instruction chains are additive.
871
- * The link in `AGENTS.md` is the registration: the knowledge tooling resolves it
872
- * so the moved prose — which is curated and not regenerable from the manifest —
873
- * stays reachable from agent context.
874
- */
875
- export declare interface DomainKnowledgeModuleDoc {
876
- /** Path relative to the package root, e.g. `agents/commissions.md`. */
877
- path: string;
878
- /** Module name derived from the file's basename, e.g. `commissions`. */
879
- module: string;
880
- content: string;
881
- }
882
-
883
- /** One object's entry in the domain-knowledge manifest (fields, relationships, surfaces). */
884
- export declare interface DomainKnowledgeObject {
885
- name: string;
886
- qualifiedName?: string;
887
- collection: string;
888
- tableName?: string;
889
- packageName?: string;
890
- extends?: string;
891
- visibility?: string;
892
- fields: DomainKnowledgeField[];
893
- relationships: DomainKnowledgeField[];
894
- methods: string[];
895
- methodSignatures?: DomainKnowledgeMethodSignature[];
896
- tenant?: DomainKnowledgeTenant;
897
- tableStrategy?: 'cti' | 'sti';
898
- conflictColumns?: string[];
899
- surfaces: DomainKnowledgeSurface[];
900
- /**
901
- * Public methods a generated surface withheld, with the reason for each.
902
- * Omitted entirely when nothing was withheld, so an artifact for a fully
903
- * exposed object is unchanged (#2686).
904
- */
905
- withheldSurfaces?: DomainKnowledgeWithheldSurface[];
906
- relationshipFeatures: string[];
907
- tags: string[];
908
- summary?: string;
909
- risks: string[];
910
- }
911
-
912
- /** A registered playbook (#2589) as emitted into the knowledge artifact (#2591). */
913
- export declare interface DomainKnowledgePlaybook {
914
- key: string;
915
- title: string;
916
- description: string;
917
- steps: DomainKnowledgePlaybookStep[];
918
- planes: Array<'browser' | 'server'>;
919
- /** False when `planes` was derived from the step kinds rather than declared. */
920
- planesDeclared: boolean;
921
- onStepFailure: 'abort' | 'continue';
922
- enabled: boolean;
923
- /** Declaring module, relative to the package root, in POSIX form. */
924
- sourceFile: string;
925
- }
926
-
927
- /** One step of an emitted playbook. Steps never nest another playbook. */
928
- export declare type DomainKnowledgePlaybookStep = {
929
- kind: 'operation';
930
- model: string;
931
- action: string;
932
- } | {
933
- kind: 'intent';
934
- id: string;
935
- };
936
-
937
- /** A single generated surface (one api/cli/mcp/ai operation) exposed by an object. */
938
- export declare interface DomainKnowledgeSurface {
939
- kind: DomainKnowledgeSurfaceKind;
940
- name: string;
941
- operation: string;
942
- path?: string;
943
- method?: string;
944
- description?: string;
945
- objectName?: string;
946
- }
947
-
948
- /** Kind of generated surface a knowledge entry describes (REST/CLI/MCP/AI). */
949
- export declare type DomainKnowledgeSurfaceKind = 'api' | 'cli' | 'mcp' | 'ai';
950
-
951
- /** Normalized tenancy facts from `@smrt({ tenantScoped })`. */
952
- export declare interface DomainKnowledgeTenant {
953
- scoped: boolean;
954
- mode?: 'required' | 'optional';
955
- field?: string;
956
- }
957
-
958
- /**
959
- * A declared view intent (#2588) as emitted into the knowledge artifact (#2591).
960
- *
961
- * `id` is the entry's identity everywhere: in this artifact, in a playbook step
962
- * (`{ kind: 'intent', id }`), and in `smrt doctor`'s surface report. It is
963
- * declared, never derived from a namespace, a generated tool name, or a route,
964
- * so it survives every rename those could undergo.
965
- */
966
- export declare interface DomainKnowledgeViewIntent {
967
- id: string;
968
- description: string;
969
- /** Resolved through the #2587 fail-closed rule at declaration time. */
970
- capability: CapabilityClassification;
971
- /** The browser registry this intent compiles into, and what it addresses. */
972
- target: Record<string, unknown>;
973
- hasInputSchema: boolean;
974
- /**
975
- * Always exactly `['browser']`. An intent moves mounted browser state; a
976
- * server-side agent reaches one only through the #2446 command/ack bridge,
977
- * which the referencing playbook declares. Typed as the literal tuple so a
978
- * consumer cannot read the contract as wider than it is.
979
- */
980
- planes: ['browser'];
981
- /** Declaring module, relative to the package root, in POSIX form. */
982
- sourceFile: string;
983
- }
984
-
985
- /**
986
- * A public method a generated surface deliberately does NOT expose, and why.
987
- *
988
- * Silence is the failure mode this closes: before #2686 a method that produced
989
- * no route simply did not appear, leaving an author to guess whether they had
990
- * mistyped a name, hit an `exclude`, or written a signature no HTTP caller can
991
- * satisfy. `reason` is human-readable prose; `code` is the stable key to react
992
- * to programmatically.
993
- */
994
- export declare interface DomainKnowledgeWithheldSurface {
995
- kind: DomainKnowledgeSurfaceKind;
996
- /** The method name that was withheld. */
997
- operation: string;
998
- /**
999
- * Stable rejection key — `not-wireable`, `excluded`, `not-included`,
1000
- * `withheld`, `lifecycle-method`, `no-receiver`, `api-disabled`.
1001
- */
1002
- code: string;
1003
- /** Human-readable explanation, e.g. why a parameter cannot cross a wire. */
1004
- reason: string;
1005
- objectName?: string;
1006
- }
1007
-
1008
- /** User↔Tenant↔Role junction. Runtime class: `@happyvertical/smrt-users:Membership`. */
1009
- export declare interface Membership extends SmrtEntityFields {
1010
- userId?: string;
1011
- tenantId?: string;
1012
- roleId?: string;
1013
- status: MembershipStatus;
1014
- }
1015
-
1016
- /**
1017
- * Status of a user's membership within a specific tenant.
1018
- *
1019
- * A user may hold memberships in multiple tenants simultaneously, each with an
1020
- * independent `MembershipStatus`.
1021
- *
1022
- * @example
1023
- * ```typescript
1024
- * const active = memberships.filter(m => m.status === MembershipStatus.ACTIVE);
1025
- * ```
1026
- *
1027
- * @see {@link UserStatus} for the global account-level status
1028
- * @see {@link TenantStatus} for the status of the tenant itself
1029
- */
1030
- export declare enum MembershipStatus {
1031
- /** Active membership */
1032
- ACTIVE = "active",
1033
- /** Inactive membership */
1034
- INACTIVE = "inactive",
1035
- /** Pending invitation acceptance */
1036
- PENDING = "pending"
1037
- }
1038
-
1039
- /**
1040
- * Generic component type for SMRT module UI slots.
1041
- *
1042
- * Intentionally opaque — defined as a loose function signature rather than
1043
- * `import('svelte').ComponentType` to avoid pulling Svelte (and its DOM types)
1044
- * into server-side Node.js builds. The actual Svelte component constructor
1045
- * is assignable to this type at runtime.
1046
- *
1047
- * @typeParam Props - The props interface the component accepts; defaults to `unknown`.
1048
- *
1049
- * @example
1050
- * ```typescript
1051
- * import InvoiceCard from './InvoiceCard.svelte';
1052
- * // InvoiceCard is assignable to ModuleComponentType<InvoiceCardProps>
1053
- * registry.register('@happyvertical/smrt-commerce', 'invoice-card', InvoiceCard);
1054
- * ```
1055
- *
1056
- * @see {@link ModuleUIBaseProps} for the base props all slot components receive
1057
- * @see {@link ModuleUIRegistryInterface} for storing and retrieving components
1058
- */
1059
- export declare type ModuleComponentType<Props = unknown> = (...args: any[]) => any;
1060
-
1061
- /**
1062
- * Base props contract for all SMRT module UI slot components.
1063
- *
1064
- * Every component registered against a `ModuleUISlot` should accept at least
1065
- * these props. Individual slot components may extend this interface with
1066
- * slot-specific required props.
1067
- *
1068
- * @typeParam TData - Shape of the primary data object(s) the component renders.
1069
- * @typeParam TConfig - Shape of the optional configuration/settings object.
1070
- *
1071
- * @example
1072
- * ```typescript
1073
- * interface InvoiceCardProps extends ModuleUIBaseProps<Invoice> {
1074
- * showLineItems?: boolean;
1075
- * }
1076
- * ```
1077
- *
1078
- * @see {@link ModuleComponentType} for the component type that accepts these props
1079
- * @see {@link ModuleUISlot} for the slot declaration that names the `propsInterface`
1080
- */
1081
- export declare interface ModuleUIBaseProps<TData = unknown, TConfig = unknown> {
1082
- /** Primary data object(s) the component operates on */
1083
- data?: TData;
1084
- /** Configuration/settings */
1085
- config?: TConfig;
1086
- /** Callback for data changes */
1087
- onChange?: (data: TData) => void | Promise<void>;
1088
- /** Callback for saving */
1089
- onSave?: (data: TData) => Promise<void>;
1090
- /** Whether component is read-only */
1091
- readonly?: boolean;
1092
- /** CSS class for styling */
1093
- class?: string;
1094
- /** Loading state */
1095
- loading?: boolean;
1096
- }
1097
-
1098
- /**
1099
- * Registry interface for mapping SMRT module slots to Svelte components.
1100
- *
1101
- * Implemented by `ModuleUIRegistry` in `@happyvertical/smrt-ui`. Consumers
1102
- * call `register()` once per slot at Svelte package initialisation time and
1103
- * `get()` when rendering to retrieve the correct component.
1104
- *
1105
- * @example
1106
- * ```typescript
1107
- * // Registration (in packages/commerce/src/svelte/index.ts)
1108
- * ModuleUIRegistry.registerModule(COMMERCE_MODULE_META);
1109
- * ModuleUIRegistry.register('@happyvertical/smrt-commerce', 'invoice-card', InvoiceCard);
1110
- *
1111
- * // Retrieval (in a host Svelte app)
1112
- * const InvoiceCard = ModuleUIRegistry.get('@happyvertical/smrt-commerce', 'invoice-card');
1113
- * ```
1114
- *
1115
- * @see {@link SmrtModuleMeta} for the module metadata structure passed to `registerModule()`
1116
- * @see {@link ModuleUISlot} for the slot identifiers used as `slotId`
1117
- * @see {@link ModuleComponentType} for the component type stored in the registry
1118
- */
1119
- export declare interface ModuleUIRegistryInterface {
1120
- /** Register a component for a module's slot */
1121
- register<TProps extends ModuleUIBaseProps>(moduleName: string, slotId: string, component: ModuleComponentType<TProps>): void;
1122
- /** Get a component for a module's slot */
1123
- get<TProps extends ModuleUIBaseProps>(moduleName: string, slotId: string): ModuleComponentType<TProps> | undefined;
1124
- /** Check if component is registered */
1125
- has(moduleName: string, slotId: string): boolean;
1126
- /** Get all registered slot IDs for a module */
1127
- getSlots(moduleName: string): string[];
1128
- /** Get all registered module names */
1129
- getModules(): string[];
1130
- /** Get module metadata */
1131
- getModuleMeta(moduleName: string): SmrtModuleMeta | undefined;
1132
- /** Register module metadata */
1133
- registerModule(meta: SmrtModuleMeta): void;
1134
- /** Unregister for testing */
1135
- unregister(moduleName: string, slotId: string): boolean;
1136
- /** Clear all for testing */
1137
- clear(): void;
1138
- }
1139
-
1140
- /**
1141
- * Module type definitions for SMRT Framework
1142
- *
1143
- * These types allow SMRT modules to declare their capabilities,
1144
- * including models, collections, and optional Svelte UI components.
1145
- *
1146
- * @example Module with UI components
1147
- * ```typescript
1148
- * // In core module: packages/commerce/src/ui.ts
1149
- * import type { SmrtModuleMeta, ModuleUISlot } from '@happyvertical/smrt-types';
1150
- *
1151
- * export const COMMERCE_UI_SLOTS: Record<string, ModuleUISlot> = {
1152
- * 'invoice-card': { id: 'invoice-card', label: 'Invoice Card', category: 'display' },
1153
- * };
1154
- *
1155
- * export const COMMERCE_MODULE_META: SmrtModuleMeta = {
1156
- * name: '@happyvertical/smrt-commerce',
1157
- * displayName: 'Commerce',
1158
- * uiSlots: COMMERCE_UI_SLOTS,
1159
- * };
1160
- *
1161
- * // In svelte subpath: packages/commerce/src/svelte/index.ts
1162
- * import { ModuleUIRegistry } from '@happyvertical/smrt-ui/registry';
1163
- * import { COMMERCE_MODULE_META } from '../ui.js';
1164
- * import InvoiceCard from './components/InvoiceCard.svelte';
1165
- *
1166
- * ModuleUIRegistry.registerModule(COMMERCE_MODULE_META);
1167
- * ModuleUIRegistry.register('@happyvertical/smrt-commerce', 'invoice-card', InvoiceCard);
1168
- * ```
1169
- */
1170
- /**
1171
- * UI slot definition for a SMRT module.
1172
- *
1173
- * Modules declare the slots they support in their `SmrtModuleMeta`. Svelte UI
1174
- * packages then implement those slots by registering components against the
1175
- * same `id` via `ModuleUIRegistryInterface.register()`.
1176
- *
1177
- * @example
1178
- * ```typescript
1179
- * const slot: ModuleUISlot = {
1180
- * id: 'invoice-card',
1181
- * label: 'Invoice Card',
1182
- * description: 'Compact card view for a single invoice',
1183
- * category: 'display',
1184
- * order: 10,
1185
- * };
1186
- * ```
1187
- *
1188
- * @see {@link SmrtModuleMeta} for how slots are declared on a module
1189
- * @see {@link ModuleUIRegistryInterface} for registering component implementations
1190
- */
1191
- export declare interface ModuleUISlot {
1192
- /** Unique identifier (e.g., 'invoice-card', 'customer-form') */
1193
- id: string;
1194
- /** Human-readable label */
1195
- label: string;
1196
- /** Description of the component's purpose */
1197
- description?: string;
1198
- /** Icon identifier (lucide icon names) */
1199
- icon?: string;
1200
- /** Display order (lower first) */
1201
- order?: number;
1202
- /** Component category for grouping */
1203
- category?: 'display' | 'form' | 'admin' | 'list' | 'detail' | 'action' | 'dashboard' | 'navigation';
1204
- /** Required props interface name (for documentation) */
1205
- propsInterface?: string;
1206
- }
1207
-
1208
- /**
1209
- * Effect applied by a user-level permission override.
1210
- *
1211
- * Overrides target a specific user + permission combination and always win
1212
- * over role-based grants. `DENY` overrides are checked before `GRANT` in
1213
- * the 4-level permission cascade.
1214
- *
1215
- * @example
1216
- * ```typescript
1217
- * await override.create({
1218
- * userId,
1219
- * permission: 'billing.view',
1220
- * effect: OverrideEffect.DENY,
1221
- * });
1222
- * ```
1223
- *
1224
- * @see {@link TenantPermissionEffect} for the tenant-level equivalent that supports inheritance
1225
- */
1226
- export declare enum OverrideEffect {
1227
- /** Grant the permission */
1228
- GRANT = "grant",
1229
- /** Deny the permission */
1230
- DENY = "deny"
1231
- }
1232
-
1233
- /** RBAC role. Runtime class: `@happyvertical/smrt-users:Role`. */
1234
- export declare interface Role extends SmrtEntityFields {
1235
- /** `null` → system role available to every tenant. */
1236
- tenantId?: string | null;
1237
- name: string;
1238
- description: string;
1239
- isSystem: boolean;
1240
- /**
1241
- * Opt-in hierarchical inheritance: when `true`, an ACTIVE membership holding
1242
- * this role also resolves permissions in descendant tenants where the user
1243
- * has no direct membership. Default `false` (authority is exact-tenant only).
1244
- */
1245
- inheritsToDescendants: boolean;
1246
- }
1247
-
1248
- /**
1249
- * Status of an authenticated session.
1250
- *
1251
- * Sessions transition from `ACTIVE` to either `EXPIRED` (time-based) or
1252
- * `REVOKED` (explicit action by the user or an administrator).
1253
- *
1254
- * @example
1255
- * ```typescript
1256
- * if (session.status !== SessionStatus.ACTIVE) {
1257
- * redirect(302, '/login');
1258
- * }
1259
- * ```
1260
- *
1261
- * @see {@link UserStatus} for the account-level status checked before session creation
1262
- */
1263
- export declare enum SessionStatus {
1264
- /** Active session */
1265
- ACTIVE = "active",
1266
- /** Expired session (past expiresAt) */
1267
- EXPIRED = "expired",
1268
- /** Revoked by user or admin */
1269
- REVOKED = "revoked"
1270
- }
1271
-
1272
- /**
1273
- * Signal emitted during SMRT method execution.
1274
- *
1275
- * Signals provide automatic observability into method execution,
1276
- * enabling logging, metrics, pub/sub updates, and other integrations
1277
- * without requiring manual instrumentation.
1278
- *
1279
- * @example
1280
- * ```typescript
1281
- * // Logging adapter
1282
- * const loggingAdapter: SignalAdapter = {
1283
- * async handle(signal: Signal) {
1284
- * const label = `${signal.className}.${signal.method} [${signal.id}]`;
1285
- * if (signal.type === 'start') console.log(`→ ${label}`);
1286
- * if (signal.type === 'end') console.log(`✓ ${label} (${signal.duration}ms)`);
1287
- * if (signal.type === 'error') console.error(`✗ ${label}`, signal.error);
1288
- * },
1289
- * };
1290
- * ```
1291
- *
1292
- * @see {@link SignalType} for the lifecycle stage values
1293
- * @see {@link SignalAdapter} for implementing a consumer
1294
- */
1295
- export declare interface Signal {
1296
- /**
1297
- * Unique identifier for this specific execution
1298
- * Generated once per method invocation
1299
- */
1300
- id: string;
1301
- /**
1302
- * ID of the SMRT object instance
1303
- */
1304
- objectId: string;
1305
- /**
1306
- * Name of the SMRT class
1307
- */
1308
- className: string;
1309
- /**
1310
- * Name of the method being executed
1311
- */
1312
- method: string;
1313
- /**
1314
- * Signal type indicating lifecycle stage:
1315
- * - 'start': Method execution started
1316
- * - 'step': Manual step within method (optional)
1317
- * - 'end': Method execution completed successfully
1318
- * - 'error': Method execution failed
1319
- */
1320
- type: SignalType;
1321
- /**
1322
- * Optional step label for manual progress tracking
1323
- * Developers can emit custom steps within methods using bus.emit()
1324
- */
1325
- step?: string;
1326
- /**
1327
- * Sanitized method arguments (sensitive data removed)
1328
- * Objects with @sensitive JSDoc tags are excluded
1329
- */
1330
- args?: unknown[];
1331
- /**
1332
- * Method result (only present on 'end' signals)
1333
- */
1334
- result?: unknown;
1335
- /**
1336
- * Error that was thrown (only present on 'error' signals)
1337
- */
1338
- error?: Error;
1339
- /**
1340
- * Method execution duration in milliseconds
1341
- * Only present on 'end' and 'error' signals
1342
- */
1343
- duration?: number;
1344
- /**
1345
- * Timestamp when signal was emitted
1346
- */
1347
- timestamp: Date;
1348
- /**
1349
- * Optional additional context
1350
- * Can include tracing IDs, user context, request metadata, etc.
1351
- */
1352
- metadata?: Record<string, unknown>;
1353
- }
1354
-
1355
- /**
1356
- * Adapter interface for consuming signals from the SMRT signaling system.
1357
- *
1358
- * Adapters process signals for specific purposes:
1359
- * - **Logging**: write to console, file, or a logging service
1360
- * - **Metrics**: track execution counts, durations, and error rates
1361
- * - **Pub/Sub**: broadcast real-time updates to connected clients
1362
- * - **Tracing**: forward spans to a distributed tracing system (e.g., OpenTelemetry)
1363
- *
1364
- * Adapters are fire-and-forget — errors thrown inside `handle()` are caught
1365
- * by the SignalBus and do not interrupt the main execution flow.
1366
- *
1367
- * @example
1368
- * ```typescript
1369
- * class MetricsAdapter implements SignalAdapter {
1370
- * async handle(signal: Signal): Promise<void> {
1371
- * if (signal.type === 'end') {
1372
- * metrics.histogram('smrt.method.duration', signal.duration ?? 0, {
1373
- * class: signal.className,
1374
- * method: signal.method,
1375
- * });
1376
- * }
1377
- * }
1378
- * }
1379
- * ```
1380
- *
1381
- * @see {@link Signal} for the payload each adapter receives
1382
- * @see {@link SignalType} for the lifecycle stages
1383
- */
1384
- export declare interface SignalAdapter {
1385
- /**
1386
- * Handle a signal event
1387
- *
1388
- * @param signal - The signal to process
1389
- * @returns Promise that resolves when signal is handled
1390
- *
1391
- * @remarks
1392
- * This method should not throw - errors are caught by the SignalBus.
1393
- * Implementations should handle their own error logging/recovery.
1394
- */
1395
- handle(signal: Signal): Promise<void>;
1396
- }
1397
-
1398
- /**
1399
- * Universal Signaling System Types
1400
- *
1401
- * This module defines the core types for the SMRT signaling system,
1402
- * which provides automatic method tracking and event distribution
1403
- * for logging, metrics, pub/sub, and other observability needs.
1404
- */
1405
- /**
1406
- * Lifecycle stage of a signal emitted during SMRT method execution.
1407
- *
1408
- * - `'start'` — emitted when a tracked method begins executing
1409
- * - `'step'` — emitted manually within a method for progress tracking
1410
- * - `'end'` — emitted when a method completes successfully
1411
- * - `'error'` — emitted when a method throws an unhandled exception
1412
- *
1413
- * @example
1414
- * ```typescript
1415
- * adapter.handle = async (signal: Signal) => {
1416
- * if (signal.type === 'error') {
1417
- * logger.error(`${signal.className}.${signal.method} failed`, signal.error);
1418
- * }
1419
- * };
1420
- * ```
1421
- *
1422
- * @see {@link Signal} for the full signal payload shape
1423
- * @see {@link SignalAdapter} for consuming signals
1424
- */
1425
- export declare type SignalType = 'start' | 'step' | 'end' | 'error';
1426
-
1427
- /**
1428
- * Stable usage event shape emitted inside SMRT after every AI call.
1429
- */
1430
- export declare interface SmrtAiUsageEvent {
1431
- /** AI provider identifier (e.g. "openai", "anthropic") */
1432
- provider: string;
1433
- /** Model identifier used for the call */
1434
- model: string;
1435
- /** High-level operation name (e.g. "chat", "embed", "stream") */
1436
- operation: string;
1437
- /** Token usage reported by the provider, when available */
1438
- usage?: AiTokenUsage;
1439
- /** Wall-clock duration in milliseconds */
1440
- duration: number;
1441
- /** Event timestamp */
1442
- timestamp: Date;
1443
- /** Optional provider- or application-specific tags */
1444
- tags?: Record<string, string>;
1445
- /** SMRT class responsible for the call */
1446
- className?: string;
1447
- /** Tenant identifier when available */
1448
- tenantId?: string | null;
1449
- /** Best-effort estimated cost in USD */
1450
- estimatedCost?: number;
1451
- }
1452
-
1453
- /**
1454
- * Persisted AI usage record returned from query helpers.
1455
- */
1456
- export declare interface SmrtAiUsageRecord extends SmrtAiUsageEvent {
1457
- /** Persistent record identifier */
1458
- id: string;
1459
- }
1460
-
1461
- /**
1462
- * Fields every persisted SMRT entity exposes — a subset of `SmrtObject`'s public
1463
- * surface. `id`/`slug` are `null`/`undefined` before the first persist, matching
1464
- * the base getters.
1465
- */
1466
- export declare interface SmrtEntityFields {
1467
- /** UUID, assigned on first persist. */
1468
- id: string | null | undefined;
1469
- /** URL-safe slug, when the model maintains one. */
1470
- slug: string | null | undefined;
1471
- /** Creation timestamp; `null`/`undefined` before first persist. */
1472
- created_at: Date | null | undefined;
1473
- /** Last-update timestamp; `null`/`undefined` before first persist. */
1474
- updated_at: Date | null | undefined;
1475
- }
1476
-
1477
- /**
1478
- * Metadata declaration for a SMRT module.
1479
- *
1480
- * Each module exports a `SmrtModuleMeta` constant describing its package
1481
- * identity, the UI slots it declares, and the model/collection classes it
1482
- * provides. The UI registry uses this to resolve component lookups at runtime.
1483
- *
1484
- * @example
1485
- * ```typescript
1486
- * export const COMMERCE_MODULE_META: SmrtModuleMeta = {
1487
- * name: '@happyvertical/smrt-commerce',
1488
- * displayName: 'Commerce',
1489
- * description: 'Invoicing, contracts, and fulfillment',
1490
- * models: ['Customer', 'Invoice', 'Contract'],
1491
- * uiSlots: {
1492
- * 'invoice-card': { id: 'invoice-card', label: 'Invoice Card', category: 'display' },
1493
- * },
1494
- * };
1495
- * ```
1496
- *
1497
- * @see {@link ModuleUISlot} for the shape of each declared slot
1498
- * @see {@link ModuleUIRegistryInterface} for registering and retrieving module components
1499
- */
1500
- export declare interface SmrtModuleMeta {
1501
- /** Package name (e.g., '@happyvertical/smrt-commerce') */
1502
- name: string;
1503
- /** Human-readable display name */
1504
- displayName: string;
1505
- /** Module description */
1506
- description?: string;
1507
- /** Module version */
1508
- version?: string;
1509
- /** UI slots this module declares */
1510
- uiSlots?: Record<string, ModuleUISlot>;
1511
- /** Model classes this module provides */
1512
- models?: string[];
1513
- /** Collection classes this module provides */
1514
- collections?: string[];
1515
- /** Peer dependencies for UI (e.g., ['@happyvertical/smrt-profiles']) */
1516
- uiDependencies?: string[];
1517
- }
1518
-
1519
- /**
1520
- * Package-owned route definition.
1521
- *
1522
- * @typeParam TData - Data shape the route component expects.
1523
- * @typeParam TLoadInput - Input accepted by the optional `load` helper.
1524
- * @typeParam TProps - Component props shape. Defaults to `{ data?: TData }`.
1525
- */
1526
- export declare interface SmrtRouteDefinition<TData = unknown, TLoadInput = unknown, TProps = {
1527
- data?: TData;
1528
- }> {
1529
- /** Stable route identifier, namespaced by package. */
1530
- id: string;
1531
- /** Human-readable page title. */
1532
- title: string;
1533
- /** Optional description for docs and tooling. */
1534
- description?: string;
1535
- /** Canonical path the package recommends by default. */
1536
- defaultPath: string;
1537
- /** Page component exported by the package. */
1538
- component: ModuleComponentType<TProps>;
1539
- /** Optional reusable load helper for app-owned route files. */
1540
- load?: (input: TLoadInput) => Promise<TData> | TData;
1541
- /** Which SvelteKit route file the `load` helper belongs in. */
1542
- loadKind?: SmrtRouteLoadKind;
1543
- /** Optional navigation metadata. */
1544
- nav?: SmrtRouteNavigationMeta;
1545
- /** Optional tags for docs, hosts, or filtering. */
1546
- tags?: string[];
1547
- }
1548
-
1549
- /**
1550
- * Route load function category.
1551
- *
1552
- * `page` maps naturally to SvelteKit's `+page.ts`, while `page-server` maps to
1553
- * `+page.server.ts`.
1554
- */
1555
- export declare type SmrtRouteLoadKind = 'page' | 'page-server';
1556
-
1557
- /**
1558
- * Package-owned route module.
1559
- *
1560
- * Consumers import one of these from `@happyvertical/smrt-<pkg>/routes`, then
1561
- * mount the exported components and loaders inside their own app route tree.
1562
- *
1563
- */
1564
- export declare interface SmrtRouteModule {
1565
- /** Package name, usually `@happyvertical/smrt-<pkg>`. */
1566
- packageName: string;
1567
- /** Human-readable module name. */
1568
- displayName: string;
1569
- /** Optional module description. */
1570
- description?: string;
1571
- /**
1572
- * Route definitions keyed by package-local name.
1573
- *
1574
- * A heterogeneous registry: each entry is a `SmrtRouteDefinition` with its
1575
- * own `TData`/`TLoadInput`/`TProps`. `TLoadInput` sits in a contravariant
1576
- * position (`load?: (input: TLoadInput) => …`), so a concrete route
1577
- * (`SmrtRouteDefinition<Foo, Bar>`) is NOT assignable to
1578
- * `SmrtRouteDefinition<unknown, unknown, unknown>` — narrowing the params to
1579
- * `unknown` would reject every real route registration. Like
1580
- * {@link ModuleComponentType}, this is an irreducible registry `any`.
1581
- */
1582
- routes: Record<string, SmrtRouteDefinition<any, any, any>>;
1583
- }
1584
-
1585
- /**
1586
- * Resolved navigation entry for a mounted route.
1587
- */
1588
- export declare interface SmrtRouteNavigationItem {
1589
- /** Stable route identifier. */
1590
- routeId: string;
1591
- /** Link href as mounted by the consuming app. */
1592
- href: string;
1593
- /** Label shown in the app navigation. */
1594
- label: string;
1595
- /** Optional description for menu UI. */
1596
- description?: string;
1597
- /** Optional icon identifier. */
1598
- icon?: string;
1599
- /** Display order (lower first). */
1600
- order?: number;
1601
- /** Optional grouping key for larger menus. */
1602
- group?: string;
1603
- }
1604
-
1605
- /**
1606
- * Navigation metadata for a package route.
1607
- */
1608
- export declare interface SmrtRouteNavigationMeta {
1609
- /** Label shown in app navigation. */
1610
- label: string;
1611
- /** Optional route description for menus or docs. */
1612
- description?: string;
1613
- /** Optional icon identifier. */
1614
- icon?: string;
1615
- /** Display order (lower first). */
1616
- order?: number;
1617
- /** Optional grouping key for larger menus. */
1618
- group?: string;
1619
- }
1620
-
1621
- /** Hierarchical tenant. Runtime class: `@happyvertical/smrt-users:Tenant`. */
1622
- export declare interface Tenant extends SmrtEntityFields {
1623
- name: string;
1624
- status: TenantStatus;
1625
- description: string;
1626
- parentTenantId?: string | null;
1627
- hierarchyLevel: number;
1628
- hierarchyPath: string;
1629
- cascadePermissions: boolean;
1630
- inheritPermissions: boolean;
1631
- }
1632
-
1633
- /**
1634
- * Effect of a tenant-level permission setting in a hierarchical tenant tree.
1635
- *
1636
- * Unlike `OverrideEffect`, tenant-level effects support `INHERIT` — the default
1637
- * behaviour where a child tenant walks up to its parent to resolve the permission.
1638
- * `DENY` blocks inheritance, preventing child tenants from acquiring the permission
1639
- * even if a grandparent grants it.
1640
- *
1641
- * @example
1642
- * ```typescript
1643
- * // Sub-tenant explicitly blocks billing access regardless of parent settings
1644
- * await tenantPermission.create({
1645
- * tenantId: subTenantId,
1646
- * permission: 'billing.manage',
1647
- * effect: TenantPermissionEffect.DENY,
1648
- * });
1649
- * ```
1650
- *
1651
- * @see {@link OverrideEffect} for user-level overrides (no inheritance step)
1652
- * @see {@link TenantStatus} for the tenant lifecycle status
1653
- */
1654
- export declare enum TenantPermissionEffect {
1655
- /** Inherit from parent tenant (default behavior) */
1656
- INHERIT = "inherit",
1657
- /** Explicitly grant at this tenant level */
1658
- GRANT = "grant",
1659
- /** Explicitly deny at this tenant level (blocks inheritance) */
1660
- DENY = "deny"
1661
- }
1662
-
1663
- /**
1664
- * Lifecycle status of a tenant (organization) within the platform.
1665
- *
1666
- * @example
1667
- * ```typescript
1668
- * if (tenant.status === TenantStatus.ARCHIVED) {
1669
- * return; // skip soft-deleted tenants
1670
- * }
1671
- * ```
1672
- *
1673
- * @see {@link MembershipStatus} for a user's membership status within a tenant
1674
- * @see {@link TenantPermissionEffect} for permission inheritance across tenant hierarchies
1675
- */
1676
- export declare enum TenantStatus {
1677
- /** Active tenant */
1678
- ACTIVE = "active",
1679
- /** Inactive tenant */
1680
- INACTIVE = "inactive",
1681
- /** Suspended tenant */
1682
- SUSPENDED = "suspended",
1683
- /** Archived tenant (soft-deleted) */
1684
- ARCHIVED = "archived"
1685
- }
1686
-
1687
- /** Auth identity record. Runtime class: `@happyvertical/smrt-users:User`. */
1688
- export declare interface User extends SmrtEntityFields {
1689
- /** Plain-string reference to the owning `Profile` (not a DB foreign key). */
1690
- profileId: string;
1691
- /** Lower-cased email; globally unique. */
1692
- email: string;
1693
- status: UserStatus;
1694
- lastLoginAt: Date | null;
1695
- }
1696
-
1697
- /**
1698
- * User-related type definitions
1699
- *
1700
- * These enums and types are exported from smrt-types to allow
1701
- * browser-safe packages (like smrt-svelte) to import them without
1702
- * pulling in server-side dependencies from smrt-users.
1703
- */
1704
- /**
1705
- * Lifecycle status of a user account.
1706
- *
1707
- * @example
1708
- * ```typescript
1709
- * if (user.status === UserStatus.SUSPENDED) {
1710
- * throw new ForbiddenError('Account is suspended');
1711
- * }
1712
- * ```
1713
- *
1714
- * @see {@link MembershipStatus} for a user's status within a specific tenant
1715
- * @see {@link SessionStatus} for the status of an active session
1716
- */
1717
- export declare enum UserStatus {
1718
- /** Active user account */
1719
- ACTIVE = "active",
1720
- /** Inactive user account */
1721
- INACTIVE = "inactive",
1722
- /** Suspended user account */
1723
- SUSPENDED = "suspended",
1724
- /** Pending email verification */
1725
- PENDING = "pending"
1726
- }
1727
-
1728
- export { }
1
+ /**
2
+ * @happyvertical/smrt-types - Shared type definitions for the SMRT SDK
3
+ *
4
+ * This package provides shared TypeScript type definitions and interfaces
5
+ * used across multiple SMRT SDK packages to prevent circular dependencies.
6
+ */
7
+ export type { AiTokenUsage, AiUsageGroupBy, AiUsageHandler, AiUsageListOptions, AiUsageSnapshot, AiUsageStats, AiUsageSummaryOptions, SmrtAiUsageEvent, SmrtAiUsageRecord, } from './ai-usage.js';
8
+ export type { CapabilityClassification, CapabilityDeclaration, CapabilityEffect, } from './capability.js';
9
+ export type { DataQueryCondition, DataQueryConsistency, DataQueryConsistencyMode, DataQueryCursorPage, DataQueryFacetRequest, DataQueryFacetResult, DataQueryFacetValue, DataQueryFieldDescriptor, DataQueryFieldId, DataQueryFilter, DataQueryFilterOperator, DataQueryFreshness, DataQueryOffsetPage, DataQueryPage, DataQueryRequest, DataQueryResult, DataQueryRow, DataQueryScalar, DataQuerySchema, DataQuerySort, DataQuerySortDirection, DataQueryTotal, } from './data-query.js';
10
+ export type { DataSurfaceActionDescriptor, DataSurfaceActionRequest, DataSurfaceActionResult, DataSurfaceActionRowOutcome, DataSurfaceActionWireRequest, DataSurfaceColumnCapability, DataSurfaceColumnDescriptor, DataSurfaceColumnOperators, DataSurfaceColumnRole, DataSurfaceColumnVisibility, DataSurfaceCommandExecution, DataSurfaceCommandFailureReason, DataSurfaceCommandResult, DataSurfaceDescriptor, DataSurfaceIdentity, DataSurfaceJsonObject, DataSurfaceJsonPrimitive, DataSurfaceJsonValue, DataSurfaceKind, DataSurfaceLimits, DataSurfaceQueryCapabilities, DataSurfaceQueryMode, DataSurfaceQueryRequest, DataSurfaceQueryResult, DataSurfaceRegistration, DataSurfaceRegistry, DataSurfaceRegistryEvent, DataSurfaceRowId, DataSurfaceSelectionReference, DataSurfaceSelectionScope, DataSurfaceSensitivity, DataSurfaceSnapshot, DataSurfaceSnapshotState, DataSurfaceSubject, DataSurfaceValidationReason, DataSurfaceValidationResult, DataSurfaceVisibleCommand, DataSurfaceVisibleControl, } from './data-surface.js';
11
+ export type { Membership, Role, SmrtEntityFields, Tenant, User, } from './identity.js';
12
+ export type { DomainKnowledgeAgentSurface, DomainKnowledgeAgentSurfaceDiagnostic, DomainKnowledgeConfig, DomainKnowledgeField, DomainKnowledgeFieldConstraints, DomainKnowledgeFreshnessResult, DomainKnowledgeManifest, DomainKnowledgeMethodSignature, DomainKnowledgeModuleDoc, DomainKnowledgeObject, DomainKnowledgePlaybook, DomainKnowledgePlaybookStep, DomainKnowledgeSurface, DomainKnowledgeSurfaceKind, DomainKnowledgeTenant, DomainKnowledgeViewIntent, DomainKnowledgeWithheldSurface, } from './knowledge.js';
13
+ export type { ModuleComponentType, ModuleUIBaseProps, ModuleUIRegistryInterface, ModuleUISlot, SmrtModuleMeta, } from './module.js';
14
+ export type { SmrtRouteDefinition, SmrtRouteLoadKind, SmrtRouteModule, SmrtRouteNavigationItem, SmrtRouteNavigationMeta, } from './routes.js';
15
+ export type { Signal, SignalAdapter, SignalType } from './signals.js';
16
+ export { AccessRequestStatus, MembershipStatus, OverrideEffect, SessionStatus, TenantPermissionEffect, TenantStatus, UserStatus, } from './user.js';
17
+ //# sourceMappingURL=index.d.ts.map