@abloatai/humans 0.44.0 → 0.45.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.
package/dist/Ablo.d.ts CHANGED
@@ -171,6 +171,9 @@ export declare namespace Ablo {
171
171
  type Held<T = Record<string, unknown>> = import('@abloatai/transaction/types/streams').HeldClaim<T>;
172
172
  type CreateOptions = import('./local/client/resourceTypes.js').ClaimCreateOptions;
173
173
  type WaitOptions = import('./local/client/resourceTypes.js').ClaimWaitOptions;
174
+ type ContentionOptions = import('@abloatai/transaction/resources/modelOperations').ClaimContentionOptions;
175
+ type AttemptEvent = import('@abloatai/transaction/resources/modelOperations').ClaimAttemptEvent;
176
+ type QueueView = import('@abloatai/transaction/resources/modelOperations').ClaimQueueView;
174
177
  type Client = import('./local/client/resourceTypes.js').ClaimResource;
175
178
  }
176
179
  namespace Model {
@@ -17,9 +17,9 @@ import type { SyncClient } from '../SyncClient.js';
17
17
  import type { OnDemandLoader } from '../sync/OnDemandLoader.js';
18
18
  import type { JoinedParticipant } from '../sync/participants.js';
19
19
  import type { Duration, Claim, ClaimHeartbeat, ClaimHeartbeatOptions, HeldClaim, HeldLease, ClaimWaitOptions, Snapshot } from '@abloatai/transaction/types/streams';
20
- export type { ModelListScope, ModelTrackParams, ModelTrackResult, LocalReadOptions, LocalCountOptions, ServerReadOptions, ServerGetOptions, ServerRetrieveOptions, ClaimTargetOptions, ClaimParams, ClaimLookupParams, ClaimReorderParams, ClaimOptions, ClaimReadApi, AwaitedClaimMethod, ClaimApi, ModelRetrieveParams, ModelCreateParams, ModelUpdateParams, ModelDeleteParams, JoinOptions, } from '@abloatai/transaction/resources/modelOperations';
20
+ export type { ModelListScope, ModelTrackParams, ModelTrackResult, LocalReadOptions, LocalCountOptions, ServerReadOptions, ServerGetOptions, ServerRetrieveOptions, ClaimTargetOptions, ClaimParams, ClaimContentionOptions, ClaimAttemptEvent, ClaimQueueView, ClaimSkipOptions, ClaimSkipParams, ClaimLookupParams, ClaimReorderParams, ClaimOptions, ClaimReadApi, AwaitedClaimMethod, ClaimApi, ModelRetrieveParams, ModelCreateParams, ModelUpdateParams, ModelDeleteParams, JoinOptions, } from '@abloatai/transaction/resources/modelOperations';
21
21
  export type { Claim, ClaimHeartbeat, ClaimHeartbeatOptions, HeldClaim, HeldLease };
22
- import type { ClaimApi, JoinOptions, LocalCountOptions, LocalReadOptions } from '@abloatai/transaction/resources/modelOperations';
22
+ import type { ClaimApi, ClaimAttemptEvent, JoinOptions, LocalCountOptions, LocalReadOptions } from '@abloatai/transaction/resources/modelOperations';
23
23
  import type { HttpModelClient } from '@abloatai/transaction/transport/httpClient';
24
24
  import type { ParticipantKind } from '@abloatai/transaction/types/participant';
25
25
  export interface ModelClientMeta {
@@ -56,6 +56,8 @@ export interface ModelCollaboration {
56
56
  waitTimeoutMs?: number;
57
57
  /** Abort the queued wait — rejects with `claim_wait_aborted`. */
58
58
  signal?: AbortSignal;
59
+ /** Request-scoped queued / granted / skipped / failed status events. */
60
+ onStatus?: (event: ClaimAttemptEvent) => void;
59
61
  }): Promise<Claim>;
60
62
  createSnapshot(modelKey: string, id: string): Snapshot;
61
63
  /**
@@ -26,6 +26,7 @@ import { subTarget } from '@abloatai/transaction/coordination';
26
26
  // here like the other enumerated crossings.
27
27
  import { declaredMeta } from '@abloatai/transaction/coordination/claimMeta';
28
28
  import { ModelScope } from '@abloatai/transaction/types';
29
+ import { claimQueueView, resolveClaimContentionOptions, } from '@abloatai/transaction/resources/modelOperations';
29
30
  const modelClientMeta = new WeakMap();
30
31
  export function getModelClientMeta(modelClient) {
31
32
  if (typeof modelClient !== 'object' || modelClient === null)
@@ -172,22 +173,13 @@ defaultWait) {
172
173
  throw new AbloValidationError(`Model "${schemaKey}" was built without the collaboration runtime, so claim() is unavailable here. Claiming needs no per-model config — use the standard Ablo({ schema, apiKey }) client and every model is claimable.`, { code: 'model_claim_not_configured' });
173
174
  }
174
175
  const { id, ...options } = params;
175
- // Is someone else already on this target? Read the local coordination
176
- // snapshot up front it decides whether a re-read is needed after the
177
- // claim (a free or already-held target cannot have changed underneath us).
176
+ // Read the local snapshot only to decide whether a post-grant re-read may
177
+ // be needed. Admission itself always goes to the server: a local presence
178
+ // snapshot may be stale or incomplete across instances.
178
179
  const held = collaboration.state({ model: wireModel, id });
179
180
  const contended = !!held && held.heldBy !== collaboration.selfParticipantId;
180
- const failFast = options.queue === false;
181
- // The try-claim (`queue: false`): a held target is an expected outcome,
182
- // not an error, so it resolves `null` — the caller reads `if (!claim)`
183
- // and moves on; who holds it stays readable via `claim.state`. Best-effort
184
- // at the client (a racing claim not yet synced into our snapshot slips
185
- // through here) — the commit-time claim guard is the authoritative
186
- // backstop that rejects the loser's first write. For work-distribution
187
- // dedup that's exactly right: don't wait (that would double-process), skip.
188
- if (failFast && contended) {
189
- return null;
190
- }
181
+ const contention = resolveClaimContentionOptions(options);
182
+ const failFast = !contention.wait;
191
183
  // Ensure the row exists locally before claiming.
192
184
  let model = ownRowOrThrow(id);
193
185
  if (!model) {
@@ -207,27 +199,40 @@ defaultWait) {
207
199
  await collaboration.pinScope?.({ [schemaKey]: id });
208
200
  // Acquire the lease. By default (`queue` is not false) this goes through the
209
201
  // server's fair FIFO queue: `queue: true` resolves only once the lease is
210
- // genuinely ours, blocking behind any current holder, with no check-then-act
211
- // gap because the server orders contenders. Fail-fast skips the queue: an
212
- // observed conflict was already rejected above, so this just records the lease.
213
- const lease = await collaboration.createClaim({
214
- target: {
215
- model: wireModel,
216
- id,
217
- // The whole sub-entity locator in one move — listing its members here
218
- // is what let `fields` die between the caller and the lease, so the
219
- // claim covered the whole row while the caller believed it named parts.
220
- ...subTarget(options, schemaKey),
221
- },
222
- description: claimDescription(options),
223
- ttl: options.ttl,
224
- queue: !failFast,
225
- maxQueueDepth: options.maxQueueDepth,
226
- // The one wait cap, declared once on ClaimTargetOptions — the socket
227
- // wait and the HTTP poll-wait both honor it as `grant_timeout`.
228
- waitTimeoutMs: options.waitTimeoutMs,
229
- signal: options.signal,
230
- });
202
+ // genuinely ours, blocking behind any current holder. Fail-fast skips the
203
+ // queue but still awaits the server: a conflict invisible in the local
204
+ // snapshot resolves `null`, never a speculative handle.
205
+ let lease;
206
+ try {
207
+ lease = await collaboration.createClaim({
208
+ target: {
209
+ model: wireModel,
210
+ id,
211
+ // The whole sub-entity locator in one move listing its members here
212
+ // is what let `fields` die between the caller and the lease, so the
213
+ // claim covered the whole row while the caller believed it named parts.
214
+ ...subTarget(options, schemaKey),
215
+ },
216
+ description: claimDescription(options),
217
+ ttl: options.ttl,
218
+ queue: contention.wait,
219
+ maxQueueDepth: contention.maxDepth,
220
+ // The one wait cap, declared once on ClaimTargetOptions — the socket
221
+ // wait and the HTTP poll-wait both honor it as `grant_timeout`.
222
+ waitTimeoutMs: contention.timeoutMs,
223
+ signal: contention.signal,
224
+ onStatus: contention.onStatus,
225
+ });
226
+ }
227
+ catch (err) {
228
+ const normalized = toAbloError(err);
229
+ if (failFast &&
230
+ normalized instanceof AbloClaimedError &&
231
+ normalized.code === 'claim_conflict') {
232
+ return null;
233
+ }
234
+ throw normalized;
235
+ }
231
236
  // Only when the claim actually waited behind another holder can the row have
232
237
  // changed underneath us — re-read so the claimed snapshot reflects what that
233
238
  // holder committed before releasing. Either of two signals suffices:
@@ -340,45 +345,45 @@ defaultWait) {
340
345
  if (!collaboration) {
341
346
  throw new AbloValidationError(`Model "${schemaKey}" was built without the collaboration runtime, so claim() is unavailable here. Claiming needs no per-model config — use the standard Ablo({ schema, apiKey }) client and every model is claimable.`, { code: 'model_claim_not_configured' });
342
347
  }
343
- // Is someone else already on this target? Read the local coordination
344
- // snapshot up front so a `queue: false` caller can reject before announcing
345
- // a claim the server would refuse.
346
- const held = collaboration.state({ model: wireModel, id });
347
- const contended = !!held && held.heldBy !== collaboration.selfParticipantId;
348
- const failFast = options.queue === false;
349
- // The try-claim (`queue: false`): resolve `null` if a holder is already
350
- // visible — an expected outcome, not an error. Best-effort at the client —
351
- // a row this participant never synced usually carries no local claim state
352
- // either, so a peer gets the deterministic `null` only once it has
353
- // observed the holder (entered the row's entity scope). The server's
354
- // queue is the backstop for the queuing path.
355
- if (failFast && contended) {
356
- return null;
357
- }
348
+ const contention = resolveClaimContentionOptions(options);
349
+ const failFast = !contention.wait;
358
350
  // Enter the entity scope before acquiring the lease so the holder's claim
359
351
  // presence broadcasts to everyone in this entity group — the same ordering
360
352
  // the row-bearing path relies on. No pool `load` and no `entity_not_found`
361
353
  // throw: the row lives only in the customer's database, so there is nothing
362
354
  // to hydrate here and nothing to re-read after the grant.
363
355
  await collaboration.pinScope?.({ [schemaKey]: id });
364
- const lease = await collaboration.createClaim({
365
- target: {
366
- model: wireModel,
367
- id,
368
- // The whole sub-entity locator in one move — listing its members here
369
- // is what let `fields` die between the caller and the lease, so the
370
- // claim covered the whole row while the caller believed it named parts.
371
- ...subTarget(options, schemaKey),
372
- },
373
- description: claimDescription(options),
374
- ttl: options.ttl,
375
- queue: !failFast,
376
- maxQueueDepth: options.maxQueueDepth,
377
- // The one wait cap, declared once on ClaimTargetOptions — the socket
378
- // wait and the HTTP poll-wait both honor it as `grant_timeout`.
379
- waitTimeoutMs: options.waitTimeoutMs,
380
- signal: options.signal,
381
- });
356
+ let lease;
357
+ try {
358
+ lease = await collaboration.createClaim({
359
+ target: {
360
+ model: wireModel,
361
+ id,
362
+ // The whole sub-entity locator in one move listing its members here
363
+ // is what let `fields` die between the caller and the lease, so the
364
+ // claim covered the whole row while the caller believed it named parts.
365
+ ...subTarget(options, schemaKey),
366
+ },
367
+ description: claimDescription(options),
368
+ ttl: options.ttl,
369
+ queue: contention.wait,
370
+ maxQueueDepth: contention.maxDepth,
371
+ // The one wait cap, declared once on ClaimTargetOptions — the socket
372
+ // wait and the HTTP poll-wait both honor it as `grant_timeout`.
373
+ waitTimeoutMs: contention.timeoutMs,
374
+ signal: contention.signal,
375
+ onStatus: contention.onStatus,
376
+ });
377
+ }
378
+ catch (err) {
379
+ const normalized = toAbloError(err);
380
+ if (failFast &&
381
+ normalized instanceof AbloClaimedError &&
382
+ normalized.code === 'claim_conflict') {
383
+ return null;
384
+ }
385
+ throw normalized;
386
+ }
382
387
  // A watermark-only snapshot: `createSnapshot` still reads the engine's
383
388
  // current `lastSyncId` even though the pool holds no row (the bucket is
384
389
  // empty). It costs nothing extra and gives a write taken under this lease a
@@ -537,10 +542,7 @@ defaultWait) {
537
542
  };
538
543
  },
539
544
  queue(params) {
540
- return {
541
- object: 'list',
542
- data: collaboration?.queue({ model: wireModel, id: params.id }) ?? [],
543
- };
545
+ return claimQueueView(collaboration?.queue({ model: wireModel, id: params.id }) ?? []);
544
546
  },
545
547
  reorder(params) {
546
548
  collaboration?.reorder({ model: wireModel, id: params.id }, params.order);
@@ -627,6 +629,7 @@ defaultWait) {
627
629
  // race — see `takeClaim`). Released with the lease in the `finally`
628
630
  // below. Awaited for broadcast ordering; still best-effort.
629
631
  await collaboration.pinScope?.({ [schemaKey]: id });
632
+ const contention = resolveClaimContentionOptions(claim);
630
633
  autoLease = await collaboration.createClaim({
631
634
  target: {
632
635
  model: wireModel,
@@ -635,8 +638,11 @@ defaultWait) {
635
638
  },
636
639
  description: claimDescription(claim, 'creating'),
637
640
  ttl: claim.ttl,
638
- queue: claim.queue !== false,
639
- maxQueueDepth: claim.maxQueueDepth,
641
+ queue: contention.wait,
642
+ maxQueueDepth: contention.maxDepth,
643
+ waitTimeoutMs: contention.timeoutMs,
644
+ signal: contention.signal,
645
+ onStatus: contention.onStatus,
640
646
  });
641
647
  }
642
648
  // Default `organizationId` from the client's identity, matching the other
@@ -724,7 +730,7 @@ defaultWait) {
724
730
  const autoClaim = params.claim && !isClaimHandle(params.claim) ? params.claim : null;
725
731
  if (autoClaim) {
726
732
  const handle = await takeClaim({ ...autoClaim, id: params.id });
727
- // A declined try-claim is `null` only on the standalone verb; a
733
+ // A skipped try-claim is `null` only on the standalone verb; a
728
734
  // write that could not take its claim is a failed write.
729
735
  if (!handle) {
730
736
  throw new AbloClaimedError(`${registeredModelName}/${params.id} is held by another participant, so this update's claim could not be taken.`, { code: 'entity_claimed' });
@@ -25,6 +25,7 @@ import { awaitClaimGrant } from '@abloatai/transaction/coordination/awaitClaimGr
25
25
  import { createSnapshot } from '../sync/createSnapshot.js';
26
26
  import { createParticipantManager } from '../sync/participants.js';
27
27
  import { resolveApiKeyValue, resolveBootstrapBaseUrl } from '@abloatai/transaction/auth/apiKey';
28
+ import { claimAttemptFailure, emitClaimStatus, } from '@abloatai/transaction/resources/modelOperations';
28
29
  import { createModelProxy } from './createModelProxy.js';
29
30
  import { assertWriteOptions } from '@abloatai/transaction/resources/writeOptionsSchema';
30
31
  export function buildReactiveEngine(inputs) {
@@ -257,8 +258,8 @@ export function buildReactiveEngine(inputs) {
257
258
  return Promise.resolve();
258
259
  };
259
260
  // The token is server-stamped and arrives on the grant frame, so prefer
260
- // the one `awaitClaimGrant` read there; fall back to any the local handle
261
- // already carried (immediate, non-queued grants).
261
+ // the one `awaitClaimGrant` read there; retain the handle fallback for
262
+ // wire-compatible transports that already stamped it locally.
262
263
  const resolvedFenceToken = fenceToken ?? claim.fenceToken;
263
264
  return {
264
265
  object: 'claim',
@@ -280,6 +281,35 @@ export function buildReactiveEngine(inputs) {
280
281
  const publicClaims = Object.assign(claimStream, {
281
282
  async create(claimOptions) {
282
283
  await ready();
284
+ // Subscribe before announcing the claim. A fast rejection can arrive
285
+ // in the same turn as `send` in tests and on a low-latency socket; if
286
+ // the listener is installed afterwards, that authoritative answer is
287
+ // lost and the locally minted handle looks like a grant.
288
+ const claimId = crypto.randomUUID();
289
+ const grant = awaitClaimGrant(transport, claimId, {
290
+ timeoutMs: claimOptions.waitTimeoutMs,
291
+ maxQueueDepth: claimOptions.maxQueueDepth,
292
+ signal: claimOptions.signal,
293
+ logger,
294
+ onQueued: ({ position }) => {
295
+ emitClaimStatus(claimOptions.onStatus, {
296
+ type: 'queued',
297
+ claimId,
298
+ position,
299
+ ahead: position + 1,
300
+ });
301
+ },
302
+ onGranted: ({ waited }) => {
303
+ emitClaimStatus(claimOptions.onStatus, {
304
+ type: 'granted',
305
+ claimId,
306
+ waited,
307
+ });
308
+ },
309
+ onFailed: (error) => {
310
+ emitClaimStatus(claimOptions.onStatus, claimAttemptFailure(claimOptions.queue !== false, error));
311
+ },
312
+ });
283
313
  const claim = claimStream.claim({
284
314
  ...streamTarget(claimOptions.target),
285
315
  ...subTarget(claimOptions.target),
@@ -287,32 +317,16 @@ export function buildReactiveEngine(inputs) {
287
317
  description: claimOptions.description,
288
318
  ttl: claimOptions.ttl,
289
319
  queue: claimOptions.queue,
320
+ }, claimId);
321
+ // A claim is ours only after the server says so. This applies equally
322
+ // to queued claims and try-claims (`queue: false`): the latter must
323
+ // observe `claim_rejected` instead of returning a phantom handle.
324
+ const { waited, fenceToken, readAt } = await grant.catch((err) => {
325
+ // Give up the local/reconnect record after any rejection, timeout,
326
+ // abort, or lost lease. For queued claims this also leaves the line.
327
+ claim.revoke?.();
328
+ throw err;
290
329
  });
291
- // With `queue`, the claim is only really *ours* once the server says
292
- // so (`claim_acquired` if the target was free, `claim_granted` once
293
- // we reach the head of the FIFO line). Block here on that grant so
294
- // callers — chiefly `ablo.<model>.claim` — get a handle that already
295
- // holds the lease, never a half-claimed one racing the queue.
296
- let waited = false;
297
- let fenceToken;
298
- let readAt;
299
- if (claimOptions.queue) {
300
- try {
301
- ({ waited, fenceToken, readAt } = await awaitClaimGrant(transport, claim.id, {
302
- timeoutMs: claimOptions.waitTimeoutMs,
303
- maxQueueDepth: claimOptions.maxQueueDepth,
304
- signal: claimOptions.signal,
305
- logger,
306
- }));
307
- }
308
- catch (err) {
309
- // Gave up waiting (queue too deep, timed out, or lost) — abandon
310
- // the queued claim so we don't leave a phantom entry in the
311
- // line that would block or mislead other claimers.
312
- claim.revoke?.();
313
- throw err;
314
- }
315
- }
316
330
  return wrapClaimHandle(claim, waited, fenceToken, readAt);
317
331
  },
318
332
  list(target) {
@@ -8,5 +8,5 @@
8
8
  * live participant handle.
9
9
  */
10
10
  export * from '@abloatai/transaction/resources/httpResources';
11
- export type { LocalCountOptions, LocalReadOptions, ModelListScope, ServerReadOptions, ModelRetrieveParams, ModelCreateParams, ModelUpdateParams, ModelDeleteParams, ClaimOptions, ClaimParams, ClaimLookupParams, ClaimReorderParams, Claim, ClaimHeartbeat, ClaimHeartbeatOptions, HeldClaim, HeldLease, } from '@abloatai/transaction/resources/modelOperations';
11
+ export type { LocalCountOptions, LocalReadOptions, ModelListScope, ServerReadOptions, ModelRetrieveParams, ModelCreateParams, ModelUpdateParams, ModelDeleteParams, ClaimOptions, ClaimParams, ClaimContentionOptions, ClaimAttemptEvent, ClaimQueueView, ClaimLookupParams, ClaimReorderParams, Claim, ClaimHeartbeat, ClaimHeartbeatOptions, HeldClaim, HeldLease, } from '@abloatai/transaction/resources/modelOperations';
12
12
  export type { ModelOperations } from './createModelProxy.js';
@@ -41,13 +41,18 @@ export interface ClaimStreamConfig {
41
41
  }
42
42
  export interface AttachableClaimStream extends ClaimStream {
43
43
  /**
44
- * Mints a lease directly: sends the `claim_begin` frame and returns a held
45
- * {@link Claim} that carries no row `data` (the resource layer reads the row
46
- * and stamps it). This is an internal entry point, not part of the public
44
+ * Mints the local handle and sends its `claim_begin` frame. The handle is a
45
+ * request until the resource layer observes the server's grant; it must never
46
+ * be returned to application code before that acknowledgement. This is an
47
+ * internal entry point, not part of the public
47
48
  * {@link ClaimStream}; application code takes a claim through
48
49
  * `ablo.<model>.claim({ id })`, which is built on this.
50
+ *
51
+ * `claimId` lets that resource layer subscribe for the acknowledgement before
52
+ * this method sends. Omitting it preserves the direct stream API's generated
53
+ * id for internal callers that do not await the grant.
49
54
  */
50
- claim(target: PresenceTarget, opts?: ClaimOptions): Claim;
55
+ claim(target: PresenceTarget, opts?: ClaimOptions, claimId?: string): Claim;
51
56
  attach(transport: ClaimTransport): void;
52
57
  /**
53
58
  * Seeds the participant identity once the host resolves it. The stream can
@@ -348,8 +348,8 @@ export function createClaimStream(config, transport = null) {
348
348
  // The locator half derives from `OwnClaim` rather than being restated: a
349
349
  // member spelled out here is a member that dies before `sendBegin`, which is
350
350
  // how `fields` used to be lost between `claim()` and the socket.
351
- function mintHandle(args) {
352
- const claimId = crypto.randomUUID();
351
+ function mintHandle(args, requestedClaimId) {
352
+ const claimId = requestedClaimId ?? crypto.randomUUID();
353
353
  const estimatedMs = args.ttl !== undefined ? toMs(args.ttl) : undefined;
354
354
  // The handle the caller reads back is a public claim, so its `meta` is the
355
355
  // declared shape; the `OwnClaim` below stays wire-typed, because that is
@@ -402,7 +402,7 @@ export function createClaimStream(config, transport = null) {
402
402
  return target;
403
403
  }
404
404
  return {
405
- claim(target, opts) {
405
+ claim(target, opts, claimId) {
406
406
  const resolved = resolveTarget(target);
407
407
  return mintHandle({
408
408
  ...wireTarget(resolved),
@@ -410,7 +410,7 @@ export function createClaimStream(config, transport = null) {
410
410
  description: claimDescription({ ...opts, meta: resolved.meta }),
411
411
  ttl: opts?.ttl,
412
412
  queue: opts?.queue,
413
- });
413
+ }, claimId);
414
414
  },
415
415
  get others() {
416
416
  return claimsSnapshot;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abloatai/humans",
3
- "version": "0.44.0",
3
+ "version": "0.45.0",
4
4
  "description": "The optional human-facing local-state package for Ablo: presence, live queries, and React bindings.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -84,7 +84,7 @@
84
84
  "directory": "packages/humans"
85
85
  },
86
86
  "dependencies": {
87
- "@abloatai/transaction": "^0.44.0",
87
+ "@abloatai/transaction": "^0.45.0",
88
88
  "mobx": "^6.13.7",
89
89
  "uuid": "^11.1.0",
90
90
  "zod": "^4.4.3"
package/src/Ablo.ts CHANGED
@@ -388,6 +388,12 @@ export namespace Ablo {
388
388
  export type Held<T = Record<string, unknown>> = import('@abloatai/transaction/types/streams').HeldClaim<T>;
389
389
  export type CreateOptions = import('./local/client/resourceTypes.js').ClaimCreateOptions;
390
390
  export type WaitOptions = import('./local/client/resourceTypes.js').ClaimWaitOptions;
391
+ export type ContentionOptions =
392
+ import('@abloatai/transaction/resources/modelOperations').ClaimContentionOptions;
393
+ export type AttemptEvent =
394
+ import('@abloatai/transaction/resources/modelOperations').ClaimAttemptEvent;
395
+ export type QueueView =
396
+ import('@abloatai/transaction/resources/modelOperations').ClaimQueueView;
391
397
  export type Client = import('./local/client/resourceTypes.js').ClaimResource;
392
398
  }
393
399
 
@@ -78,6 +78,11 @@ export type {
78
78
  ServerRetrieveOptions,
79
79
  ClaimTargetOptions,
80
80
  ClaimParams,
81
+ ClaimContentionOptions,
82
+ ClaimAttemptEvent,
83
+ ClaimQueueView,
84
+ ClaimSkipOptions,
85
+ ClaimSkipParams,
81
86
  ClaimLookupParams,
82
87
  ClaimReorderParams,
83
88
  ClaimOptions,
@@ -97,6 +102,10 @@ import type {
97
102
  ClaimLookupParams,
98
103
  ClaimOptions,
99
104
  ClaimParams,
105
+ ClaimSkipOptions,
106
+ ClaimSkipParams,
107
+ ClaimAttemptEvent,
108
+ ClaimQueueView,
100
109
  ClaimReorderParams,
101
110
  JoinOptions,
102
111
  LocalCountOptions,
@@ -109,6 +118,10 @@ import type {
109
118
  ModelUpdateParams,
110
119
  ServerReadOptions,
111
120
  } from '@abloatai/transaction/resources/modelOperations';
121
+ import {
122
+ claimQueueView,
123
+ resolveClaimContentionOptions,
124
+ } from '@abloatai/transaction/resources/modelOperations';
112
125
  import type { HttpModelClient } from '@abloatai/transaction/transport/httpClient';
113
126
  import type { ParticipantKind } from '@abloatai/transaction/types/participant';
114
127
 
@@ -160,6 +173,8 @@ export interface ModelCollaboration {
160
173
  waitTimeoutMs?: number;
161
174
  /** Abort the queued wait — rejects with `claim_wait_aborted`. */
162
175
  signal?: AbortSignal;
176
+ /** Request-scoped queued / granted / skipped / failed status events. */
177
+ onStatus?: (event: ClaimAttemptEvent) => void;
163
178
  }): Promise<Claim>;
164
179
  createSnapshot(modelKey: string, id: string): Snapshot;
165
180
  /**
@@ -557,23 +572,13 @@ export function createModelProxy<T, C>(
557
572
  );
558
573
  }
559
574
  const { id, ...options } = params;
560
- // Is someone else already on this target? Read the local coordination
561
- // snapshot up front it decides whether a re-read is needed after the
562
- // claim (a free or already-held target cannot have changed underneath us).
575
+ // Read the local snapshot only to decide whether a post-grant re-read may
576
+ // be needed. Admission itself always goes to the server: a local presence
577
+ // snapshot may be stale or incomplete across instances.
563
578
  const held = collaboration.state({ model: wireModel, id });
564
579
  const contended = !!held && held.heldBy !== collaboration.selfParticipantId;
565
- const failFast = options.queue === false;
566
-
567
- // The try-claim (`queue: false`): a held target is an expected outcome,
568
- // not an error, so it resolves `null` — the caller reads `if (!claim)`
569
- // and moves on; who holds it stays readable via `claim.state`. Best-effort
570
- // at the client (a racing claim not yet synced into our snapshot slips
571
- // through here) — the commit-time claim guard is the authoritative
572
- // backstop that rejects the loser's first write. For work-distribution
573
- // dedup that's exactly right: don't wait (that would double-process), skip.
574
- if (failFast && contended) {
575
- return null;
576
- }
580
+ const contention = resolveClaimContentionOptions(options);
581
+ const failFast = !contention.wait;
577
582
 
578
583
  // Ensure the row exists locally before claiming.
579
584
  let model = ownRowOrThrow(id);
@@ -599,27 +604,41 @@ export function createModelProxy<T, C>(
599
604
 
600
605
  // Acquire the lease. By default (`queue` is not false) this goes through the
601
606
  // server's fair FIFO queue: `queue: true` resolves only once the lease is
602
- // genuinely ours, blocking behind any current holder, with no check-then-act
603
- // gap because the server orders contenders. Fail-fast skips the queue: an
604
- // observed conflict was already rejected above, so this just records the lease.
605
- const lease = await collaboration.createClaim({
606
- target: {
607
- model: wireModel,
608
- id,
609
- // The whole sub-entity locator in one move — listing its members here
610
- // is what let `fields` die between the caller and the lease, so the
611
- // claim covered the whole row while the caller believed it named parts.
612
- ...subTarget(options, schemaKey),
613
- },
614
- description: claimDescription(options),
615
- ttl: options.ttl,
616
- queue: !failFast,
617
- maxQueueDepth: options.maxQueueDepth,
618
- // The one wait cap, declared once on ClaimTargetOptions — the socket
619
- // wait and the HTTP poll-wait both honor it as `grant_timeout`.
620
- waitTimeoutMs: options.waitTimeoutMs,
621
- signal: options.signal,
622
- });
607
+ // genuinely ours, blocking behind any current holder. Fail-fast skips the
608
+ // queue but still awaits the server: a conflict invisible in the local
609
+ // snapshot resolves `null`, never a speculative handle.
610
+ let lease: Claim;
611
+ try {
612
+ lease = await collaboration.createClaim({
613
+ target: {
614
+ model: wireModel,
615
+ id,
616
+ // The whole sub-entity locator in one move listing its members here
617
+ // is what let `fields` die between the caller and the lease, so the
618
+ // claim covered the whole row while the caller believed it named parts.
619
+ ...subTarget(options, schemaKey),
620
+ },
621
+ description: claimDescription(options),
622
+ ttl: options.ttl,
623
+ queue: contention.wait,
624
+ maxQueueDepth: contention.maxDepth,
625
+ // The one wait cap, declared once on ClaimTargetOptions — the socket
626
+ // wait and the HTTP poll-wait both honor it as `grant_timeout`.
627
+ waitTimeoutMs: contention.timeoutMs,
628
+ signal: contention.signal,
629
+ onStatus: contention.onStatus,
630
+ });
631
+ } catch (err) {
632
+ const normalized = toAbloError(err);
633
+ if (
634
+ failFast &&
635
+ normalized instanceof AbloClaimedError &&
636
+ normalized.code === 'claim_conflict'
637
+ ) {
638
+ return null;
639
+ }
640
+ throw normalized;
641
+ }
623
642
 
624
643
  // Only when the claim actually waited behind another holder can the row have
625
644
  // changed underneath us — re-read so the claimed snapshot reflects what that
@@ -748,22 +767,8 @@ export function createModelProxy<T, C>(
748
767
  { code: 'model_claim_not_configured' },
749
768
  );
750
769
  }
751
- // Is someone else already on this target? Read the local coordination
752
- // snapshot up front so a `queue: false` caller can reject before announcing
753
- // a claim the server would refuse.
754
- const held = collaboration.state({ model: wireModel, id });
755
- const contended = !!held && held.heldBy !== collaboration.selfParticipantId;
756
- const failFast = options.queue === false;
757
-
758
- // The try-claim (`queue: false`): resolve `null` if a holder is already
759
- // visible — an expected outcome, not an error. Best-effort at the client —
760
- // a row this participant never synced usually carries no local claim state
761
- // either, so a peer gets the deterministic `null` only once it has
762
- // observed the holder (entered the row's entity scope). The server's
763
- // queue is the backstop for the queuing path.
764
- if (failFast && contended) {
765
- return null;
766
- }
770
+ const contention = resolveClaimContentionOptions(options);
771
+ const failFast = !contention.wait;
767
772
 
768
773
  // Enter the entity scope before acquiring the lease so the holder's claim
769
774
  // presence broadcasts to everyone in this entity group — the same ordering
@@ -772,24 +777,38 @@ export function createModelProxy<T, C>(
772
777
  // to hydrate here and nothing to re-read after the grant.
773
778
  await collaboration.pinScope?.({ [schemaKey]: id });
774
779
 
775
- const lease = await collaboration.createClaim({
776
- target: {
777
- model: wireModel,
778
- id,
779
- // The whole sub-entity locator in one move — listing its members here
780
- // is what let `fields` die between the caller and the lease, so the
781
- // claim covered the whole row while the caller believed it named parts.
782
- ...subTarget(options, schemaKey),
783
- },
784
- description: claimDescription(options),
785
- ttl: options.ttl,
786
- queue: !failFast,
787
- maxQueueDepth: options.maxQueueDepth,
788
- // The one wait cap, declared once on ClaimTargetOptions — the socket
789
- // wait and the HTTP poll-wait both honor it as `grant_timeout`.
790
- waitTimeoutMs: options.waitTimeoutMs,
791
- signal: options.signal,
792
- });
780
+ let lease: Claim;
781
+ try {
782
+ lease = await collaboration.createClaim({
783
+ target: {
784
+ model: wireModel,
785
+ id,
786
+ // The whole sub-entity locator in one move listing its members here
787
+ // is what let `fields` die between the caller and the lease, so the
788
+ // claim covered the whole row while the caller believed it named parts.
789
+ ...subTarget(options, schemaKey),
790
+ },
791
+ description: claimDescription(options),
792
+ ttl: options.ttl,
793
+ queue: contention.wait,
794
+ maxQueueDepth: contention.maxDepth,
795
+ // The one wait cap, declared once on ClaimTargetOptions — the socket
796
+ // wait and the HTTP poll-wait both honor it as `grant_timeout`.
797
+ waitTimeoutMs: contention.timeoutMs,
798
+ signal: contention.signal,
799
+ onStatus: contention.onStatus,
800
+ });
801
+ } catch (err) {
802
+ const normalized = toAbloError(err);
803
+ if (
804
+ failFast &&
805
+ normalized instanceof AbloClaimedError &&
806
+ normalized.code === 'claim_conflict'
807
+ ) {
808
+ return null;
809
+ }
810
+ throw normalized;
811
+ }
793
812
 
794
813
  // A watermark-only snapshot: `createSnapshot` still reads the engine's
795
814
  // current `lastSyncId` even though the pool holds no row (the bucket is
@@ -881,12 +900,12 @@ export function createModelProxy<T, C>(
881
900
  const guardedTakeClaim = guard(takeClaim);
882
901
  const guardedTakeRowFreeClaim = guard(takeRowFreeClaim);
883
902
  function claim(
884
- params: ClaimParams<C> & { queue: false },
903
+ params: ClaimSkipParams<C>,
885
904
  ): Promise<HeldClaim<T> | null>;
886
905
  function claim(params: ClaimParams<C>): Promise<HeldClaim<T>>;
887
906
  function claim(
888
907
  id: string,
889
- opts: ClaimOptions<C> & { queue: false },
908
+ opts: ClaimSkipOptions<C>,
890
909
  ): Promise<HeldLease | null>;
891
910
  function claim(id: string, opts?: ClaimOptions<C>): Promise<HeldLease>;
892
911
  function claim(
@@ -973,11 +992,10 @@ export function createModelProxy<T, C>(
973
992
  };
974
993
  },
975
994
 
976
- queue(params: ClaimLookupParams<T>): { readonly object: 'list'; readonly data: readonly Claim[] } {
977
- return {
978
- object: 'list',
979
- data: collaboration?.queue({ model: wireModel, id: params.id }) ?? [],
980
- };
995
+ queue(params: ClaimLookupParams<T>): ClaimQueueView {
996
+ return claimQueueView(
997
+ collaboration?.queue({ model: wireModel, id: params.id }) ?? [],
998
+ );
981
999
  },
982
1000
 
983
1001
  reorder(params: ClaimReorderParams<T>): void {
@@ -1086,6 +1104,7 @@ export function createModelProxy<T, C>(
1086
1104
  // race — see `takeClaim`). Released with the lease in the `finally`
1087
1105
  // below. Awaited for broadcast ordering; still best-effort.
1088
1106
  await collaboration.pinScope?.({ [schemaKey]: id });
1107
+ const contention = resolveClaimContentionOptions(claim);
1089
1108
  autoLease = await collaboration.createClaim({
1090
1109
  target: {
1091
1110
  model: wireModel,
@@ -1094,8 +1113,11 @@ export function createModelProxy<T, C>(
1094
1113
  },
1095
1114
  description: claimDescription(claim, 'creating'),
1096
1115
  ttl: claim.ttl,
1097
- queue: claim.queue !== false,
1098
- maxQueueDepth: claim.maxQueueDepth,
1116
+ queue: contention.wait,
1117
+ maxQueueDepth: contention.maxDepth,
1118
+ waitTimeoutMs: contention.timeoutMs,
1119
+ signal: contention.signal,
1120
+ onStatus: contention.onStatus,
1099
1121
  });
1100
1122
  }
1101
1123
 
@@ -1200,7 +1222,7 @@ export function createModelProxy<T, C>(
1200
1222
  params.claim && !isClaimHandle(params.claim) ? params.claim : null;
1201
1223
  if (autoClaim) {
1202
1224
  const handle = await takeClaim({ ...autoClaim, id: params.id });
1203
- // A declined try-claim is `null` only on the standalone verb; a
1225
+ // A skipped try-claim is `null` only on the standalone verb; a
1204
1226
  // write that could not take its claim is a failed write.
1205
1227
  if (!handle) {
1206
1228
  throw new AbloClaimedError(
@@ -62,6 +62,10 @@ import type {
62
62
  CreateAgentSessionParams,
63
63
  CreateSessionParams,
64
64
  } from './resourceTypes.js';
65
+ import {
66
+ claimAttemptFailure,
67
+ emitClaimStatus,
68
+ } from '@abloatai/transaction/resources/modelOperations';
65
69
  import { createModelProxy, type ModelOperations } from './createModelProxy.js';
66
70
  import { assertWriteOptions } from '@abloatai/transaction/resources/writeOptionsSchema';
67
71
  import type { AbloClient as Ablo } from '../../client.js';
@@ -409,8 +413,8 @@ export function buildReactiveEngine<const S extends SchemaRecord>(
409
413
  return Promise.resolve();
410
414
  };
411
415
  // The token is server-stamped and arrives on the grant frame, so prefer
412
- // the one `awaitClaimGrant` read there; fall back to any the local handle
413
- // already carried (immediate, non-queued grants).
416
+ // the one `awaitClaimGrant` read there; retain the handle fallback for
417
+ // wire-compatible transports that already stamped it locally.
414
418
  const resolvedFenceToken = fenceToken ?? claim.fenceToken;
415
419
  return {
416
420
  object: 'claim',
@@ -433,6 +437,38 @@ export function buildReactiveEngine<const S extends SchemaRecord>(
433
437
  const publicClaims: ClaimResource = Object.assign(claimStream, {
434
438
  async create(claimOptions: ClaimCreateOptions): Promise<Claim> {
435
439
  await ready();
440
+ // Subscribe before announcing the claim. A fast rejection can arrive
441
+ // in the same turn as `send` in tests and on a low-latency socket; if
442
+ // the listener is installed afterwards, that authoritative answer is
443
+ // lost and the locally minted handle looks like a grant.
444
+ const claimId = crypto.randomUUID();
445
+ const grant = awaitClaimGrant(transport, claimId, {
446
+ timeoutMs: claimOptions.waitTimeoutMs,
447
+ maxQueueDepth: claimOptions.maxQueueDepth,
448
+ signal: claimOptions.signal,
449
+ logger,
450
+ onQueued: ({ position }) => {
451
+ emitClaimStatus(claimOptions.onStatus, {
452
+ type: 'queued',
453
+ claimId,
454
+ position,
455
+ ahead: position + 1,
456
+ });
457
+ },
458
+ onGranted: ({ waited }) => {
459
+ emitClaimStatus(claimOptions.onStatus, {
460
+ type: 'granted',
461
+ claimId,
462
+ waited,
463
+ });
464
+ },
465
+ onFailed: (error) => {
466
+ emitClaimStatus(
467
+ claimOptions.onStatus,
468
+ claimAttemptFailure(claimOptions.queue !== false, error),
469
+ );
470
+ },
471
+ });
436
472
  const claim = claimStream.claim(
437
473
  {
438
474
  ...streamTarget(claimOptions.target),
@@ -443,31 +479,17 @@ export function buildReactiveEngine<const S extends SchemaRecord>(
443
479
  ttl: claimOptions.ttl,
444
480
  queue: claimOptions.queue,
445
481
  },
482
+ claimId,
446
483
  );
447
- // With `queue`, the claim is only really *ours* once the server says
448
- // so (`claim_acquired` if the target was free, `claim_granted` once
449
- // we reach the head of the FIFO line). Block here on that grant so
450
- // callers chiefly `ablo.<model>.claim` get a handle that already
451
- // holds the lease, never a half-claimed one racing the queue.
452
- let waited = false;
453
- let fenceToken: number | undefined;
454
- let readAt: number | undefined;
455
- if (claimOptions.queue) {
456
- try {
457
- ({ waited, fenceToken, readAt } = await awaitClaimGrant(transport, claim.id, {
458
- timeoutMs: claimOptions.waitTimeoutMs,
459
- maxQueueDepth: claimOptions.maxQueueDepth,
460
- signal: claimOptions.signal,
461
- logger,
462
- }));
463
- } catch (err) {
464
- // Gave up waiting (queue too deep, timed out, or lost) — abandon
465
- // the queued claim so we don't leave a phantom entry in the
466
- // line that would block or mislead other claimers.
467
- claim.revoke?.();
468
- throw err;
469
- }
470
- }
484
+ // A claim is ours only after the server says so. This applies equally
485
+ // to queued claims and try-claims (`queue: false`): the latter must
486
+ // observe `claim_rejected` instead of returning a phantom handle.
487
+ const { waited, fenceToken, readAt } = await grant.catch((err: unknown) => {
488
+ // Give up the local/reconnect record after any rejection, timeout,
489
+ // abort, or lost lease. For queued claims this also leaves the line.
490
+ claim.revoke?.();
491
+ throw err;
492
+ });
471
493
  return wrapClaimHandle(claim, waited, fenceToken, readAt);
472
494
  },
473
495
  list(target?: Partial<ModelTarget>): readonly ModelClaim[] {
@@ -23,6 +23,9 @@ export type {
23
23
  ModelDeleteParams,
24
24
  ClaimOptions,
25
25
  ClaimParams,
26
+ ClaimContentionOptions,
27
+ ClaimAttemptEvent,
28
+ ClaimQueueView,
26
29
  ClaimLookupParams,
27
30
  ClaimReorderParams,
28
31
  Claim,
@@ -88,13 +88,18 @@ const HEARTBEAT_ACK_TIMEOUT_MS = 10_000;
88
88
 
89
89
  export interface AttachableClaimStream extends ClaimStream {
90
90
  /**
91
- * Mints a lease directly: sends the `claim_begin` frame and returns a held
92
- * {@link Claim} that carries no row `data` (the resource layer reads the row
93
- * and stamps it). This is an internal entry point, not part of the public
91
+ * Mints the local handle and sends its `claim_begin` frame. The handle is a
92
+ * request until the resource layer observes the server's grant; it must never
93
+ * be returned to application code before that acknowledgement. This is an
94
+ * internal entry point, not part of the public
94
95
  * {@link ClaimStream}; application code takes a claim through
95
96
  * `ablo.<model>.claim({ id })`, which is built on this.
97
+ *
98
+ * `claimId` lets that resource layer subscribe for the acknowledgement before
99
+ * this method sends. Omitting it preserves the direct stream API's generated
100
+ * id for internal callers that do not await the grant.
96
101
  */
97
- claim(target: PresenceTarget, opts?: ClaimOptions): Claim;
102
+ claim(target: PresenceTarget, opts?: ClaimOptions, claimId?: string): Claim;
98
103
  attach(transport: ClaimTransport): void;
99
104
  /**
100
105
  * Seeds the participant identity once the host resolves it. The stream can
@@ -523,8 +528,9 @@ export function createClaimStream(
523
528
  ttl?: ClaimLeaseOptions['ttl'];
524
529
  queue?: boolean;
525
530
  },
531
+ requestedClaimId?: string,
526
532
  ): Claim {
527
- const claimId = crypto.randomUUID();
533
+ const claimId = requestedClaimId ?? crypto.randomUUID();
528
534
  const estimatedMs = args.ttl !== undefined ? toMs(args.ttl) : undefined;
529
535
  // The handle the caller reads back is a public claim, so its `meta` is the
530
536
  // declared shape; the `OwnClaim` below stays wire-typed, because that is
@@ -589,6 +595,7 @@ export function createClaimStream(
589
595
  claim(
590
596
  target: PresenceTarget,
591
597
  opts?: ClaimOptions,
598
+ claimId?: string,
592
599
  ): Claim {
593
600
  const resolved = resolveTarget(target);
594
601
  return mintHandle({
@@ -597,7 +604,7 @@ export function createClaimStream(
597
604
  description: claimDescription({ ...opts, meta: resolved.meta }),
598
605
  ttl: opts?.ttl,
599
606
  queue: opts?.queue,
600
- });
607
+ }, claimId);
601
608
  },
602
609
  get others() {
603
610
  return claimsSnapshot;