@abloatai/ablo 0.27.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +59 -3
  2. package/README.md +1 -1
  3. package/dist/BaseSyncedStore.js +8 -9
  4. package/dist/Database.d.ts +14 -1
  5. package/dist/Database.js +228 -28
  6. package/dist/Model.d.ts +17 -0
  7. package/dist/Model.js +32 -1
  8. package/dist/SyncClient.d.ts +10 -6
  9. package/dist/SyncClient.js +390 -75
  10. package/dist/adapters/inMemoryStorage.d.ts +1 -0
  11. package/dist/adapters/inMemoryStorage.js +29 -13
  12. package/dist/ai-sdk/coordinatedTool.d.ts +15 -2
  13. package/dist/auth/schemas.d.ts +6 -0
  14. package/dist/auth/schemas.js +7 -0
  15. package/dist/cli.cjs +821 -402
  16. package/dist/client/Ablo.d.ts +53 -24
  17. package/dist/client/Ablo.js +12 -199
  18. package/dist/client/claimHeartbeatLoop.d.ts +1 -1
  19. package/dist/client/claimHeartbeatLoop.js +1 -1
  20. package/dist/client/createInternalComponents.d.ts +4 -0
  21. package/dist/client/createInternalComponents.js +3 -1
  22. package/dist/client/durableWrites.d.ts +21 -0
  23. package/dist/client/durableWrites.js +46 -0
  24. package/dist/client/httpClient.d.ts +21 -45
  25. package/dist/client/httpClient.js +104 -26
  26. package/dist/client/httpTransport.d.ts +8 -0
  27. package/dist/client/{ApiClient.js → httpTransport.js} +361 -308
  28. package/dist/client/modelRegistration.js +11 -0
  29. package/dist/client/options.d.ts +54 -7
  30. package/dist/client/options.js +3 -2
  31. package/dist/client/resourceTypes.d.ts +9 -85
  32. package/dist/client/resourceTypes.js +1 -1
  33. package/dist/client/sessionMint.d.ts +5 -6
  34. package/dist/client/sessionMint.js +4 -5
  35. package/dist/client/validateAbloOptions.js +3 -3
  36. package/dist/client/wsMutationExecutor.d.ts +3 -2
  37. package/dist/client/wsMutationExecutor.js +3 -2
  38. package/dist/coordination/schema.d.ts +30 -0
  39. package/dist/coordination/schema.js +14 -0
  40. package/dist/core/StoreManager.d.ts +2 -0
  41. package/dist/core/StoreManager.js +12 -0
  42. package/dist/core/index.d.ts +1 -1
  43. package/dist/errorCodes.js +6 -2
  44. package/dist/errors.d.ts +4 -40
  45. package/dist/errors.js +5 -5
  46. package/dist/index.d.ts +20 -8
  47. package/dist/index.js +9 -5
  48. package/dist/interfaces/index.d.ts +5 -2
  49. package/dist/mutators/UndoManager.d.ts +2 -0
  50. package/dist/mutators/UndoManager.js +32 -0
  51. package/dist/mutators/defineMutators.d.ts +18 -0
  52. package/dist/mutators/defineMutators.js +4 -8
  53. package/dist/react/index.d.ts +1 -1
  54. package/dist/react/useAblo.d.ts +6 -4
  55. package/dist/react/useAblo.js +25 -3
  56. package/dist/schema/index.d.ts +2 -2
  57. package/dist/schema/index.js +1 -1
  58. package/dist/schema/schema.d.ts +31 -1
  59. package/dist/schema/select.d.ts +15 -0
  60. package/dist/schema/select.js +27 -3
  61. package/dist/source/connector.d.ts +3 -3
  62. package/dist/source/factory.d.ts +4 -6
  63. package/dist/source/factory.js +4 -7
  64. package/dist/source/index.d.ts +4 -4
  65. package/dist/source/index.js +2 -2
  66. package/dist/source/signing.d.ts +0 -3
  67. package/dist/source/types.d.ts +0 -26
  68. package/dist/stores/ObjectStore.d.ts +14 -1
  69. package/dist/stores/ObjectStore.js +33 -10
  70. package/dist/stores/ObjectStoreContract.d.ts +2 -0
  71. package/dist/surface.d.ts +1 -1
  72. package/dist/surface.js +3 -0
  73. package/dist/sync/BootstrapFetcher.d.ts +10 -0
  74. package/dist/sync/BootstrapFetcher.js +27 -4
  75. package/dist/sync/SyncWebSocket.d.ts +2 -1
  76. package/dist/sync/createClaimStream.d.ts +11 -2
  77. package/dist/sync/createClaimStream.js +4 -3
  78. package/dist/sync/persistedPrefix.d.ts +12 -0
  79. package/dist/sync/persistedPrefix.js +22 -0
  80. package/dist/testing/index.d.ts +2 -0
  81. package/dist/testing/index.js +1 -0
  82. package/dist/testing/mocks/FakeDatabase.d.ts +18 -0
  83. package/dist/testing/mocks/FakeDatabase.js +10 -0
  84. package/dist/testing/mocks/MockWebSocket.d.ts +2 -1
  85. package/dist/transactions/TransactionQueue.d.ts +66 -8
  86. package/dist/transactions/TransactionQueue.js +607 -89
  87. package/dist/transactions/commitEnvelope.d.ts +132 -0
  88. package/dist/transactions/commitEnvelope.js +139 -0
  89. package/dist/transactions/commitOutboxStore.d.ts +32 -0
  90. package/dist/transactions/commitOutboxStore.js +26 -0
  91. package/dist/transactions/commitPayload.d.ts +15 -0
  92. package/dist/transactions/commitPayload.js +6 -0
  93. package/dist/transactions/durableWriteStore.d.ts +123 -0
  94. package/dist/transactions/durableWriteStore.js +30 -0
  95. package/dist/transactions/httpCommitEnvelope.d.ts +44 -0
  96. package/dist/transactions/httpCommitEnvelope.js +181 -0
  97. package/dist/transactions/idempotencyKey.d.ts +10 -0
  98. package/dist/transactions/idempotencyKey.js +9 -0
  99. package/dist/transactions/replayValidation.d.ts +83 -0
  100. package/dist/transactions/replayValidation.js +46 -1
  101. package/dist/types/global.d.ts +10 -29
  102. package/dist/types/global.js +4 -7
  103. package/dist/types/streams.d.ts +2 -28
  104. package/dist/wire/bootstrapReason.d.ts +9 -0
  105. package/dist/wire/bootstrapReason.js +8 -0
  106. package/dist/wire/frames.d.ts +6 -21
  107. package/dist/wire/frames.js +4 -4
  108. package/dist/wire/index.d.ts +6 -3
  109. package/dist/wire/index.js +3 -2
  110. package/dist/wire/protocolVersion.d.ts +30 -17
  111. package/dist/wire/protocolVersion.js +34 -18
  112. package/docs/agents.md +8 -3
  113. package/docs/api.md +16 -14
  114. package/docs/client-behavior.md +6 -3
  115. package/docs/coordination.md +4 -5
  116. package/docs/data-sources.md +5 -8
  117. package/docs/guarantees.md +21 -0
  118. package/docs/integration-guide.md +1 -0
  119. package/docs/mcp.md +1 -1
  120. package/docs/migration.md +21 -1
  121. package/docs/quickstart.md +11 -0
  122. package/docs/react.md +0 -46
  123. package/examples/README.md +6 -5
  124. package/llms.txt +15 -15
  125. package/package.json +3 -3
  126. package/dist/client/ApiClient.d.ts +0 -177
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Runtime contracts for retry-safe commits.
3
+ *
4
+ * `commitEnvelopeMemberSchema` is the compact pointer stored on an in-memory
5
+ * transaction. `durableCommitEnvelopeSchema` is the actual outbox record: one
6
+ * atomic IndexedDB value containing the stable request key, exact ordered wire
7
+ * operations, and the source mutations it supersedes.
8
+ */
9
+ import { z } from 'zod';
10
+ export declare const COMMIT_ENVELOPE_VERSION: 1;
11
+ export declare const COMMIT_ENVELOPE_RECORD_PREFIX = "commit-envelope:";
12
+ /** One transaction's position in a commit; this is not the envelope itself. */
13
+ export declare const commitEnvelopeMemberSchema: z.ZodObject<{
14
+ idempotencyKey: z.core.$ZodBranded<z.ZodString, "IdempotencyKey", "out">;
15
+ operationIndex: z.ZodNumber;
16
+ operationCount: z.ZodNumber;
17
+ sealedAt: z.ZodOptional<z.ZodNumber>;
18
+ sequence: z.ZodOptional<z.ZodNumber>;
19
+ }, z.core.$strict>;
20
+ export type CommitEnvelopeMember = z.infer<typeof commitEnvelopeMemberSchema>;
21
+ /** One operation stored exactly as the current commit transport sends it. */
22
+ export declare const durableCommitOperationSchema: z.ZodObject<{
23
+ type: z.ZodEnum<{
24
+ CREATE: "CREATE";
25
+ UPDATE: "UPDATE";
26
+ DELETE: "DELETE";
27
+ ARCHIVE: "ARCHIVE";
28
+ UNARCHIVE: "UNARCHIVE";
29
+ }>;
30
+ readAt: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
31
+ onStale: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
32
+ reject: "reject";
33
+ overwrite: "overwrite";
34
+ notify: "notify";
35
+ }>>>;
36
+ model: z.ZodString;
37
+ id: z.ZodString;
38
+ input: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
39
+ transactionId: z.ZodOptional<z.ZodString>;
40
+ options: z.ZodOptional<z.ZodObject<{
41
+ idempotencyKey: z.ZodOptional<z.ZodNullable<z.ZodString>>;
42
+ label: z.ZodOptional<z.ZodString>;
43
+ }, z.core.$strict>>;
44
+ }, z.core.$strip>;
45
+ export type DurableCommitOperation = z.infer<typeof durableCommitOperationSchema>;
46
+ export type DurableCommitOperationInput = z.input<typeof durableCommitOperationSchema>;
47
+ export declare const commitOutboxScopeSchema: z.ZodObject<{
48
+ organizationId: z.ZodString;
49
+ participantId: z.ZodString;
50
+ namespace: z.ZodString;
51
+ }, z.core.$strict>;
52
+ export type CommitOutboxScope = z.infer<typeof commitOutboxScopeSchema>;
53
+ /**
54
+ * One crash-durable logical commit. Keeping every operation in one record makes
55
+ * membership and order atomic: recovery can observe the old record or the new
56
+ * record, never half an envelope.
57
+ */
58
+ export declare const durableCommitEnvelopeSchema: z.ZodObject<{
59
+ id: z.ZodString;
60
+ type: z.ZodLiteral<"commit_envelope">;
61
+ storageVersion: z.ZodLiteral<1>;
62
+ origin: z.ZodEnum<{
63
+ model_batch: "model_batch";
64
+ atomic_commit: "atomic_commit";
65
+ }>;
66
+ idempotencyKey: z.core.$ZodBranded<z.ZodString, "IdempotencyKey", "out">;
67
+ operations: z.ZodArray<z.ZodObject<{
68
+ type: z.ZodEnum<{
69
+ CREATE: "CREATE";
70
+ UPDATE: "UPDATE";
71
+ DELETE: "DELETE";
72
+ ARCHIVE: "ARCHIVE";
73
+ UNARCHIVE: "UNARCHIVE";
74
+ }>;
75
+ readAt: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
76
+ onStale: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
77
+ reject: "reject";
78
+ overwrite: "overwrite";
79
+ notify: "notify";
80
+ }>>>;
81
+ model: z.ZodString;
82
+ id: z.ZodString;
83
+ input: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
84
+ transactionId: z.ZodOptional<z.ZodString>;
85
+ options: z.ZodOptional<z.ZodObject<{
86
+ idempotencyKey: z.ZodOptional<z.ZodNullable<z.ZodString>>;
87
+ label: z.ZodOptional<z.ZodString>;
88
+ }, z.core.$strict>>;
89
+ }, z.core.$strip>>;
90
+ sourceMutationIds: z.ZodDefault<z.ZodArray<z.ZodString>>;
91
+ commitOptions: z.ZodDefault<z.ZodObject<{
92
+ causedByTaskId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
93
+ reads: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
94
+ model: z.ZodString;
95
+ id: z.ZodString;
96
+ readAt: z.ZodNumber;
97
+ fields: z.ZodOptional<z.ZodArray<z.ZodString>>;
98
+ onStale: z.ZodOptional<z.ZodEnum<{
99
+ reject: "reject";
100
+ overwrite: "overwrite";
101
+ notify: "notify";
102
+ }>>;
103
+ }, z.core.$strip>, z.ZodObject<{
104
+ group: z.ZodString;
105
+ readAt: z.ZodNumber;
106
+ onStale: z.ZodOptional<z.ZodEnum<{
107
+ reject: "reject";
108
+ overwrite: "overwrite";
109
+ notify: "notify";
110
+ }>>;
111
+ }, z.core.$strip>]>>>>;
112
+ }, z.core.$strict>>;
113
+ scope: z.ZodOptional<z.ZodObject<{
114
+ organizationId: z.ZodString;
115
+ participantId: z.ZodString;
116
+ namespace: z.ZodString;
117
+ }, z.core.$strict>>;
118
+ createdAt: z.ZodNumber;
119
+ sealedAt: z.ZodNumber;
120
+ sequence: z.ZodOptional<z.ZodNumber>;
121
+ timestamp: z.ZodNumber;
122
+ }, z.core.$strict>;
123
+ export type DurableCommitEnvelope = z.infer<typeof durableCommitEnvelopeSchema>;
124
+ export declare function commitEnvelopeRecordId(idempotencyKey: string): string;
125
+ /** Constructs validated member metadata when an in-memory batch is formed. */
126
+ export declare function createCommitEnvelopeMember(value: z.input<typeof commitEnvelopeMemberSchema>): CommitEnvelopeMember;
127
+ /**
128
+ * Freezes the exact JSON request that will be persisted and sent. The JSON
129
+ * round-trip deliberately applies the same Date/undefined semantics as the
130
+ * WebSocket transport before the request fingerprint becomes durable.
131
+ */
132
+ export declare function createDurableCommitEnvelope(value: Omit<z.input<typeof durableCommitEnvelopeSchema>, 'id' | 'type' | 'storageVersion' | 'timestamp'>): DurableCommitEnvelope;
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Runtime contracts for retry-safe commits.
3
+ *
4
+ * `commitEnvelopeMemberSchema` is the compact pointer stored on an in-memory
5
+ * transaction. `durableCommitEnvelopeSchema` is the actual outbox record: one
6
+ * atomic IndexedDB value containing the stable request key, exact ordered wire
7
+ * operations, and the source mutations it supersedes.
8
+ */
9
+ import { z } from 'zod';
10
+ import { readDependencySchema } from '../coordination/schema.js';
11
+ import { commitOperationSchema } from '../wire/frames.js';
12
+ import { idempotencyKeySchema } from './idempotencyKey.js';
13
+ export const COMMIT_ENVELOPE_VERSION = 1;
14
+ export const COMMIT_ENVELOPE_RECORD_PREFIX = 'commit-envelope:';
15
+ /** One transaction's position in a commit; this is not the envelope itself. */
16
+ export const commitEnvelopeMemberSchema = z
17
+ .strictObject({
18
+ idempotencyKey: idempotencyKeySchema,
19
+ operationIndex: z.number().int().nonnegative(),
20
+ operationCount: z.number().int().positive(),
21
+ sealedAt: z.number().int().nonnegative().optional(),
22
+ sequence: z.number().int().nonnegative().optional(),
23
+ })
24
+ .refine(({ operationIndex, operationCount }) => operationIndex < operationCount, { message: 'operationIndex must be smaller than operationCount' });
25
+ /** One operation stored exactly as the current commit transport sends it. */
26
+ export const durableCommitOperationSchema = commitOperationSchema
27
+ .pick({
28
+ type: true,
29
+ model: true,
30
+ id: true,
31
+ input: true,
32
+ transactionId: true,
33
+ readAt: true,
34
+ onStale: true,
35
+ })
36
+ .extend({
37
+ model: z.string().min(1),
38
+ id: z.string().min(1),
39
+ input: z.record(z.string(), z.unknown()).optional(),
40
+ transactionId: z.string().min(1).optional(),
41
+ options: z
42
+ .strictObject({
43
+ idempotencyKey: z.string().min(1).max(255).nullable().optional(),
44
+ label: z.string().min(1).max(255).optional(),
45
+ })
46
+ .optional(),
47
+ });
48
+ const durableCommitOptionsSchema = z.strictObject({
49
+ causedByTaskId: z.string().min(1).nullable().optional(),
50
+ reads: z.array(readDependencySchema).nullable().optional(),
51
+ });
52
+ export const commitOutboxScopeSchema = z.strictObject({
53
+ organizationId: z.string().min(1),
54
+ participantId: z.string().min(1),
55
+ namespace: z.string().min(1),
56
+ });
57
+ /**
58
+ * One crash-durable logical commit. Keeping every operation in one record makes
59
+ * membership and order atomic: recovery can observe the old record or the new
60
+ * record, never half an envelope.
61
+ */
62
+ export const durableCommitEnvelopeSchema = z
63
+ .strictObject({
64
+ id: z.string().startsWith(COMMIT_ENVELOPE_RECORD_PREFIX),
65
+ type: z.literal('commit_envelope'),
66
+ storageVersion: z.literal(COMMIT_ENVELOPE_VERSION),
67
+ origin: z.enum(['model_batch', 'atomic_commit']),
68
+ idempotencyKey: idempotencyKeySchema,
69
+ operations: z.array(durableCommitOperationSchema).min(1).max(500),
70
+ // Bookkeeping cardinality is independent of the 500 wire-operation cap:
71
+ // hundreds of same-row offline patches may coalesce into one operation.
72
+ sourceMutationIds: z.array(z.string().min(1)).default([]),
73
+ commitOptions: durableCommitOptionsSchema.default({}),
74
+ scope: commitOutboxScopeSchema.optional(),
75
+ createdAt: z.number().int().nonnegative(),
76
+ sealedAt: z.number().int().nonnegative(),
77
+ /** Monotonic within one client; disambiguates writes sealed in the same ms. */
78
+ sequence: z.number().int().nonnegative().optional(),
79
+ timestamp: z.number().int().nonnegative(),
80
+ })
81
+ .superRefine((envelope, context) => {
82
+ if (envelope.id !== commitEnvelopeRecordId(envelope.idempotencyKey)) {
83
+ context.addIssue({
84
+ code: 'custom',
85
+ path: ['id'],
86
+ message: 'Envelope record id must be derived from its idempotency key',
87
+ });
88
+ }
89
+ if (new Set(envelope.sourceMutationIds).size !== envelope.sourceMutationIds.length) {
90
+ context.addIssue({
91
+ code: 'custom',
92
+ path: ['sourceMutationIds'],
93
+ message: 'Source mutation ids must be unique',
94
+ });
95
+ }
96
+ if (envelope.origin === 'model_batch') {
97
+ const transactionIds = envelope.operations.map((operation) => operation.transactionId);
98
+ if (transactionIds.some((id) => typeof id !== 'string' || id.length === 0)) {
99
+ context.addIssue({
100
+ code: 'custom',
101
+ path: ['operations'],
102
+ message: 'Every model-batch operation must carry a transactionId',
103
+ });
104
+ }
105
+ else if (new Set(transactionIds).size !== transactionIds.length) {
106
+ context.addIssue({
107
+ code: 'custom',
108
+ path: ['operations'],
109
+ message: 'Model-batch transactionIds must be unique',
110
+ });
111
+ }
112
+ }
113
+ });
114
+ export function commitEnvelopeRecordId(idempotencyKey) {
115
+ return `${COMMIT_ENVELOPE_RECORD_PREFIX}${idempotencyKey}`;
116
+ }
117
+ /** Constructs validated member metadata when an in-memory batch is formed. */
118
+ export function createCommitEnvelopeMember(value) {
119
+ return commitEnvelopeMemberSchema.parse(value);
120
+ }
121
+ /**
122
+ * Freezes the exact JSON request that will be persisted and sent. The JSON
123
+ * round-trip deliberately applies the same Date/undefined semantics as the
124
+ * WebSocket transport before the request fingerprint becomes durable.
125
+ */
126
+ export function createDurableCommitEnvelope(value) {
127
+ const candidate = {
128
+ ...value,
129
+ id: commitEnvelopeRecordId(value.idempotencyKey),
130
+ type: 'commit_envelope',
131
+ storageVersion: COMMIT_ENVELOPE_VERSION,
132
+ timestamp: value.sealedAt,
133
+ };
134
+ const serialized = JSON.stringify(candidate);
135
+ if (serialized === undefined) {
136
+ throw new TypeError('Commit envelope is not JSON serializable');
137
+ }
138
+ return durableCommitEnvelopeSchema.parse(JSON.parse(serialized));
139
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Narrow persistence port for crash-durable commit envelopes.
3
+ *
4
+ * Browser clients use {@link DatabaseCommitOutboxStore}. Agent/Node hosts can
5
+ * inject a workflow-, SQLite-, or filesystem-backed implementation without
6
+ * coupling TransactionQueue to the browser database/cache implementation.
7
+ */
8
+ import type { DurableWriteStore, PendingWrite } from './durableWriteStore.js';
9
+ /** @deprecated Use {@link PendingWrite}. */
10
+ export type CommitOutboxRecord = PendingWrite;
11
+ /** @deprecated Use {@link DurableWriteStore}. */
12
+ export type CommitOutboxStore = DurableWriteStore;
13
+ /**
14
+ * The exact subset of the browser `Database` that {@link DatabaseCommitOutboxStore}
15
+ * drives. Typing the adapter to this narrow port instead of importing the
16
+ * concrete `Database` class keeps the outbox store off the
17
+ * `Database → DatabaseManager → ModelRegistry → BaseSyncedStore` import cycle;
18
+ * the real `Database` still satisfies it structurally, so callers are unchanged.
19
+ */
20
+ export interface CommitOutboxDatabase {
21
+ sealTransactionRecord(record: PendingWrite, consumedRecordIds: readonly string[]): Promise<unknown>;
22
+ getPersistedTransactions(): Promise<readonly unknown[]>;
23
+ removeTransaction(id: string): Promise<void>;
24
+ }
25
+ /** Strict IndexedDB adapter backed by Database's `__transactions` store. */
26
+ export declare class DatabaseCommitOutboxStore implements DurableWriteStore {
27
+ private readonly database;
28
+ constructor(database: CommitOutboxDatabase);
29
+ seal(envelope: PendingWrite, consumedRecordIds: readonly string[]): Promise<void>;
30
+ list(): Promise<readonly unknown[]>;
31
+ remove(envelopeRecordId: string): Promise<void>;
32
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Narrow persistence port for crash-durable commit envelopes.
3
+ *
4
+ * Browser clients use {@link DatabaseCommitOutboxStore}. Agent/Node hosts can
5
+ * inject a workflow-, SQLite-, or filesystem-backed implementation without
6
+ * coupling TransactionQueue to the browser database/cache implementation.
7
+ */
8
+ /** Strict IndexedDB adapter backed by Database's `__transactions` store. */
9
+ export class DatabaseCommitOutboxStore {
10
+ database;
11
+ constructor(database) {
12
+ this.database = database;
13
+ }
14
+ async seal(envelope, consumedRecordIds) {
15
+ // This adapter deliberately has no duck-typed fallback. Reporting a
16
+ // successful seal after a no-op or a non-atomic save/delete handoff would
17
+ // authorize network dispatch without the durability this port promises.
18
+ await this.database.sealTransactionRecord(envelope, consumedRecordIds);
19
+ }
20
+ async list() {
21
+ return this.database.getPersistedTransactions();
22
+ }
23
+ async remove(envelopeRecordId) {
24
+ await this.database.removeTransaction(envelopeRecordId);
25
+ }
26
+ }
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import { MutationOperationType } from '../types/index.js';
12
12
  import type { MutationOptions, WriteOptions } from '../interfaces/index.js';
13
+ import type { CommitEnvelopeMember } from './commitEnvelope.js';
13
14
  export interface UserContext {
14
15
  userId: string;
15
16
  organizationId: string;
@@ -55,6 +56,18 @@ export interface Transaction {
55
56
  priorityScore: number;
56
57
  writeOptions?: WriteOptions;
57
58
  batchId?: string;
59
+ /**
60
+ * Stable identity of the wire commit that currently owns this operation.
61
+ *
62
+ * A transport failure is ambiguous: the server may have committed the
63
+ * batch even though the acknowledgement never reached this client. Keeping
64
+ * this envelope on every member lets the queue replay the exact same ordered
65
+ * batch with the exact same idempotency key instead of accidentally
66
+ * re-batching its operations under a fresh key.
67
+ */
68
+ commitEnvelope?: CommitEnvelopeMember;
69
+ /** Pending-mutation journal entries atomically consumed by this envelope. */
70
+ sourceMutationIds?: string[];
58
71
  /** Completed locally without a server operation; no sync echo will arrive. */
59
72
  localOnly?: boolean;
60
73
  /** Sync-id threshold: the transaction confirms once a delta with an id at least this value arrives. */
@@ -90,6 +103,8 @@ export declare const stripModelSuffix: (modelName: string) => string;
90
103
  export declare const computePriorityScore: (type: Transaction["type"], modelName: string) => number;
91
104
  export declare const TX_TYPE_TO_MUTATION_OP: Record<Transaction['type'], MutationOperationType>;
92
105
  export declare function hasStaleWriteOptions(options?: WriteOptions): boolean;
106
+ /** Options whose identity/audit semantics forbid merging two caller writes. */
107
+ export declare function hasCommitCoalescingBarrier(options?: WriteOptions): boolean;
93
108
  export interface WriteOperationFields {
94
109
  readAt?: number | null;
95
110
  onStale?: 'reject' | 'overwrite' | 'notify' | null;
@@ -107,6 +107,12 @@ export function hasStaleWriteOptions(options) {
107
107
  return (options?.readAt !== undefined ||
108
108
  options?.onStale !== undefined);
109
109
  }
110
+ /** Options whose identity/audit semantics forbid merging two caller writes. */
111
+ export function hasCommitCoalescingBarrier(options) {
112
+ return (hasStaleWriteOptions(options) ||
113
+ typeof options?.idempotencyKey === 'string' ||
114
+ typeof options?.label === 'string');
115
+ }
110
116
  /**
111
117
  * Copies a transaction's `writeOptions` onto the wire operation. The
112
118
  * stale-context guards (`readAt` and `onStale`) sit at the operation's root,
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Product-facing persistence contract for writes that must survive a process
3
+ * restart or an ambiguous network response.
4
+ *
5
+ * The engine implements this contract with a transactional outbox internally,
6
+ * but callers should only need to think in terms of pending durable writes.
7
+ */
8
+ import { z } from 'zod';
9
+ /** Every write shape that Ablo may ask an injected store to persist. */
10
+ export declare const pendingWriteSchema: z.ZodUnion<readonly [z.ZodObject<{
11
+ id: z.ZodString;
12
+ type: z.ZodLiteral<"commit_envelope">;
13
+ storageVersion: z.ZodLiteral<1>;
14
+ origin: z.ZodEnum<{
15
+ model_batch: "model_batch";
16
+ atomic_commit: "atomic_commit";
17
+ }>;
18
+ idempotencyKey: z.core.$ZodBranded<z.ZodString, "IdempotencyKey", "out">;
19
+ operations: z.ZodArray<z.ZodObject<{
20
+ type: z.ZodEnum<{
21
+ CREATE: "CREATE";
22
+ UPDATE: "UPDATE";
23
+ DELETE: "DELETE";
24
+ ARCHIVE: "ARCHIVE";
25
+ UNARCHIVE: "UNARCHIVE";
26
+ }>;
27
+ readAt: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
28
+ onStale: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
29
+ reject: "reject";
30
+ overwrite: "overwrite";
31
+ notify: "notify";
32
+ }>>>;
33
+ model: z.ZodString;
34
+ id: z.ZodString;
35
+ input: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
36
+ transactionId: z.ZodOptional<z.ZodString>;
37
+ options: z.ZodOptional<z.ZodObject<{
38
+ idempotencyKey: z.ZodOptional<z.ZodNullable<z.ZodString>>;
39
+ label: z.ZodOptional<z.ZodString>;
40
+ }, z.core.$strict>>;
41
+ }, z.core.$strip>>;
42
+ sourceMutationIds: z.ZodDefault<z.ZodArray<z.ZodString>>;
43
+ commitOptions: z.ZodDefault<z.ZodObject<{
44
+ causedByTaskId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
45
+ reads: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
46
+ model: z.ZodString;
47
+ id: z.ZodString;
48
+ readAt: z.ZodNumber;
49
+ fields: z.ZodOptional<z.ZodArray<z.ZodString>>;
50
+ onStale: z.ZodOptional<z.ZodEnum<{
51
+ reject: "reject";
52
+ overwrite: "overwrite";
53
+ notify: "notify";
54
+ }>>;
55
+ }, z.core.$strip>, z.ZodObject<{
56
+ group: z.ZodString;
57
+ readAt: z.ZodNumber;
58
+ onStale: z.ZodOptional<z.ZodEnum<{
59
+ reject: "reject";
60
+ overwrite: "overwrite";
61
+ notify: "notify";
62
+ }>>;
63
+ }, z.core.$strip>]>>>>;
64
+ }, z.core.$strict>>;
65
+ scope: z.ZodOptional<z.ZodObject<{
66
+ organizationId: z.ZodString;
67
+ participantId: z.ZodString;
68
+ namespace: z.ZodString;
69
+ }, z.core.$strict>>;
70
+ createdAt: z.ZodNumber;
71
+ sealedAt: z.ZodNumber;
72
+ sequence: z.ZodOptional<z.ZodNumber>;
73
+ timestamp: z.ZodNumber;
74
+ }, z.core.$strict>, z.ZodObject<{
75
+ id: z.ZodString;
76
+ type: z.ZodLiteral<"http_commit_envelope">;
77
+ storageVersion: z.ZodLiteral<1>;
78
+ idempotencyKey: z.core.$ZodBranded<z.ZodString, "IdempotencyKey", "out">;
79
+ protocolVersion: z.ZodDefault<z.ZodNumber>;
80
+ request: z.ZodObject<{
81
+ method: z.ZodEnum<{
82
+ DELETE: "DELETE";
83
+ POST: "POST";
84
+ PATCH: "PATCH";
85
+ }>;
86
+ path: z.ZodString;
87
+ body: z.ZodString;
88
+ }, z.core.$strict>;
89
+ scopeNamespace: z.ZodString;
90
+ createdAt: z.ZodNumber;
91
+ sealedAt: z.ZodNumber;
92
+ sequence: z.ZodOptional<z.ZodNumber>;
93
+ timestamp: z.ZodNumber;
94
+ }, z.core.$strict>]>;
95
+ export type PendingWrite = z.infer<typeof pendingWriteSchema>;
96
+ /**
97
+ * Persistence port used by `Ablo({ durableWrites })`.
98
+ *
99
+ * `seal` is the durability boundary: it must atomically persist the exact write
100
+ * and consume the staged records that write supersedes. Resolving this promise
101
+ * authorizes Ablo to dispatch the request, so adapters must never report success
102
+ * before the data is durable.
103
+ */
104
+ export interface DurableWriteStore {
105
+ /**
106
+ * Atomically reserve a pending write and consume the staged records it owns.
107
+ * The same id + same request is idempotent; the same id + a different request
108
+ * must be rejected.
109
+ */
110
+ seal(write: PendingWrite, consumedRecordIds: readonly string[]): Promise<void>;
111
+ /** Load all unacknowledged writes. Stored data is treated as untrusted. */
112
+ list(): Promise<readonly unknown[]>;
113
+ /** Remove one write only after its outcome is definitive. */
114
+ remove(writeId: string): Promise<void>;
115
+ }
116
+ /** Runtime validation for injected adapters, including JavaScript consumers. */
117
+ export declare const durableWriteStoreSchema: z.ZodCustom<DurableWriteStore, DurableWriteStore>;
118
+ /** Options for crash-durable `create`, `update`, and `delete` calls. */
119
+ export declare const durableWritesConfigSchema: z.ZodObject<{
120
+ store: z.ZodCustom<DurableWriteStore, DurableWriteStore>;
121
+ namespace: z.ZodOptional<z.ZodString>;
122
+ }, z.core.$strict>;
123
+ export type DurableWritesConfig = z.infer<typeof durableWritesConfigSchema>;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Product-facing persistence contract for writes that must survive a process
3
+ * restart or an ambiguous network response.
4
+ *
5
+ * The engine implements this contract with a transactional outbox internally,
6
+ * but callers should only need to think in terms of pending durable writes.
7
+ */
8
+ import { z } from 'zod';
9
+ import { durableCommitEnvelopeSchema } from './commitEnvelope.js';
10
+ import { durableHttpCommitEnvelopeSchema } from './httpCommitEnvelope.js';
11
+ /** Every write shape that Ablo may ask an injected store to persist. */
12
+ export const pendingWriteSchema = z.union([
13
+ durableCommitEnvelopeSchema,
14
+ durableHttpCommitEnvelopeSchema,
15
+ ]);
16
+ /** Runtime validation for injected adapters, including JavaScript consumers. */
17
+ export const durableWriteStoreSchema = z.custom((value) => {
18
+ if (typeof value !== 'object' || value === null)
19
+ return false;
20
+ const candidate = value;
21
+ return (typeof candidate.seal === 'function' &&
22
+ typeof candidate.list === 'function' &&
23
+ typeof candidate.remove === 'function');
24
+ }, { message: 'store must implement seal(), list(), and remove()' });
25
+ /** Options for crash-durable `create`, `update`, and `delete` calls. */
26
+ export const durableWritesConfigSchema = z.strictObject({
27
+ store: durableWriteStoreSchema,
28
+ /** Separates deployments or workflow lanes that share an authenticated actor. */
29
+ namespace: z.string().trim().min(1).optional(),
30
+ });
@@ -0,0 +1,44 @@
1
+ /** Crash-durable exact HTTP request used by the stateless agent client. */
2
+ import { z } from 'zod';
3
+ export declare const HTTP_COMMIT_ENVELOPE_VERSION: 1;
4
+ export declare const HTTP_COMMIT_ENVELOPE_PREFIX = "http-commit-envelope:";
5
+ /** Stay one hour inside the server's 24-hour idempotency retention window. */
6
+ export declare const HTTP_COMMIT_REPLAY_WINDOW_MS: number;
7
+ /** Apply normal JSON semantics once, then make object-key order canonical. */
8
+ export declare function canonicalHttpCommitBody(value: unknown): string;
9
+ export declare const durableHttpCommitEnvelopeSchema: z.ZodObject<{
10
+ id: z.ZodString;
11
+ type: z.ZodLiteral<"http_commit_envelope">;
12
+ storageVersion: z.ZodLiteral<1>;
13
+ idempotencyKey: z.core.$ZodBranded<z.ZodString, "IdempotencyKey", "out">;
14
+ protocolVersion: z.ZodDefault<z.ZodNumber>;
15
+ request: z.ZodObject<{
16
+ method: z.ZodEnum<{
17
+ DELETE: "DELETE";
18
+ POST: "POST";
19
+ PATCH: "PATCH";
20
+ }>;
21
+ path: z.ZodString;
22
+ body: z.ZodString;
23
+ }, z.core.$strict>;
24
+ scopeNamespace: z.ZodString;
25
+ createdAt: z.ZodNumber;
26
+ sealedAt: z.ZodNumber;
27
+ sequence: z.ZodOptional<z.ZodNumber>;
28
+ timestamp: z.ZodNumber;
29
+ }, z.core.$strict>;
30
+ export type DurableHttpCommitEnvelope = z.infer<typeof durableHttpCommitEnvelopeSchema>;
31
+ export declare function httpCommitEnvelopeRecordId(idempotencyKey: string, scopeNamespace?: string): string;
32
+ export declare function createDurableHttpCommitEnvelope(input: {
33
+ idempotencyKey: string;
34
+ request: {
35
+ method: 'POST' | 'PATCH' | 'DELETE';
36
+ path: string;
37
+ body: unknown;
38
+ };
39
+ scopeNamespace: string;
40
+ createdAt?: number;
41
+ sealedAt?: number;
42
+ sequence?: number;
43
+ }): DurableHttpCommitEnvelope;
44
+ export declare function isHttpCommitReplayExpired(envelope: Pick<DurableHttpCommitEnvelope, 'sealedAt'>, now?: number): boolean;