simetra 0.2.0 → 0.3.0-next.10

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.
Files changed (35) hide show
  1. package/dist/channel-grant-BATD6oQu.js +15 -0
  2. package/dist/compiler/index.d.ts +732 -85
  3. package/dist/compiler/index.js +26488 -13752
  4. package/dist/data/centrifugo/index.d.ts +24 -0
  5. package/dist/data/centrifugo/index.js +173 -0
  6. package/dist/data/index.d.ts +27 -0
  7. package/dist/data/index.js +10115 -0
  8. package/dist/data/react/index.d.ts +103 -0
  9. package/dist/data/react/index.js +214 -0
  10. package/dist/grant-Zg0hmqK7.d.ts +11 -0
  11. package/dist/handle-C6PFsnUX.js +44 -0
  12. package/dist/holder-CkR-qRYU.d.ts +585 -0
  13. package/dist/model/index.d.ts +4396 -400
  14. package/dist/model/index.js +4425 -380
  15. package/dist/schema/index.d.ts +1545 -572
  16. package/dist/schema/index.js +8554 -4215
  17. package/dist/server/index.d.ts +710 -21
  18. package/dist/server/index.js +4663 -483
  19. package/dist/server/signals/index.d.ts +92 -0
  20. package/dist/server/signals/index.js +140 -0
  21. package/dist/shell/index.d.ts +112 -0
  22. package/dist/shell/index.js +159 -0
  23. package/dist/ui/index.d.ts +213 -0
  24. package/dist/ui/index.js +1098 -0
  25. package/package.json +75 -3
  26. package/schemas/accumulation-registers.schema.json +46 -5
  27. package/schemas/catalogs.schema.json +113 -33
  28. package/schemas/constants.schema.json +31 -5
  29. package/schemas/custom-tables.schema.json +24 -0
  30. package/schemas/documents.schema.json +86 -31
  31. package/schemas/functions.schema.json +129 -0
  32. package/schemas/information-registers.schema.json +47 -5
  33. package/schemas/project.schema.json +206 -1
  34. package/schemas/rights-sets.schema.json +19 -1
  35. package/schemas/roles.schema.json +23 -2
@@ -1,4 +1,180 @@
1
- import { CommandError, CommandResult, DatabaseProvider, ObjectModule, Operation, ProviderApiRoles, ReadQuery, RequestRolePurpose, RuntimeCatalog, SessionClaims } from "simetra/model";
1
+ import { t as ChannelGrant } from "../grant-Zg0hmqK7.js";
2
+ import { z } from "zod";
3
+ import { Batch, CommandError, CommandFailure, CommandResult, DataResponse, DatabaseProvider, IdentitySource, LocalizedString, MetadataRef, ObjectModule, ObjectOperation, Operation, ProviderApiRoles, ReadPart, ReadPartValue, ReadQuery, ReadResult, ReadResultOf, RequestRolePurpose, RightsSnapshot, RuntimeCatalog, RuntimeObject, SessionClaims } from "simetra/model";
4
+ /** Object key of the database binding marker (platform spec §8.2). */
5
+ export declare const INSTANCE_MARKER_KEY = "simetra-instance";
6
+ /** The file store port of the server tier (platform spec §8.4). */
7
+ interface FileStore {
8
+ /**
9
+ * Reads the body, counts the bytes itself and aborts past `maxBytes`
10
+ * (nothing is written then). `instance` is the database binding string
11
+ * (`parseBinding`): the bucket must carry the same marker. `put` never
12
+ * writes the marker: an unbound empty bucket is `no-binding`, a bucket with
13
+ * objects but no marker or another database's marker is `foreign-bucket`.
14
+ */
15
+ put(key: string, body: ReadableStream<Uint8Array>, options: {
16
+ contentType: string;
17
+ maxBytes: number;
18
+ instance: string;
19
+ }): Promise<{
20
+ size: number;
21
+ }>;
22
+ /** `null` when the key has no object. */
23
+ get(key: string): Promise<{
24
+ body: ReadableStream<Uint8Array>;
25
+ size: number;
26
+ contentType: string;
27
+ } | null>;
28
+ delete(key: string): Promise<void>;
29
+ /** Objects under `prefix` in key order, after the key `after` when given. */
30
+ list(prefix: string, after?: string): AsyncIterable<{
31
+ key: string;
32
+ lastModified: Date;
33
+ }>;
34
+ /**
35
+ * The object prefixes `o/<uuid>/` present in the bucket, in key order.
36
+ * Lets the reconciliation name a prefix of an object the catalog does not
37
+ * know, which it only logs.
38
+ */
39
+ listPrefixes(): AsyncIterable<string>;
40
+ /**
41
+ * Refuses (throws {@link FileStoreError}) a bucket that is not this
42
+ * database's: a different marker (`foreign-bucket`), the same marker
43
+ * written for another cluster, database or timeline (`binding-changed`: a
44
+ * copy or a restore), or objects without a marker. An empty unbound bucket
45
+ * passes (nothing to delete).
46
+ * Used by the reconciliation before any deletion.
47
+ */
48
+ checkInstance(instance: string): Promise<void>;
49
+ /**
50
+ * The first binding of a bucket, an explicit operator step (the S3 servers
51
+ * of the profiles have no conditional write, so `put` cannot bind safely).
52
+ * Writes the marker only into a completely empty bucket and reads it back;
53
+ * the same marker already there is a no-op. Objects without a marker or
54
+ * another database's marker are `foreign-bucket`, the same uuid with another
55
+ * cluster state is `binding-changed` (use `rebind`).
56
+ */
57
+ bind(instance: string): Promise<void>;
58
+ /**
59
+ * Rewrites the marker with `instance` after a legitimate restore. Only a
60
+ * marker of the same `storage_instance` uuid is rewritten; anything else
61
+ * (no marker, another uuid) is `foreign-bucket`.
62
+ */
63
+ rebind(instance: string): Promise<void>;
64
+ }
65
+ /** Refusal of the store itself; `reason` is a closed list. */
66
+ export declare class FileStoreError extends Error {
67
+ readonly reason: "too-large" | "foreign-bucket" | "binding-changed" | "no-binding" | "in-recovery" | "bad-limit" | "bad-key" | "bad-listing";
68
+ constructor(reason: "too-large" | "foreign-bucket" | "binding-changed" | "no-binding" | "in-recovery" | "bad-limit" | "bad-key" | "bad-listing", message: string);
69
+ }
70
+ /**
71
+ * The slice of the aggregate AWS SDK `S3` client the adapter uses. Структурний
72
+ * тип замість імпорту SDK: серверний ярус не тягне його в бандл, host
73
+ * передає будь-який клієнт з такою формою (як `PgPoolLike`).
74
+ */
75
+ interface S3ClientLike {
76
+ putObject(input: {
77
+ Bucket: string;
78
+ Key: string;
79
+ Body: Uint8Array;
80
+ ContentLength: number;
81
+ ContentType?: string;
82
+ }): Promise<unknown>;
83
+ getObject(input: {
84
+ Bucket: string;
85
+ Key: string;
86
+ }): Promise<{
87
+ Body?: {
88
+ transformToWebStream(): ReadableStream<Uint8Array>;
89
+ };
90
+ ContentLength?: number;
91
+ ContentType?: string;
92
+ }>;
93
+ deleteObject(input: {
94
+ Bucket: string;
95
+ Key: string;
96
+ }): Promise<unknown>;
97
+ listObjectsV2(input: {
98
+ Bucket: string;
99
+ Prefix?: string;
100
+ Delimiter?: string;
101
+ StartAfter?: string;
102
+ ContinuationToken?: string;
103
+ MaxKeys?: number;
104
+ }): Promise<{
105
+ Contents?: {
106
+ Key?: string;
107
+ LastModified?: Date;
108
+ }[];
109
+ CommonPrefixes?: {
110
+ Prefix?: string;
111
+ }[];
112
+ IsTruncated?: boolean;
113
+ NextContinuationToken?: string;
114
+ }>;
115
+ }
116
+ /** Adapts an S3 client to the port; the bucket is fixed by the server. */
117
+ export declare function fromS3Client(client: S3ClientLike, bucket: string): FileStore;
118
+ /** Age after which an object without a row may be deleted (platform spec §8.2). */
119
+ export declare const RECONCILE_GRACE_MS: number;
120
+ /**
121
+ * Why a run deleted nothing on purpose: a bucket of another database
122
+ * (`instance`), the marker of a copied or restored database (`binding`), a
123
+ * standby (`recovery`) or the deletion guard (`guard`).
124
+ */
125
+ type ReconcileRefusal = "instance" | "binding" | "recovery" | "guard";
126
+ /** What the reconciliation reports to its `log` option. */
127
+ type ReconcileLogEntry = {
128
+ kind: "refused";
129
+ reason: ReconcileRefusal;
130
+ message: string;
131
+ } | {
132
+ kind: "unknown-prefix";
133
+ prefix: string;
134
+ } | {
135
+ kind: "row-without-bytes";
136
+ object: string;
137
+ id: string;
138
+ };
139
+ /** Options of `CommandRuntime.reconcileFiles`. */
140
+ interface ReconcileOptions {
141
+ log: (entry: ReconcileLogEntry) => void;
142
+ }
143
+ /** The outcome of one reconciliation run. */
144
+ interface ReconcileReport {
145
+ /** File objects found under the prefixes of objects with `storage`. */
146
+ listed: number;
147
+ deleted: number;
148
+ /** Why the run deleted nothing on purpose; `null` — it did not refuse. */
149
+ refused: ReconcileRefusal | null;
150
+ /** Object prefixes in the bucket the catalog does not know (only logged). */
151
+ unknownPrefixes: string[];
152
+ /** Rows of objects with `storage` that have no bytes in the bucket. */
153
+ rowsWithoutBytes: number;
154
+ /** Attach records of finished transactions removed from the database. */
155
+ pendingSwept: number;
156
+ }
157
+ /**
158
+ * Facts about the request origin that the host passes to the data handler.
159
+ * An HTTP call carries the `Sec-Fetch-Site` and `Origin` header values (absent
160
+ * header = absent field) and the origin the host serves from; a call inside
161
+ * the server process (SSR) is `{ inProcess: true }`.
162
+ */
163
+ type RequestOrigin = {
164
+ secFetchSite?: string;
165
+ origin?: string;
166
+ expectedOrigin: string;
167
+ } | {
168
+ inProcess: true;
169
+ };
170
+ /**
171
+ * Step 0 of the data handler: refuses a request that could be forged by
172
+ * another site. Runs before the envelope is parsed, so it touches nothing but
173
+ * the origin facts (and, for `inProcess`, the raw request type).
174
+ *
175
+ * @returns the refusal, or `undefined` when the request may proceed.
176
+ */
177
+ export declare function checkRequestOrigin(origin: RequestOrigin, rawRequest: unknown): CommandError | undefined;
2
178
  /**
3
179
  * One connection taken from a pool: bound text parameters only, unnamed
4
180
  * statements (P4 spec Рт19).
@@ -32,6 +208,10 @@ interface PgPoolLike {
32
208
  command: string;
33
209
  }>;
34
210
  release(destroy?: boolean): void;
211
+ on(event: "error", listener: (error: Error) => void): unknown;
212
+ on(event: "end", listener: () => void): unknown;
213
+ removeListener(event: "error", listener: (error: Error) => void): unknown;
214
+ removeListener(event: "end", listener: () => void): unknown;
35
215
  }>;
36
216
  }
37
217
  /**
@@ -44,22 +224,68 @@ declare const RAW_TYPES: {
44
224
  };
45
225
  /** Adapts a `pg` pool to the runtime port. */
46
226
  export declare function fromPgPool(pool: PgPoolLike): CommandDatabase;
47
- /**
48
- * The rejection of `run` and `read`: `message` is the error code, no
49
- * `cause` — текст Postgres не має виходити назовні навіть через ланцюжок
50
- * причин (Р-A3-8).
51
- */
52
- export declare class CommandFailure extends Error {
53
- readonly error: CommandError;
54
- constructor(error: CommandError);
55
- }
56
227
  /** A runtime log entry: the full error stays inside the process. */
57
228
  type LogEntry = {
58
229
  kind: "afterCommit" | "hook" | "defer" | "database";
59
230
  error: unknown;
60
231
  };
232
+ /** The rejection of `attachFile`: a `CommandFailure` with the commit flag. */
233
+ export declare class FileAttachFailure extends CommandFailure {
234
+ /**
235
+ * `true` when `COMMIT` was sent and the session closed: the row may exist,
236
+ * so the caller must keep the bytes. `false` — a known rollback or a
237
+ * refusal before the database.
238
+ */
239
+ readonly commitUnknown: boolean;
240
+ constructor(error: CommandError,
241
+ /**
242
+ * `true` when `COMMIT` was sent and the session closed: the row may exist,
243
+ * so the caller must keep the bytes. `false` — a known rollback or a
244
+ * refusal before the database.
245
+ */
246
+ commitUnknown: boolean);
247
+ }
248
+ /** The input of {@link CommandRuntime.checkUpload}. */
249
+ interface CheckUploadInput {
250
+ object: MetadataRef;
251
+ /** The scope the file row would be created in; `null`/absent for an unscoped object. */
252
+ scope?: string | null;
253
+ }
254
+ /** What a user may upload to an object: the limits of its `storage`. */
255
+ interface UploadLimits {
256
+ maxBytes: number;
257
+ mediaTypes: string[];
258
+ /**
259
+ * The database binding string read in the same transaction as the check
260
+ * (`FileStore.put` option `instance`, see `parseBinding`).
261
+ */
262
+ instance: string;
263
+ }
264
+ /** The input of {@link CommandRuntime.attachFile}. */
265
+ interface AttachFileInput {
266
+ object: MetadataRef;
267
+ /** The scope of the row; required for a scoped object, absent otherwise. */
268
+ scope?: string | null;
269
+ /** The row id the server generated and wrote the bytes under (`fileObjectKey`). */
270
+ id: string;
271
+ /** The file name; stored in the `file_name` attribute. */
272
+ name: string;
273
+ /** Other attributes of the row, by logical names. */
274
+ fields?: Record<string, unknown>;
275
+ /** The byte count `FileStore.put` counted itself. */
276
+ size: number;
277
+ /** The content type of the bytes. */
278
+ contentType: string;
279
+ }
61
280
  /** Options of {@link createCommandRuntime}. */
62
281
  interface CommandRuntimeOptions {
282
+ /**
283
+ * The database port. Its connections log in as the runtime login role
284
+ * directly: the runtime judges `session_user`, which must reach neither
285
+ * the owner nor a privileged role (`command.privileged-login`). A pool that
286
+ * logs in as a superuser and switches with `SET SESSION AUTHORIZATION` is
287
+ * outside this trust model — such a host already holds a superuser DSN.
288
+ */
63
289
  database: CommandDatabase;
64
290
  /** The runtime catalog object (`runtime-catalog.json`); validated here. */
65
291
  catalog: unknown;
@@ -67,37 +293,500 @@ interface CommandRuntimeOptions {
67
293
  objectModules?: Readonly<Record<string, ObjectModule<object>>>;
68
294
  /** Hands `afterCommit` work to the platform (`waitUntil`); without it `run` awaits that work. */
69
295
  defer?: (work: Promise<unknown>) => void;
70
- /** Reads through the fallback path when the login role lacks the request role. */
296
+ /**
297
+ * Reads through the fallback path when the login role lacks the user
298
+ * request role. Membership in the anonymous request role of the profile is
299
+ * always required.
300
+ */
71
301
  readFallback?: boolean;
72
302
  /** Attempts in total on serialization failure or deadlock; default 3. */
73
303
  maxAttempts?: number;
74
304
  /** Depth limit of phases started by hooks; default 8. */
75
305
  maxDepth?: number;
306
+ /**
307
+ * `statement_timeout` ceiling of a server read statement in milliseconds
308
+ * (integer ≥ 1); default 15 000. A statement past it fails its part with
309
+ * `command.timeout`.
310
+ */
311
+ readStatementTimeoutMs?: number;
312
+ /**
313
+ * Time budget of one server read transaction, all its parts, in
314
+ * milliseconds (integer ≥ 1000); default 15 000. A part not started
315
+ * before it fails with `command.timeout`.
316
+ */
317
+ readBudgetMs?: number;
318
+ /**
319
+ * Time budget of one `run` call, retries and their pauses included, in
320
+ * milliseconds (integer ≥ 1000); default 60 000. A command past it rejects
321
+ * with `command.timeout`.
322
+ */
323
+ commandBudgetMs?: number;
324
+ /**
325
+ * Operations of one `run` batch (integer 1…`BATCH_MAX`); default
326
+ * `BATCH_MAX`. A longer batch rejects with `command.invalid`
327
+ * `reason: "batch-too-large"`. Phases started by `ctx.run` are not counted:
328
+ * they stay bound by `BATCH_MAX`.
329
+ */
330
+ maxBatch?: number;
331
+ /**
332
+ * Rows of one tabular section of an operation, of `run` and of every
333
+ * `ctx.run` phase (integer 1…`TABULAR_LINES_MAX`); default
334
+ * `TABULAR_LINES_MAX`. More rows reject with `command.invalid`
335
+ * `reason: "tabular-too-large"`. Reads keep the `TABULAR_LINES_MAX` ceiling.
336
+ */
337
+ maxTabularLines?: number;
338
+ /**
339
+ * `lock_timeout` of a command transaction in milliseconds (integer ≥ 1);
340
+ * default 5 000. A lock wait past it rejects with `command.busy`.
341
+ */
342
+ lockTimeoutMs?: number;
343
+ /**
344
+ * Signal phases of one command transaction, `ctx.run` phases included,
345
+ * that each send a row signal (integer ≥ 1); default 90. The phases
346
+ * after it run in signal merge mode: one `invalidate` per (scope, object)
347
+ * pair instead of a signal per phase (P4-B spec §8.2). Keep it below the
348
+ * channel history size, so the signals of one pair fit the history and a
349
+ * short gap still recovers.
350
+ */
351
+ signalMergeThreshold?: number;
76
352
  /** Receives errors that never leave the runtime; default `console.error`. */
77
353
  log?: (entry: LogEntry) => void;
78
354
  }
355
+ /** Options of one {@link CommandRuntime.run} call. */
356
+ interface CommandRunOptions {
357
+ /**
358
+ * A tabular section array of `update` replaces the section as given:
359
+ * existing rows it leaves out are deleted. Without it (the default) such
360
+ * rows must be named in `deleteIds`, or the phase fails with
361
+ * `command.invalid` `reason: "tabular-rows-missing"`. `ctx.run` is always
362
+ * strict. An operation with `deleteIds` under this option is
363
+ * `command.invalid` with `path` `deleteIds`.
364
+ */
365
+ fullTabularArrays?: true;
366
+ }
367
+ /** The snapshot and its fingerprint, see {@link CommandRuntime.rightsSnapshot}. */
368
+ interface RightsSnapshotValue {
369
+ rightsVersion: string;
370
+ snapshot: RightsSnapshot;
371
+ }
372
+ /** The outcome of one part of {@link CommandRuntime.readParts}. */
373
+ type ReadPartOutcome = {
374
+ ok: true;
375
+ value: ReadPartValue;
376
+ } | {
377
+ ok: false;
378
+ error: CommandError;
379
+ };
380
+ /**
381
+ * The result of {@link CommandRuntime.readParts}: the row version epoch of
382
+ * its transaction (`null` without an epoch or without a transaction) and an
383
+ * outcome per part, in request order.
384
+ */
385
+ interface ReadPartsResult {
386
+ epoch: string | null;
387
+ items: ReadPartOutcome[];
388
+ }
389
+ /** Options of one {@link CommandRuntime.readParts} call. */
390
+ interface ReadPartsOptions {
391
+ /**
392
+ * Called after each part that read its value, before the next part runs;
393
+ * `"overflow"` stops the transaction there: the parts after it fail with
394
+ * `command.unavailable` `reason: "batch-budget"` without running, and the
395
+ * part keeps its value for the caller to cut or drop.
396
+ */
397
+ fit?: (index: number, value: ReadPartValue) => "accept" | "overflow";
398
+ }
79
399
  /** The command runtime of one catalog and database. */
80
400
  interface CommandRuntime {
401
+ /**
402
+ * The runtime catalog the runtime was created with: parsed by
403
+ * `runtimeCatalogSchema`, the runtime's own deep-frozen copy.
404
+ */
405
+ readonly catalog: RuntimeCatalog;
81
406
  /** Runs an operation or a batch in one transaction; rejects with `CommandFailure`. */
82
- run(session: SessionClaims, input: Operation | readonly Operation[]): Promise<CommandResult>;
407
+ run(session: SessionClaims, input: Operation | readonly Operation[], options?: CommandRunOptions): Promise<CommandResult>;
83
408
  /**
84
409
  * Reads rows under the request role of the profile, or through the
85
410
  * fallback path (P4 spec §6.11); rejects with `CommandFailure`.
86
411
  */
87
- read(session: SessionClaims, query: ReadQuery): Promise<Record<string, unknown>[]>;
412
+ read<Q extends ReadQuery>(session: SessionClaims, query: Q): Promise<ReadResultOf<Q>>;
413
+ /**
414
+ * Reads the parts in one `REPEATABLE READ READ ONLY` transaction (P4-B spec
415
+ * §4.2): every part sees the same snapshot. An invalid part fails alone,
416
+ * before the database; past the deadline a part and those after it fail
417
+ * with `command.timeout`; a database error fails its part, and those after
418
+ * it fail with `command.unavailable` `reason: "batch-aborted"` (or without
419
+ * a reason on a lost connection). Rejects with `CommandFailure` for the
420
+ * whole request: `command.unauthenticated`, `command.invalid`
421
+ * `reason: "batch-too-large"` over `READ_BATCH_MAX` parts or
422
+ * `READ_BATCH_STATEMENTS_MAX` statements.
423
+ */
424
+ readParts(session: SessionClaims, parts: readonly ReadPart[], options?: ReadPartsOptions): Promise<ReadPartsResult>;
425
+ /**
426
+ * The rights snapshot of the session's user and its `rightsVersion` (P4-B
427
+ * spec §9.1), read as a one-part batch: one `REPEATABLE READ READ ONLY`
428
+ * transaction, one statement under the request role. An anonymous session
429
+ * with the profile's anonymous read role gets the empty snapshot without a
430
+ * database call. Rejects with `CommandFailure`: `command.unauthenticated`
431
+ * for an invalid session, or an anonymous one in a project without an
432
+ * anonymous read role; `command.invalid` when the
433
+ * catalog has no rights functions; `command.internal` when the function's
434
+ * output fails `rightsSnapshotSchema`.
435
+ */
436
+ rightsSnapshot(session: SessionClaims): Promise<RightsSnapshotValue>;
437
+ /**
438
+ * The signal channels the session may subscribe to (P4-B spec §8.3), as
439
+ * the `ChannelGrant` the token port of `simetra/server/signals` signs. One
440
+ * `READ ONLY` transaction under the request role asks `current_user_id()`
441
+ * and `signal_topic_allowed(<channel>, false)` for every channel.
442
+ * `subject` is that user id, not the raw `sub`; `null` — an anonymous
443
+ * session (no database call) or no valid user, and then no channels.
444
+ * `channels` — the allowed ones, sorted, without duplicates. Rejects with
445
+ * `CommandFailure`: `command.unauthenticated`; `command.invalid` before the
446
+ * database — over 256 channels (`reason:
447
+ * "batch-too-large"`) or a channel over `CENTRIFUGO_CHANNEL_MAX` UTF-8
448
+ * bytes (`reason: "too-large"`, `path` — its index).
449
+ */
450
+ authorizeChannels(session: SessionClaims, channels: readonly string[]): Promise<ChannelGrant>;
451
+ /**
452
+ * The pre-check of an upload (platform spec §8.2 step 2): one `READ ONLY`
453
+ * transaction under the request role asks `storage_headroom`, then, under
454
+ * the storage role, reads the database binding string (`instance`: the
455
+ * `storage_instance` uuid with the cluster `system_identifier`, the
456
+ * database oid and the WAL timeline; never cached, so a promotion or a
457
+ * restore of a live process is seen by the next upload). The caller passes
458
+ * it to `FileStore.put` as option `instance`. Returns the limits of the
459
+ * object's `storage` with the binding, or `null` — for a guest (no database
460
+ * call), an unknown object or one without `storage`, a scope that does not
461
+ * fit, and a refusal of the right or of the quota alike. The check is
462
+ * necessary, not sufficient: `attachFile` judges the row. Rejects with
463
+ * `CommandFailure`: `command.unauthenticated` for an invalid session; with
464
+ * `FileStoreError` `no-binding` when the runtime has not created the
465
+ * `storage_instance` row (it does so at start).
466
+ */
467
+ checkUpload(session: SessionClaims, input: CheckUploadInput): Promise<UploadLimits | null>;
468
+ /**
469
+ * Creates the row of an uploaded file (platform spec §8.2 step 4): one
470
+ * transaction — `file_attach` with the size and type under the storage
471
+ * role, then the `create` phase under the command role — with the retries
472
+ * and the budget of `run`. Rejects with `FileAttachFailure`:
473
+ * `commitUnknown` is `true` when `COMMIT` was sent and the session closed
474
+ * (the row may exist, the bytes must stay); otherwise the transaction is
475
+ * known to have rolled back and the caller deletes the bytes. The error
476
+ * `command.rejected` with `reason` `storage.<reason>` is a storage refusal.
477
+ */
478
+ attachFile(session: SessionClaims, input: AttachFileInput): Promise<CommandResult>;
479
+ /**
480
+ * The reconciliation of the byte store with the database (platform spec
481
+ * §8.2): the only place bytes are physically deleted. Refuses (deletes
482
+ * nothing, `report.refused`) for a bucket of another database, a marker of a
483
+ * copied or restored database, a database in recovery, or when the guard
484
+ * trips. Rejects with `command.nested` from inside a hook.
485
+ */
486
+ reconcileFiles(store: FileStore, options: ReconcileOptions): Promise<ReconcileReport>;
487
+ /**
488
+ * The operator command that makes the first binding of a bucket to this
489
+ * database: writes the marker only into a completely empty bucket and reads
490
+ * it back; the same marker is a no-op, another database's marker or objects
491
+ * without a marker are `FileStoreError` `foreign-bucket`. Uploads never bind
492
+ * (`no-binding` on an unbound bucket). Refused with `in-recovery` on a
493
+ * standby. Rejects with `command.nested` from inside a hook.
494
+ */
495
+ bindFileStore(store: FileStore): Promise<void>;
496
+ /**
497
+ * The operator command after a legitimate restore (dump/restore, PITR, a
498
+ * promoted replica): rewrites the bucket marker with the current binding of
499
+ * this database. Only a marker of the same `storage_instance` uuid is
500
+ * rewritten (`FileStoreError` `foreign-bucket` otherwise); refused with
501
+ * `in-recovery` on a standby. Reads the binding fresh from the database.
502
+ * Rejects with `command.nested` from inside a hook.
503
+ */
504
+ rebindFileStore(store: FileStore): Promise<void>;
505
+ /**
506
+ * Accepts an invitation by its secret (invitations spec §5) in a command
507
+ * transaction of its own. The origin is checked first: a foreign origin
508
+ * and `inProcess` alike are `command.forbidden` `reason: "origin"`, before
509
+ * the database. Rejects with `CommandFailure` before the database:
510
+ * `command.invalid` in a catalog without invitations, `command.forbidden`
511
+ * for a session without a user (invalid, no `sub`), an anonymous one or
512
+ * one with the `act` claim,
513
+ * `invitation.invalid` for a secret that is not 43 base64url characters.
514
+ * The database answer is committed whatever it is, then mapped: an unknown,
515
+ * expired, used or changed secret alike — `invitation.invalid`;
516
+ * `invitation.already-member`; `invitation.rate-limited`;
517
+ * `command.forbidden` when the database sees no actor.
518
+ */
519
+ acceptInvitation(session: SessionClaims, secret: string, origin: RequestOrigin): Promise<AcceptedInvitation>;
520
+ /**
521
+ * The scopes the session's user is a member of (invitations spec §7):
522
+ * `rights_my_scopes()` and the root row of each scope, read in one
523
+ * `REPEATABLE READ READ ONLY` transaction under the request role; a root
524
+ * the user cannot read is `null`. `inProcess` is allowed, as for reads. An
525
+ * anonymous session gets `[]` without a database call. Rejects with
526
+ * `CommandFailure`: `command.forbidden` `reason: "origin"`,
527
+ * `command.invalid` in a catalog without invitations,
528
+ * `command.unauthenticated` for an invalid session.
529
+ */
530
+ workspaces(session: SessionClaims, origin: RequestOrigin): Promise<Workspace[]>;
88
531
  }
532
+ /** The membership an accepted invitation created. */
533
+ interface AcceptedInvitation {
534
+ /** The scope kind id. */
535
+ scopeKind: string;
536
+ scope: string;
537
+ /** The member row id. */
538
+ member: string;
539
+ }
540
+ /** One scope of {@link CommandRuntime.workspaces}. */
541
+ interface Workspace {
542
+ /** The scope kind id. */
543
+ scopeKind: string;
544
+ scope: string;
545
+ /** The user's member row id. */
546
+ member: string;
547
+ /** The root row of the scope by logical names; `null` — not readable. */
548
+ root: Record<string, unknown> | null;
549
+ }
550
+ /**
551
+ * The request role of `purpose` the server reads under for a provider
552
+ * profile; `undefined` — the profile names none (P4 spec Рт18). Таблиці —
553
+ * параметри, щоб правило перевірялося на підставлених профілях.
554
+ */
555
+ export declare function readRoleOf(provider: DatabaseProvider, purposes?: Readonly<Record<DatabaseProvider, readonly RequestRolePurpose[]>>, roles?: Readonly<Record<DatabaseProvider, ProviderApiRoles>>, purpose?: RequestRolePurpose): string | undefined;
89
556
  /**
90
- * The request role the server reads under for a provider profile;
91
- * `undefined` — the profile names none (P4 spec Рт18). Таблиці — параметри,
92
- * щоб правило перевірялося на підставлених профілях.
557
+ * The kind of a session by the anonymous claim of the provider
558
+ * (`PROVIDER_IDENTITY_SOURCES[provider].anonymousClaim`): `true` or `"true"`
559
+ * — `"anonymous"`, `false` or `"false"` — `"user"`, any other value or none —
560
+ * `"invalid"`. A provider without anonymous sessions reads every session as
561
+ * `"user"`. `sources` is a parameter so the rule is testable on a substituted
562
+ * profile.
93
563
  */
94
- export declare function readRoleOf(provider: DatabaseProvider, purposes?: Readonly<Record<DatabaseProvider, readonly RequestRolePurpose[]>>, roles?: Readonly<Record<DatabaseProvider, ProviderApiRoles>>): string | undefined;
564
+ export declare function sessionKind(provider: DatabaseProvider, claims: SessionClaims, sources?: Readonly<Record<DatabaseProvider, IdentitySource>>): "user" | "anonymous" | "invalid";
95
565
  /**
96
566
  * Creates the command runtime (P4 spec §6.5): validates the catalog and the
97
- * object modules, checks the applied snapshot hash and the request-role
98
- * membership in one read-only transaction. Rejects with `CommandFailure`
99
- * (`command.model-mismatch`, `command.read-role-missing`, …); an invalid
567
+ * object modules, checks the facts of the login role, the request-role
568
+ * membership and the applied snapshot hash in one read-only transaction.
569
+ * Rejects with `CommandFailure` (`command.privileged-login`,
570
+ * `command.model-mismatch`, `command.read-role-missing`, …); an invalid
100
571
  * catalog or module map throws before any database call.
101
572
  */
102
573
  export declare function createCommandRuntime(options: CommandRuntimeOptions): Promise<CommandRuntime>;
103
- export type { CommandDatabase, CommandRuntime, CommandRuntimeOptions, DatabaseClient, LogEntry, PgPoolLike };
574
+ /**
575
+ * Creates the data handler of the transport (P4-B spec §4.5): checks the
576
+ * request origin, the envelope, the session and the compatibility with the
577
+ * runtime catalog, maps the wire form to the logical one, calls the runtime
578
+ * and fits the encoded value into the response budget. Every response
579
+ * carries `serverHash` — the catalog's `snapshotHash`. A `CommandFailure`
580
+ * becomes an error value in wire form; any other exception is
581
+ * `command.internal` with no text and goes to `log` (default
582
+ * `console.error`). The handler keeps no state between calls.
583
+ */
584
+ export declare function createDataHandler(runtime: CommandRuntime, options?: {
585
+ log?: (error: unknown) => void;
586
+ }): (session: SessionClaims, request: unknown, origin: RequestOrigin) => Promise<DataResponse>;
587
+ /** The verb of an agent write tool. */
588
+ type AgentVerb = "write" | "remove";
589
+ /** The verb of every runtime operation. */
590
+ export declare const OPERATION_VERBS: Readonly<Record<ObjectOperation, AgentVerb>>;
591
+ /** An attribute in a description: what an agent needs to build a query and values. */
592
+ interface AgentAttributeDescription {
593
+ name: string;
594
+ type: string;
595
+ array?: true;
596
+ required: boolean;
597
+ maxLength?: number;
598
+ /** May be set on create / on update. */
599
+ insert: boolean;
600
+ update: boolean;
601
+ generated?: true;
602
+ enumValues?: {
603
+ name: string;
604
+ label: string;
605
+ }[];
606
+ /** The target of a single-target `Ref`. */
607
+ ref?: MetadataRef;
608
+ /** The targets of a polymorphic `Ref` (`allowedTypes`). */
609
+ allowedTypes?: MetadataRef[];
610
+ title?: LocalizedString;
611
+ description?: LocalizedString;
612
+ }
613
+ interface AgentObjectDescription {
614
+ object: MetadataRef;
615
+ kindLabel: string;
616
+ title?: LocalizedString;
617
+ description?: LocalizedString;
618
+ /** The logical name of the row key and the presentation attribute. */
619
+ key: string;
620
+ presentation?: string;
621
+ attributes: AgentAttributeDescription[];
622
+ tabularSections: {
623
+ name: string;
624
+ title?: LocalizedString;
625
+ attributes: AgentAttributeDescription[];
626
+ }[];
627
+ verbs: AgentVerb[];
628
+ operations: ObjectOperation[];
629
+ }
630
+ /** A list entry: an object without its fields. */
631
+ interface AgentObjectSummary {
632
+ object: MetadataRef;
633
+ title?: LocalizedString;
634
+ description?: LocalizedString;
635
+ verbs: AgentVerb[];
636
+ operations: ObjectOperation[];
637
+ }
638
+ /** A named object is not in the runtime catalog (`catalog.unknown-object`). */
639
+ export declare class AgentUnknownObject extends Error {
640
+ readonly object: MetadataRef;
641
+ constructor(object: MetadataRef);
642
+ }
643
+ interface AgentCorePermissions {
644
+ /** Permission to write rights: rights catalogs and a scope root with a creator. */
645
+ rightsWrite?: boolean;
646
+ }
647
+ /** What the catalog needs from a command runtime. */
648
+ interface AgentRuntime {
649
+ readonly catalog: RuntimeCatalog;
650
+ run(session: SessionClaims, input: readonly Batch[number][]): Promise<CommandResult>;
651
+ read(session: SessionClaims, query: ReadQuery): Promise<ReadResult>;
652
+ }
653
+ interface AgentCoreOptions {
654
+ runtime: AgentRuntime;
655
+ permissions?: AgentCorePermissions;
656
+ }
657
+ /**
658
+ * The core of the agent tool catalog: data in JSON form, with no presentation
659
+ * limits. It calls only the command runtime methods; there is no other path to
660
+ * the database. A refusal is the runtime's `CommandFailure`, the guard's
661
+ * `AgentWriteRefused` or `AgentUnknownObject`.
662
+ */
663
+ interface AgentCore {
664
+ /** Without a name: every catalog object; with a name: that object's description. */
665
+ describe(): {
666
+ objects: AgentObjectSummary[];
667
+ };
668
+ describe(object: MetadataRef): AgentObjectDescription;
669
+ describe(object?: MetadataRef): {
670
+ objects: AgentObjectSummary[];
671
+ } | AgentObjectDescription;
672
+ read(session: SessionClaims, query: ReadQuery): Promise<unknown>;
673
+ /** Runs a batch of one or more objects; every verb goes through this one point. */
674
+ execute(session: SessionClaims, batch: Batch): Promise<unknown>;
675
+ }
676
+ export declare function createAgentCore(options: AgentCoreOptions): AgentCore;
677
+ /** The closed set of codes an agent tool result may carry. */
678
+ export declare const AGENT_ERROR_CODES: readonly ["command.forbidden", "command.conflict", "command.invalid", "command.constraint", "command.context", "command.unauthenticated", "command.rejected", "command.nested", "command.depth", "command.retry-exhausted", "command.model-mismatch", "command.read-role-missing", "command.privileged-login", "command.unavailable", "command.timeout", "command.busy", "command.stale-client", "command.internal", "invitation.invalid", "invitation.already-member", "invitation.rate-limited", "invitation.not-pending", "catalog.invalid-input", "catalog.unknown-tool", "catalog.unknown-object", "catalog.rights-write-refused", "catalog.result-too-large"];
679
+ type AgentErrorCode = (typeof AGENT_ERROR_CODES)[number];
680
+ /**
681
+ * The next step for an agent: `retry` — the same call may work later;
682
+ * `ask_user` — a human has to decide or fix something; `fix_input` — change
683
+ * the call and send it again.
684
+ */
685
+ type AgentOutcome = "retry" | "ask_user" | "fix_input";
686
+ /** The outcome of every error code. */
687
+ export declare const AGENT_OUTCOMES: Readonly<Record<AgentErrorCode, AgentOutcome>>;
688
+ /** An error result of a tool: always with `hint` and `outcome`. */
689
+ interface AgentToolError {
690
+ code: AgentErrorCode;
691
+ message: string;
692
+ hint: string;
693
+ outcome: AgentOutcome;
694
+ /** Logical path of the offending input (`catalog.invalid-input`). */
695
+ path?: string;
696
+ /** The runtime's error, intact (`command.*` codes). */
697
+ error?: CommandError;
698
+ }
699
+ /**
700
+ * `awaiting_confirmation` is reserved for a two-step write confirmed by a
701
+ * human (ADR-0104); the first release never returns it.
702
+ */
703
+ type AgentToolState = "done" | "awaiting_confirmation";
704
+ /** A successful tool result. */
705
+ interface AgentToolSuccess {
706
+ state: AgentToolState;
707
+ data?: unknown;
708
+ /** The result was cut to fit the size limit. */
709
+ truncated?: true;
710
+ /** Where the next page of a cut `read` starts. */
711
+ continuation?: {
712
+ offset: number;
713
+ };
714
+ /** How to get the rest of a cut result. */
715
+ hint?: string;
716
+ }
717
+ type AgentToolResult = AgentToolSuccess | AgentToolError;
718
+ /** A tool result in the shape of an MCP `CallToolResult`. */
719
+ interface AgentMcpResult {
720
+ structuredContent?: AgentToolSuccess;
721
+ content: [{
722
+ type: "text";
723
+ text: string;
724
+ }];
725
+ isError?: true;
726
+ }
727
+ /**
728
+ * Presents a result for MCP without the SDK. Clients show the model different
729
+ * parts, so both are self-contained: `structuredContent` is the result object
730
+ * and `content` its full JSON text. An error carries only `content`: clients
731
+ * show nothing else when `isError` is set.
732
+ */
733
+ export declare function agentResultToMcp(result: AgentToolResult): AgentMcpResult;
734
+ /** MCP tool annotations; every one is explicit, the MCP defaults are unsafe. */
735
+ interface AgentToolAnnotations {
736
+ readOnlyHint: boolean;
737
+ destructiveHint: boolean;
738
+ idempotentHint: boolean;
739
+ openWorldHint: false;
740
+ }
741
+ /** A tool of the catalog: what an adapter lists in `tools/list`. */
742
+ interface AgentTool {
743
+ /** Matches `^[a-z][a-z0-9_]{0,47}$`. */
744
+ name: string;
745
+ title: string;
746
+ /** At most 4096 characters. */
747
+ description: string;
748
+ /** The input schema; the adapter derives the JSON Schema from it. */
749
+ input: z.ZodType;
750
+ annotations: AgentToolAnnotations;
751
+ }
752
+ /**
753
+ * Converts runtime values to JSON: `bigint` becomes a decimal string, which
754
+ * the `BigInt` input of T0 accepts back. The single place of this conversion.
755
+ */
756
+ export declare function toJson(value: unknown): unknown;
757
+ /** The guard refused a batch that writes rights without permission; carries the object. */
758
+ export declare class AgentWriteRefused extends Error {
759
+ readonly object: MetadataRef;
760
+ constructor(object: MetadataRef);
761
+ }
762
+ /**
763
+ * The rights-write guard: a pure function over the runtime catalog and a batch,
764
+ * so an adapter can call it before opening a pool. It refuses when any
765
+ * operation of the batch (not only the first) touches a rights system catalog
766
+ * (its operations have the `administerRights` context), creates a scope root
767
+ * with a creator or issues an invitation. An object outside the catalog is
768
+ * skipped: the runtime schema rejects it. Without `rightsWrite` the refusal
769
+ * comes before the database.
770
+ */
771
+ export declare function agentWriteRefusal(catalog: RuntimeCatalog, batch: Batch, permissions: {
772
+ rightsWrite: boolean;
773
+ }): {
774
+ object: MetadataRef;
775
+ } | undefined;
776
+ interface AgentToolCatalogOptions {
777
+ runtime: CommandRuntime;
778
+ /** Given at creation, not per call: no write path goes around the guard. */
779
+ permissions?: AgentCorePermissions;
780
+ /** Size limit of a result text in characters; default 44 000. */
781
+ maxResultChars?: number;
782
+ }
783
+ /**
784
+ * The agent tool catalog: the tool layer (`tools`, `call`) over the core
785
+ * (`describe`, `read`, `execute`, data in JSON form).
786
+ */
787
+ interface AgentToolCatalog extends AgentCore {
788
+ readonly tools: readonly AgentTool[];
789
+ call(session: SessionClaims, name: string, input: unknown): Promise<AgentToolResult>;
790
+ }
791
+ export declare function createAgentToolCatalog(options: AgentToolCatalogOptions): AgentToolCatalog;
792
+ export type { AcceptedInvitation, AgentAttributeDescription, AgentCore, AgentCoreOptions, AgentCorePermissions, AgentErrorCode, AgentMcpResult, AgentObjectDescription, AgentObjectSummary, AgentOutcome, AgentTool, AgentToolAnnotations, AgentToolCatalog, AgentToolCatalogOptions, AgentToolError, AgentToolResult, AgentToolState, AgentToolSuccess, AgentVerb, AttachFileInput, CheckUploadInput, CommandDatabase, CommandRunOptions, CommandRuntime, CommandRuntimeOptions, DatabaseClient, FileStore, LogEntry, PgPoolLike, ReadPartOutcome, ReadPartsOptions, ReadPartsResult, ReconcileLogEntry, ReconcileOptions, ReconcileRefusal, ReconcileReport, RequestOrigin, S3ClientLike, UploadLimits, Workspace };