@get-bb/plugin-sdk 0.6.65 → 0.6.73

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.
@@ -98,24 +98,454 @@ import {
98
98
  useQueryClient,
99
99
  useMutation,
100
100
  useMutationState,
101
- replaceEqualDeep as replaceEqualDeep2
101
+ replaceEqualDeep as replaceEqualDeep3
102
102
  } from "@tanstack/react-query";
103
103
 
104
- // ../query-tags/src/optimistic.ts
104
+ // ../query-tags/src/clock.ts
105
+ var order = 0;
106
+ function tick() {
107
+ return ++order;
108
+ }
109
+
110
+ // ../query-tags/src/keyed-store.ts
105
111
  import {
106
112
  notifyManager,
107
113
  replaceEqualDeep
108
114
  } from "@tanstack/react-query";
115
+ var KeyedCollection = class {
116
+ constructor(name) {
117
+ this.name = name;
118
+ }
119
+ name;
120
+ };
121
+ var stores = /* @__PURE__ */ new WeakMap();
122
+ function isObject(value) {
123
+ return typeof value === "object" && value !== null;
124
+ }
125
+ function collectionOf(store, token) {
126
+ let collection = store.collections.get(token);
127
+ if (collection === void 0) {
128
+ collection = {
129
+ base: /* @__PURE__ */ new Map(),
130
+ visible: /* @__PURE__ */ new Map(),
131
+ layers: [],
132
+ acknowledgedAt: /* @__PURE__ */ new Map(),
133
+ views: /* @__PURE__ */ new Map()
134
+ };
135
+ store.collections.set(token, collection);
136
+ }
137
+ return collection;
138
+ }
139
+ function readEntity(collection, id) {
140
+ const cached = collection.visible.get(id);
141
+ if (cached !== void 0) return cached;
142
+ let entity = collection.base.get(id);
143
+ if (entity === void 0) return void 0;
144
+ for (const layer of collection.layers)
145
+ if (layer.ids.has(id)) entity = layer.apply(entity, id);
146
+ collection.visible.set(id, entity);
147
+ return entity;
148
+ }
149
+ function changed(store, collection, ids) {
150
+ const dirty = new Set(ids);
151
+ for (const id of dirty) collection.visible.delete(id);
152
+ if (store.batching > 0) {
153
+ const pending = store.dirtyIds.get(collection) ?? /* @__PURE__ */ new Set();
154
+ for (const id of dirty) pending.add(id);
155
+ store.dirtyIds.set(collection, pending);
156
+ return;
157
+ }
158
+ const views = /* @__PURE__ */ new Map();
159
+ for (const id of dirty)
160
+ for (const view of collection.views.get(id) ?? []) {
161
+ const viewIds = views.get(view) ?? /* @__PURE__ */ new Set();
162
+ viewIds.add(id);
163
+ views.set(view, viewIds);
164
+ }
165
+ notifyManager.batch(() => {
166
+ for (const [view, viewIds] of views) rematerialize(store, view, viewIds);
167
+ });
168
+ }
169
+ function writeBase(store, collection, id, update) {
170
+ const current = collection.base.get(id);
171
+ const next = update(current);
172
+ if (next === void 0 || next === current) return;
173
+ collection.base.set(id, next);
174
+ changed(store, collection, [id]);
175
+ }
176
+ function ingest(store, skeleton, id, item, readStart) {
177
+ const fresh = readStart > (skeleton.collection.acknowledgedAt.get(id) ?? -1);
178
+ writeBase(
179
+ store,
180
+ skeleton.collection,
181
+ id,
182
+ (current) => skeleton.view.read(item, current, fresh)
183
+ );
184
+ }
185
+ function materializeItem(store, view, item, entity) {
186
+ if (!isObject(item) || !isObject(entity)) return view.render(item, entity);
187
+ let byEntity = store.rows.get(item);
188
+ if (byEntity === void 0) {
189
+ byEntity = /* @__PURE__ */ new WeakMap();
190
+ store.rows.set(item, byEntity);
191
+ }
192
+ const cached = byEntity.get(entity);
193
+ if (cached !== void 0) return cached;
194
+ const row = view.render(item, entity);
195
+ byEntity.set(entity, row);
196
+ return row;
197
+ }
198
+ function rematerialize(store, query, dirty) {
199
+ const skeleton = store.skeletons.get(query);
200
+ if (skeleton === void 0) return;
201
+ const { view, collection } = skeleton;
202
+ const previous = store.materialized.get(query);
203
+ const incremental = dirty !== void 0 && previous !== void 0;
204
+ const slotKeys = /* @__PURE__ */ new Set();
205
+ if (incremental) {
206
+ for (const id of dirty)
207
+ for (const slot of skeleton.slotsById.get(id) ?? []) slotKeys.add(slot);
208
+ } else for (const slot of skeleton.slots.keys()) slotKeys.add(slot);
209
+ if (slotKeys.size === 0) return;
210
+ const items = /* @__PURE__ */ new Map();
211
+ const materialized = new Map(previous);
212
+ for (const slot of slotKeys) {
213
+ const prior = previous?.get(slot);
214
+ const visible = /* @__PURE__ */ new Map();
215
+ const rows = [];
216
+ for (const entry of skeleton.slots.get(slot) ?? []) {
217
+ if (entry.id === null) {
218
+ rows.push(entry.item);
219
+ continue;
220
+ }
221
+ const entity = readEntity(collection, entry.id);
222
+ if (entity !== void 0 && view.shows !== void 0 && !view.shows(entity, query.queryKey))
223
+ continue;
224
+ const previousRow = incremental ? prior?.get(entry.id) : void 0;
225
+ const row = previousRow !== void 0 && dirty?.has(entry.id) === false ? previousRow : replaceEqualDeep(
226
+ previousRow,
227
+ entity === void 0 ? entry.item : materializeItem(store, view, entry.item, entity)
228
+ );
229
+ visible.set(entry.id, row);
230
+ rows.push(row);
231
+ }
232
+ const unchanged = prior !== void 0 && prior.size === rows.length && [...prior.values()].every((row, index) => row === rows[index]);
233
+ if (incremental && unchanged) continue;
234
+ items.set(slot, rows);
235
+ materialized.set(slot, visible);
236
+ }
237
+ if (items.size === 0) return;
238
+ let next = view.rebuild(
239
+ incremental ? query.state.data : skeleton.data,
240
+ items
241
+ );
242
+ if (!incremental) {
243
+ next = replaceEqualDeep(query.state.data, next);
244
+ for (const slot of view.slots(next) ?? []) {
245
+ const visible = /* @__PURE__ */ new Map();
246
+ for (const item of slot.items) {
247
+ const id = view.keyOf(item);
248
+ if (id !== void 0) visible.set(id, item);
249
+ }
250
+ materialized.set(slot.key, visible);
251
+ }
252
+ }
253
+ store.materialized.set(query, materialized);
254
+ if (next !== query.state.data) query.setState({ data: next });
255
+ }
256
+ function skeletonIds(skeleton) {
257
+ const ids = /* @__PURE__ */ new Set();
258
+ for (const entries of skeleton?.slots.values() ?? [])
259
+ for (const { id } of entries) if (id !== null) ids.add(id);
260
+ return ids;
261
+ }
262
+ function setSkeleton(store, query, skeleton) {
263
+ const previous = store.skeletons.get(query);
264
+ const previousIds = skeletonIds(previous);
265
+ const nextIds = skeletonIds(skeleton);
266
+ if (skeleton === void 0) {
267
+ store.skeletons.delete(query);
268
+ store.materialized.delete(query);
269
+ } else store.skeletons.set(query, skeleton);
270
+ const collection = skeleton?.collection ?? previous?.collection;
271
+ if (collection === void 0) return;
272
+ for (const id of nextIds) {
273
+ let views = collection.views.get(id);
274
+ if (views === void 0) {
275
+ views = /* @__PURE__ */ new Set();
276
+ collection.views.set(id, views);
277
+ }
278
+ views.add(query);
279
+ }
280
+ for (const id of previousIds) {
281
+ if (nextIds.has(id)) continue;
282
+ const views = collection.views.get(id);
283
+ views?.delete(query);
284
+ if (views === void 0 || views.size === 0) {
285
+ collection.views.delete(id);
286
+ collection.base.delete(id);
287
+ collection.visible.delete(id);
288
+ }
289
+ }
290
+ }
291
+ function priorItem(materialized, slot, id) {
292
+ const same = materialized?.get(slot)?.get(id);
293
+ if (same !== void 0) return same;
294
+ for (const visible of materialized?.values() ?? []) {
295
+ const item = visible.get(id);
296
+ if (item !== void 0) return item;
297
+ }
298
+ return void 0;
299
+ }
300
+ function isHidden(entry, visible) {
301
+ return entry.id !== null && !visible.has(entry.id);
302
+ }
303
+ function keepHiddenEntries(previous, next, visible) {
304
+ if (!previous.some((entry) => isHidden(entry, visible))) return next;
305
+ const result = [...next];
306
+ let insertAt = result.length;
307
+ for (let index = previous.length - 1; index >= 0; index--) {
308
+ const entry = previous[index];
309
+ const existing = entry.id === null ? -1 : result.findIndex(({ id }) => id === entry.id);
310
+ if (existing >= 0) insertAt = existing;
311
+ else if (isHidden(entry, visible)) result.splice(insertAt, 0, entry);
312
+ }
313
+ return result;
314
+ }
315
+ function keptInsertions(store, query, slot, readStart) {
316
+ const insertions = (store.insertions.get(query) ?? []).filter(
317
+ (insertion) => insertion.at > readStart
318
+ );
319
+ store.insertions.set(query, insertions);
320
+ return insertions.filter((insertion) => insertion.slot === slot);
321
+ }
322
+ function batch(store, run) {
323
+ store.batching++;
324
+ try {
325
+ notifyManager.batch(run);
326
+ } finally {
327
+ store.batching--;
328
+ }
329
+ if (store.batching > 0) return;
330
+ const full = new Set(store.dirtyViews);
331
+ const partial = /* @__PURE__ */ new Map();
332
+ for (const [collection, ids] of store.dirtyIds)
333
+ for (const id of ids)
334
+ for (const view of collection.views.get(id) ?? []) {
335
+ if (full.has(view)) continue;
336
+ const viewIds = partial.get(view) ?? /* @__PURE__ */ new Set();
337
+ viewIds.add(id);
338
+ partial.set(view, viewIds);
339
+ }
340
+ store.dirtyIds.clear();
341
+ store.dirtyViews.clear();
342
+ notifyManager.batch(() => {
343
+ for (const view of full) rematerialize(store, view);
344
+ for (const [view, ids] of partial) rematerialize(store, view, ids);
345
+ });
346
+ }
347
+ function onViewWritten(store, query, view, manual) {
348
+ const data = query.state.data;
349
+ const slots = data === void 0 ? void 0 : view.slots(data);
350
+ if (slots === void 0) {
351
+ setSkeleton(store, query, void 0);
352
+ return;
353
+ }
354
+ const collection = collectionOf(store, view.collection);
355
+ const target = { view, collection };
356
+ const previous = store.skeletons.get(query);
357
+ const materialized = manual ? store.materialized.get(query) : void 0;
358
+ const readStart = manual ? -1 : store.fetchStartedAt.get(query) ?? 0;
359
+ const receipt = manual ? void 0 : store.receipts.get(query);
360
+ if (receipt !== void 0) store.receipts.delete(query);
361
+ batch(store, () => {
362
+ const nextSlots = /* @__PURE__ */ new Map();
363
+ const slotsById = /* @__PURE__ */ new Map();
364
+ for (const slot of slots) {
365
+ const entries = [];
366
+ for (const item of slot.items) {
367
+ const id = view.keyOf(item);
368
+ entries.push({ id: id ?? null, item });
369
+ if (id === void 0) continue;
370
+ const prior = priorItem(materialized, slot.key, id);
371
+ if (prior !== void 0) {
372
+ if (prior !== item)
373
+ writeBase(
374
+ store,
375
+ collection,
376
+ id,
377
+ (current) => current === void 0 ? current : view.write(item, prior, current)
378
+ );
379
+ continue;
380
+ }
381
+ const start = receipt === void 0 ? readStart : receipt.get(id);
382
+ if (start !== void 0) ingest(store, target, id, item, start);
383
+ else if (!collection.base.has(id))
384
+ ingest(store, target, id, item, readStart);
385
+ }
386
+ const previousEntries = previous?.slots.get(slot.key);
387
+ const visible = materialized?.get(slot.key);
388
+ const kept = previousEntries !== void 0 && visible !== void 0 ? keepHiddenEntries(previousEntries, entries, visible) : entries;
389
+ if (!manual) {
390
+ for (const insertion of keptInsertions(
391
+ store,
392
+ query,
393
+ slot.key,
394
+ readStart
395
+ ))
396
+ if (!kept.some(({ id }) => id === insertion.entry.id))
397
+ kept.push(insertion.entry);
398
+ }
399
+ nextSlots.set(slot.key, kept);
400
+ for (const { id } of kept) {
401
+ if (id === null) continue;
402
+ const slotKeys = slotsById.get(id) ?? /* @__PURE__ */ new Set();
403
+ slotKeys.add(slot.key);
404
+ slotsById.set(id, slotKeys);
405
+ }
406
+ }
407
+ setSkeleton(store, query, {
408
+ view,
409
+ collection,
410
+ data,
411
+ slots: nextSlots,
412
+ slotsById
413
+ });
414
+ store.dirtyViews.add(query);
415
+ });
416
+ }
417
+ function viewOf(store, query) {
418
+ const exact = store.exact.get(query.queryHash);
419
+ if (exact !== void 0) return exact;
420
+ for (const resolve of store.resolvers) {
421
+ const view = resolve(query.queryKey);
422
+ if (view !== void 0) return view;
423
+ }
424
+ return void 0;
425
+ }
426
+ function storeOf(client) {
427
+ const existing = stores.get(client);
428
+ if (existing !== void 0) return existing;
429
+ const store = {
430
+ client,
431
+ collections: /* @__PURE__ */ new Map(),
432
+ resolvers: [],
433
+ exact: /* @__PURE__ */ new Map(),
434
+ skeletons: /* @__PURE__ */ new Map(),
435
+ insertions: /* @__PURE__ */ new WeakMap(),
436
+ materialized: /* @__PURE__ */ new WeakMap(),
437
+ fetchStartedAt: /* @__PURE__ */ new WeakMap(),
438
+ receipts: /* @__PURE__ */ new WeakMap(),
439
+ rows: /* @__PURE__ */ new WeakMap(),
440
+ batching: 0,
441
+ dirtyIds: /* @__PURE__ */ new Map(),
442
+ dirtyViews: /* @__PURE__ */ new Set()
443
+ };
444
+ stores.set(client, store);
445
+ client.getQueryCache().subscribe((event) => {
446
+ const { query } = event;
447
+ if (event.type === "removed") {
448
+ if (store.skeletons.has(query)) setSkeleton(store, query, void 0);
449
+ return;
450
+ }
451
+ if (event.type !== "updated") return;
452
+ const { type } = event.action;
453
+ if (type !== "fetch" && type !== "success") return;
454
+ const view = viewOf(store, query);
455
+ if (view === void 0) return;
456
+ if (event.action.type === "fetch") {
457
+ store.fetchStartedAt.set(query, tick());
458
+ return;
459
+ }
460
+ if (event.action.type === "success")
461
+ onViewWritten(store, query, view, event.action.manual === true);
462
+ });
463
+ return store;
464
+ }
465
+ function adopt(store, matches) {
466
+ for (const query of store.client.getQueryCache().getAll()) {
467
+ const view = matches(query);
468
+ if (view !== void 0 && query.state.data !== void 0)
469
+ onViewWritten(store, query, view, true);
470
+ }
471
+ }
472
+ function registerKeyedView(client, queryKey, view) {
473
+ const store = storeOf(client);
474
+ const { queryHash } = client.defaultQueryOptions({ queryKey });
475
+ if (store.exact.has(queryHash)) return;
476
+ store.exact.set(queryHash, view);
477
+ adopt(store, (query) => query.queryHash === queryHash ? view : void 0);
478
+ }
479
+ function recordKeyedRead(client, queryKey, startedAt) {
480
+ const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
481
+ if (query !== void 0) storeOf(client).receipts.set(query, startedAt);
482
+ }
483
+ function bakeSettledLayers(collection) {
484
+ const baked = /* @__PURE__ */ new Set();
485
+ const pending = /* @__PURE__ */ new Set();
486
+ collection.layers = collection.layers.filter((layer) => {
487
+ const blocked = [...layer.ids].some((id) => pending.has(id));
488
+ if (!layer.settled || blocked) {
489
+ for (const id of layer.ids) pending.add(id);
490
+ return true;
491
+ }
492
+ for (const id of layer.ids) {
493
+ const current = collection.base.get(id);
494
+ if (current !== void 0)
495
+ collection.base.set(id, layer.apply(current, id));
496
+ baked.add(id);
497
+ }
498
+ return false;
499
+ });
500
+ return baked;
501
+ }
502
+ function predictKeyed(client, token, ids, apply) {
503
+ const store = storeOf(client);
504
+ const collection = collectionOf(store, token);
505
+ const layer = { ids, apply, settled: false };
506
+ collection.layers.push(layer);
507
+ changed(store, collection, ids);
508
+ const live = () => !layer.settled && collection.layers.includes(layer);
509
+ return {
510
+ accept() {
511
+ if (!live()) return;
512
+ const at = tick();
513
+ for (const id of ids) collection.acknowledgedAt.set(id, at);
514
+ layer.settled = true;
515
+ changed(store, collection, [...ids, ...bakeSettledLayers(collection)]);
516
+ },
517
+ remove() {
518
+ if (!live()) return;
519
+ collection.layers = collection.layers.filter((other) => other !== layer);
520
+ changed(store, collection, [...ids, ...bakeSettledLayers(collection)]);
521
+ }
522
+ };
523
+ }
524
+
525
+ // ../query-tags/src/optimistic.ts
526
+ import {
527
+ matchQuery,
528
+ notifyManager as notifyManager2,
529
+ replaceEqualDeep as replaceEqualDeep2
530
+ } from "@tanstack/react-query";
531
+ function optimisticKeyedUpdate(collection, key, update) {
532
+ return {
533
+ collection,
534
+ key,
535
+ update: (current, result) => update(current, result)
536
+ };
537
+ }
109
538
  function optimisticQueryUpdate(queryKey, update, path = []) {
110
539
  return {
111
540
  queryKey,
112
541
  path: [...path],
113
- update: (current) => update(current)
542
+ update: (current, result) => update(current, result)
114
543
  };
115
544
  }
116
545
  var predictions = /* @__PURE__ */ new WeakMap();
117
546
  var receipts = /* @__PURE__ */ new WeakMap();
118
- var order = 0;
547
+ var taggedMeta = /* @__PURE__ */ new WeakSet();
548
+ var syncedClients = /* @__PURE__ */ new WeakMap();
119
549
  function valueAt(data, path) {
120
550
  let value = data;
121
551
  for (const key of path) {
@@ -164,6 +594,22 @@ function confirmedValue(current, predicted, confirmed) {
164
594
  }
165
595
  return next;
166
596
  }
597
+ function rebase(base, visible, next) {
598
+ if (Object.is(visible, next)) return base;
599
+ if (typeof base !== "object" || base === null || typeof visible !== "object" || visible === null || typeof next !== "object" || next === null || Array.isArray(base) || Array.isArray(visible) || Array.isArray(next))
600
+ return next;
601
+ const result = {};
602
+ for (const key of Object.keys(base))
603
+ if (!Object.hasOwn(visible, key) && !Object.hasOwn(next, key))
604
+ result[key] = Reflect.get(base, key);
605
+ for (const key of Object.keys(next))
606
+ result[key] = Object.hasOwn(visible, key) && Object.hasOwn(base, key) ? rebase(
607
+ Reflect.get(base, key),
608
+ Reflect.get(visible, key),
609
+ Reflect.get(next, key)
610
+ ) : Reflect.get(next, key);
611
+ return result;
612
+ }
167
613
  function projected(state) {
168
614
  return state.layers.reduce((data, layer) => {
169
615
  const current = valueAt(data, layer.path);
@@ -189,38 +635,98 @@ function subscribeOptimisticQuery(query, listener) {
189
635
  if (listeners.size === 0) predictionListeners.delete(query);
190
636
  };
191
637
  }
638
+ function isTaggedQuery(query) {
639
+ return query.meta !== void 0 && taggedMeta.has(query.meta);
640
+ }
641
+ function applyLayer(data, layer) {
642
+ const current = valueAt(data, layer.path);
643
+ return replaceAt(
644
+ data,
645
+ layer.path,
646
+ layer.update(current === void 0 ? layer.initial : current.value)
647
+ );
648
+ }
649
+ function confirmLayers(query, state, ready) {
650
+ const tagged = isTaggedQuery(query);
651
+ while (state.layers[0] !== void 0 && ready(state.layers[0])) {
652
+ const layer = state.layers.shift();
653
+ state.base = applyLayer(state.base, layer);
654
+ if (tagged && !layer.fresh) state.guards.push(layer);
655
+ }
656
+ }
657
+ function confirmBeforeWrite(query, state) {
658
+ confirmLayers(query, state, (layer) => layer.acceptedAt !== null);
659
+ }
660
+ function isIdle(state) {
661
+ return state.layers.length === 0 && state.guards.length === 0;
662
+ }
663
+ function untrack(query, state) {
664
+ predictions.delete(query);
665
+ const synced = syncedClients.get(state.client);
666
+ if (synced === void 0) return;
667
+ synced.queries.delete(query);
668
+ if (synced.queries.size === 0) {
669
+ synced.unsubscribe();
670
+ syncedClients.delete(state.client);
671
+ }
672
+ }
673
+ function track(query, state) {
674
+ predictions.set(query, state);
675
+ let synced = syncedClients.get(state.client);
676
+ if (synced === void 0) {
677
+ const queries = /* @__PURE__ */ new Set();
678
+ const unsubscribe = state.client.getQueryCache().subscribe((event) => {
679
+ if (event.type !== "updated" || event.action.type !== "success") return;
680
+ const current = predictions.get(event.query);
681
+ if (current === void 0 || isTaggedQuery(event.query)) return;
682
+ const data = event.query.state.data;
683
+ if (event.action.manual) {
684
+ confirmBeforeWrite(event.query, current);
685
+ current.base = rebase(current.base, current.visible, data);
686
+ } else {
687
+ current.base = data;
688
+ }
689
+ publish(event.query, current);
690
+ });
691
+ synced = { queries, unsubscribe };
692
+ syncedClients.set(state.client, synced);
693
+ }
694
+ synced.queries.add(query);
695
+ }
192
696
  function publish(query, state) {
193
- query.setState({
194
- data: replaceEqualDeep(query.state.data, projected(state))
195
- });
196
- if (state.layers.length === 0) predictions.delete(query);
697
+ if (!isTaggedQuery(query))
698
+ confirmLayers(query, state, (layer) => layer.settled);
699
+ const data = replaceEqualDeep2(query.state.data, projected(state));
700
+ state.visible = data;
701
+ query.setState({ data });
702
+ if (isIdle(state)) untrack(query, state);
197
703
  for (const listener of predictionListeners.get(query) ?? []) listener();
198
704
  }
199
- function taggedReadReceipt(query) {
200
- const paths = [];
201
- return {
202
- start: () => ++order,
203
- record(started, loaded) {
204
- paths.push(...loaded.map((path) => ({ path, started })));
205
- },
206
- commit(data) {
207
- receipts.set(query, { data, paths });
208
- }
209
- };
705
+ function markTaggedQueryMeta(meta) {
706
+ taggedMeta.add(meta);
707
+ }
708
+ function commitTaggedReadReceipt(query, data, started) {
709
+ receipts.set(query, { data, started });
710
+ }
711
+ function consumeReceipt(query, next) {
712
+ const receipt = receipts.get(query);
713
+ if (receipt === void 0 || !Object.is(receipt.data, next)) return;
714
+ receipts.delete(query);
715
+ return receipt;
716
+ }
717
+ function refreshedBy(receipt, layer) {
718
+ return layer.acceptedAt !== null && receipt.started > layer.acceptedAt;
210
719
  }
211
720
  function taggedStructuralSharing(client, queryKey, previous, next) {
212
721
  const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
213
- const state = query === void 0 ? void 0 : predictions.get(query);
214
- if (query !== void 0) {
215
- const receipt = receipts.get(query);
216
- if (receipt !== void 0 && Object.is(receipt.data, next)) {
217
- receipts.delete(query);
218
- if (state !== void 0) {
722
+ if (query !== void 0 && Object.is(previous, query.state.data)) {
723
+ const receipt = consumeReceipt(query, next);
724
+ const state = predictions.get(query);
725
+ if (state !== void 0) {
726
+ if (receipt !== void 0) {
219
727
  const refreshed = /* @__PURE__ */ new Set();
220
728
  for (const layer of state.layers) {
221
- if (layer.acceptedAt !== null && receipt.paths.some(
222
- ({ path, started }) => started > layer.acceptedAt && prefix(path, layer.path)
223
- )) {
729
+ if (refreshedBy(receipt, layer)) {
224
730
  layer.fresh = true;
225
731
  refreshed.add(layer);
226
732
  }
@@ -229,60 +735,129 @@ function taggedStructuralSharing(client, queryKey, previous, next) {
229
735
  (layer) => !layer.settled || !refreshed.has(layer) || olderPending(state, layer)
230
736
  );
231
737
  }
232
- }
233
- if (state !== void 0) {
234
- state.base = next;
738
+ if (receipt !== void 0) {
739
+ state.guards = state.guards.filter(
740
+ (guard) => !refreshedBy(receipt, guard)
741
+ );
742
+ state.base = state.guards.reduce(applyLayer, next);
743
+ } else {
744
+ confirmBeforeWrite(query, state);
745
+ state.base = rebase(state.base, previous, next);
746
+ }
235
747
  next = projected(state);
236
- if (state.layers.length === 0) predictions.delete(query);
748
+ state.visible = next;
749
+ if (isIdle(state)) untrack(query, state);
237
750
  }
238
751
  }
239
752
  const sharing = client.defaultQueryOptions({ queryKey }).structuralSharing;
240
- return sharing === false ? next : typeof sharing === "function" ? sharing(previous, next) : replaceEqualDeep(previous, next);
753
+ return sharing === false ? next : typeof sharing === "function" ? sharing(previous, next) : replaceEqualDeep2(previous, next);
241
754
  }
242
755
  function getTaggedReadData(client, queryKey) {
243
756
  const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
244
757
  const state = query === void 0 ? void 0 : predictions.get(query);
245
758
  return state === void 0 ? query?.state.data : state.base;
246
759
  }
247
- function beginOptimisticMutation(client, updates) {
760
+ function isKeyedUpdate(update) {
761
+ return "collection" in update;
762
+ }
763
+ function beginKeyedPredictions(client, updates, result) {
764
+ const byCollection = /* @__PURE__ */ new Map();
765
+ for (const update of updates) {
766
+ const byKey = byCollection.get(update.collection) ?? /* @__PURE__ */ new Map();
767
+ byKey.set(update.key, [...byKey.get(update.key) ?? [], update]);
768
+ byCollection.set(update.collection, byKey);
769
+ }
770
+ return [...byCollection].map(
771
+ ([collection, byKey]) => predictKeyed(
772
+ client,
773
+ collection,
774
+ new Set(byKey.keys()),
775
+ (entity, key) => (byKey.get(key) ?? []).reduce(
776
+ (current, update) => update.update(current, result()),
777
+ entity
778
+ )
779
+ )
780
+ );
781
+ }
782
+ function beginOptimisticMutation(client, allUpdates) {
248
783
  const owner = {};
249
- const mutationOrder = ++order;
250
- let accepted = false;
784
+ const mutationOrder = tick();
785
+ let accepted;
786
+ let done = false;
787
+ const updates = allUpdates.filter(
788
+ (update) => !isKeyedUpdate(update)
789
+ );
790
+ const keyed = beginKeyedPredictions(
791
+ client,
792
+ allUpdates.filter(isKeyedUpdate),
793
+ () => accepted?.result.value === void 0 ? void 0 : accepted.result
794
+ );
251
795
  const affected = /* @__PURE__ */ new Map();
252
- const rollback = () => notifyManager.batch(() => {
253
- if (accepted) return;
796
+ const attached = new Map(
797
+ updates.map((update) => [update, /* @__PURE__ */ new Set()])
798
+ );
799
+ const attach = (query, update) => {
800
+ const queries = attached.get(update);
801
+ if (queries.has(query) || query.state.data === void 0) return;
802
+ const state = predictions.get(query) ?? {
803
+ client,
804
+ base: query.state.data,
805
+ visible: query.state.data,
806
+ layers: [],
807
+ guards: []
808
+ };
809
+ const current = valueAt(projected(state), update.path);
810
+ if (current === void 0) return;
811
+ queries.add(query);
812
+ const layer = {
813
+ owner,
814
+ order: mutationOrder,
815
+ path: update.path,
816
+ initial: current.value,
817
+ update: (value) => update.update(value, accepted?.result),
818
+ acceptedAt: accepted?.at ?? null,
819
+ fresh: false,
820
+ settled: false
821
+ };
822
+ const index = state.layers.findIndex((other) => other.order > layer.order);
823
+ if (index < 0) state.layers.push(layer);
824
+ else state.layers.splice(index, 0, layer);
825
+ track(query, state);
826
+ affected.set(query, state);
827
+ publish(query, state);
828
+ };
829
+ const unsubscribe = updates.length === 0 ? () => {
830
+ } : client.getQueryCache().subscribe((event) => {
831
+ if (event.type !== "updated" || event.action.type !== "success")
832
+ return;
833
+ for (const update of updates)
834
+ if (matchQuery(
835
+ { queryKey: update.queryKey, exact: true },
836
+ event.query
837
+ ))
838
+ attach(event.query, update);
839
+ });
840
+ const finish = () => {
841
+ done = true;
842
+ unsubscribe();
843
+ };
844
+ const rollback = () => notifyManager2.batch(() => {
845
+ if (accepted !== void 0 || done) return;
846
+ finish();
847
+ for (const prediction of keyed) prediction.remove();
254
848
  for (const [query, state] of affected) {
255
849
  state.layers = state.layers.filter((layer) => layer.owner !== owner);
256
850
  publish(query, state);
257
851
  }
258
852
  });
259
853
  try {
260
- notifyManager.batch(() => {
261
- for (const update of updates) {
262
- const query = client.getQueryCache().get(
263
- client.defaultQueryOptions({ queryKey: update.queryKey }).queryHash
264
- );
265
- if (query === void 0 || query.state.data === void 0) continue;
266
- const state = predictions.get(query) ?? {
267
- base: query.state.data,
268
- layers: []
269
- };
270
- const current = valueAt(projected(state), update.path);
271
- if (current === void 0) continue;
272
- state.layers.push({
273
- owner,
274
- order: mutationOrder,
275
- path: update.path,
276
- initial: current.value,
277
- update: update.update,
278
- acceptedAt: null,
279
- fresh: false,
280
- settled: false
281
- });
282
- predictions.set(query, state);
283
- affected.set(query, state);
284
- publish(query, state);
285
- }
854
+ notifyManager2.batch(() => {
855
+ for (const update of updates)
856
+ for (const query of client.getQueryCache().findAll({
857
+ queryKey: update.queryKey,
858
+ exact: true
859
+ }))
860
+ attach(query, update);
286
861
  });
287
862
  } catch (error) {
288
863
  rollback();
@@ -290,19 +865,27 @@ function beginOptimisticMutation(client, updates) {
290
865
  }
291
866
  return {
292
867
  rollback,
293
- accept() {
294
- accepted = true;
295
- const acceptedAt = ++order;
296
- for (const state of affected.values())
297
- for (const layer of state.layers)
298
- if (layer.owner === owner) layer.acceptedAt = acceptedAt;
868
+ accept(result) {
869
+ accepted = { at: tick(), result: { value: result } };
870
+ notifyManager2.batch(() => {
871
+ for (const prediction of keyed) prediction.accept();
872
+ for (const [query, state] of affected) {
873
+ for (const layer of state.layers)
874
+ if (layer.owner === owner) layer.acceptedAt = accepted.at;
875
+ publish(query, state);
876
+ }
877
+ });
299
878
  },
300
879
  settle() {
301
- notifyManager.batch(() => {
880
+ if (done) return;
881
+ finish();
882
+ notifyManager2.batch(() => {
302
883
  for (const [query, state] of affected) {
884
+ const tagged = isTaggedQuery(query);
303
885
  state.layers = state.layers.filter((layer) => {
304
886
  if (layer.owner !== owner) return true;
305
887
  layer.settled = true;
888
+ if (!tagged) return true;
306
889
  if (!layer.fresh) return true;
307
890
  if (!olderPending(state, layer)) return false;
308
891
  const current = valueAt(state.base, layer.path);
@@ -339,6 +922,7 @@ var registrations = /* @__PURE__ */ new WeakMap();
339
922
  var reads = /* @__PURE__ */ new WeakMap();
340
923
  function taggedQueryOptions(client, queryKey, registration) {
341
924
  const meta = {};
925
+ markTaggedQueryMeta(meta);
342
926
  registrations.set(meta, {
343
927
  scope: registration.scope,
344
928
  tagsOf: (data) => registration.tagsOf(data),
@@ -352,22 +936,20 @@ function taggedQueryOptions(client, queryKey, registration) {
352
936
  function registrationOf(query) {
353
937
  return query.meta === void 0 ? void 0 : registrations.get(query.meta);
354
938
  }
355
- async function runTaggedRead(client, queryKey, read, paths = () => [[]]) {
939
+ async function runTaggedRead(client, queryKey, read) {
356
940
  const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
357
941
  if (query === void 0) return read();
358
942
  const registration = registrationOf(query);
359
- const receipt = taggedReadReceipt(query);
360
943
  for (; ; ) {
361
944
  const pending = { tags: /* @__PURE__ */ new Set(), restart: false };
362
945
  reads.set(query, pending);
363
- const started = receipt.start();
946
+ const started = tick();
364
947
  try {
365
948
  const result = await read();
366
- receipt.record(started, paths());
367
949
  const overlap = registration?.tagsOf(result).some((tag) => pending.tags.has(tag));
368
950
  if (overlap) registration?.onInvalidate?.(result, [...pending.tags]);
369
951
  if (pending.restart || overlap) continue;
370
- receipt.commit(result);
952
+ commitTaggedReadReceipt(query, result, started);
371
953
  return result;
372
954
  } catch (error) {
373
955
  if (pending.restart) continue;
@@ -415,10 +997,11 @@ async function invalidateTags(client, scope, tags) {
415
997
  }
416
998
  async function executeTaggedMutation(invalidate, call, prediction) {
417
999
  const { result, invalidated } = await call();
418
- prediction?.accept();
1000
+ prediction?.accept(result);
419
1001
  const refresh = async () => {
420
1002
  try {
421
- if (invalidated.length > 0) await invalidate(invalidated);
1003
+ if (invalidate !== void 0 && invalidated.length > 0)
1004
+ await invalidate(invalidated);
422
1005
  } finally {
423
1006
  prediction?.settle();
424
1007
  }
@@ -432,7 +1015,13 @@ function restartTaggedRead(query) {
432
1015
  const pending = reads.get(query);
433
1016
  if (pending) pending.restart = true;
434
1017
  }
435
- function useTaggedMutation(client, invalidate, call, optimistic) {
1018
+ function useTaggedMutation({
1019
+ client,
1020
+ invalidate,
1021
+ call,
1022
+ optimistic,
1023
+ meta
1024
+ }) {
436
1025
  const [owner] = useState(() => ({}));
437
1026
  const predict = useRef(optimistic);
438
1027
  useEffect(() => {
@@ -440,7 +1029,7 @@ function useTaggedMutation(client, invalidate, call, optimistic) {
440
1029
  }, [optimistic]);
441
1030
  const mutation = useMutation(
442
1031
  {
443
- meta: { taggedMutationOwner: owner },
1032
+ meta: { ...meta, taggedMutationOwner: owner },
444
1033
  mutationFn: ({ input, prediction }) => executeTaggedMutation(invalidate, () => call(input), prediction)
445
1034
  },
446
1035
  client
@@ -477,8 +1066,33 @@ function useTaggedMutation(client, invalidate, call, optimistic) {
477
1066
  reset: mutation.reset
478
1067
  };
479
1068
  }
1069
+ function hasRows(data) {
1070
+ return typeof data === "object" && data !== null && "result" in data && typeof data.result === "object" && data.result !== null;
1071
+ }
1072
+ var rowKey = (item) => Array.isArray(item) && typeof item[0] === "string" ? item[0] : void 0;
1073
+ var rowValue = (item) => Array.isArray(item) ? item[1] : void 0;
1074
+ function keyedRowsView(collection) {
1075
+ return {
1076
+ collection,
1077
+ slots: (data) => hasRows(data) ? [{ key: "result", items: Object.entries(data.result) }] : void 0,
1078
+ rebuild: (data, items) => hasRows(data) ? {
1079
+ ...data,
1080
+ result: Object.fromEntries(
1081
+ (items.get("result") ?? []).flatMap((item) => {
1082
+ const key = rowKey(item);
1083
+ return key === void 0 ? [] : [[key, rowValue(item)]];
1084
+ })
1085
+ )
1086
+ } : data,
1087
+ keyOf: rowKey,
1088
+ read: (item, current, fresh) => current === void 0 || fresh ? rowValue(item) : current,
1089
+ write: rowValue,
1090
+ render: (item, entity) => Object.is(rowValue(item), entity) ? item : [rowKey(item), entity]
1091
+ };
1092
+ }
480
1093
  function createTaggedKeyedQueryOwner(options) {
481
- const { client, queryKey, scope, read } = options;
1094
+ const { client, queryKey, scope, collection, read } = options;
1095
+ registerKeyedView(client, queryKey, keyedRowsView(collection));
482
1096
  const keys = /* @__PURE__ */ new Map();
483
1097
  let readingKeys = /* @__PURE__ */ new Set();
484
1098
  let missingOnly = false;
@@ -506,76 +1120,73 @@ function createTaggedKeyedQueryOwner(options) {
506
1120
  }),
507
1121
  queryFn: () => {
508
1122
  let previous = getTaggedReadData(client, queryKey);
509
- let loaded = [];
1123
+ const startedAt = /* @__PURE__ */ new Map();
510
1124
  let refresh = !missingOnly && dirtyKeys.size === 0;
511
1125
  missingOnly = false;
512
1126
  const refreshedKeys = /* @__PURE__ */ new Set();
513
1127
  let refreshedAll = false;
514
- return runTaggedRead(
515
- client,
516
- queryKey,
517
- async () => {
518
- const subscribed = await collectSubscribedKeys();
519
- const all = refreshAll || refresh;
520
- refresh = false;
521
- const dirty = new Set(dirtyKeys);
522
- for (const key of dirty) refreshedKeys.add(key);
523
- refreshedAll ||= all;
524
- dirtyKeys.clear();
525
- refreshAll = false;
526
- const requested = subscribed.filter(
527
- (key) => all || dirty.has(key) || !Object.hasOwn(previous?.result ?? {}, key)
1128
+ return runTaggedRead(client, queryKey, async () => {
1129
+ const subscribed = await collectSubscribedKeys();
1130
+ const all = refreshAll || refresh;
1131
+ refresh = false;
1132
+ const dirty = new Set(dirtyKeys);
1133
+ for (const key of dirty) refreshedKeys.add(key);
1134
+ refreshedAll ||= all;
1135
+ dirtyKeys.clear();
1136
+ refreshAll = false;
1137
+ const requested = subscribed.filter(
1138
+ (key) => all || dirty.has(key) || !Object.hasOwn(previous?.result ?? {}, key)
1139
+ );
1140
+ readingKeys = new Set(requested);
1141
+ const started = tick();
1142
+ try {
1143
+ const results = await Promise.all(
1144
+ Array.from(
1145
+ { length: Math.ceil(requested.length / 200) },
1146
+ async (_, i) => {
1147
+ const batch2 = requested.slice(i * 200, (i + 1) * 200);
1148
+ const response = await read(batch2);
1149
+ for (const key of batch2)
1150
+ if (!Object.hasOwn(response.result, key))
1151
+ throw new Error(`Keyed read omitted key ${key}`);
1152
+ return response;
1153
+ }
1154
+ )
528
1155
  );
529
- readingKeys = new Set(requested);
530
- try {
531
- const results = await Promise.all(
532
- Array.from(
533
- { length: Math.ceil(requested.length / 200) },
534
- async (_, i) => {
535
- const batch = requested.slice(i * 200, (i + 1) * 200);
536
- const response = await read(batch);
537
- for (const key of batch)
538
- if (!Object.hasOwn(response.result, key))
539
- throw new Error(`Keyed read omitted key ${key}`);
540
- return response;
541
- }
542
- )
543
- );
544
- const retained = (key) => !all && !dirty.has(key) && !readingKeys.has(key);
545
- loaded = requested;
546
- previous = {
547
- result: Object.fromEntries([
548
- ...Object.entries(previous?.result ?? {}).filter(
549
- ([key]) => retained(key)
550
- ),
551
- ...results.flatMap(
552
- (response) => Object.entries(response.result)
553
- )
554
- ]),
555
- tags: [
556
- .../* @__PURE__ */ new Set([
557
- ...all ? [] : previous?.tags ?? [],
558
- ...results.flatMap((r) => r.tags)
559
- ])
560
- ],
561
- keyTags: Object.fromEntries([
562
- ...Object.entries(previous?.keyTags ?? {}).filter(
563
- ([key]) => retained(key)
564
- ),
565
- ...results.flatMap(
566
- (response) => Object.entries(response.keyTags)
567
- )
1156
+ const retained = (key) => !all && !dirty.has(key) && !readingKeys.has(key);
1157
+ for (const key of requested) startedAt.set(key, started);
1158
+ previous = {
1159
+ result: Object.fromEntries([
1160
+ ...Object.entries(previous?.result ?? {}).filter(
1161
+ ([key]) => retained(key)
1162
+ ),
1163
+ ...results.flatMap((response) => Object.entries(response.result))
1164
+ ]),
1165
+ tags: [
1166
+ .../* @__PURE__ */ new Set([
1167
+ ...all ? [] : previous?.tags ?? [],
1168
+ ...results.flatMap((r) => r.tags)
568
1169
  ])
569
- };
570
- return previous;
571
- } catch (error) {
572
- for (const key of refreshedKeys) dirtyKeys.add(key);
573
- refreshAll ||= refreshedAll;
574
- throw error;
575
- }
576
- },
577
- () => loaded.map((key) => ["result", key])
578
- );
1170
+ ],
1171
+ keyTags: Object.fromEntries([
1172
+ ...Object.entries(previous?.keyTags ?? {}).filter(
1173
+ ([key]) => retained(key)
1174
+ ),
1175
+ ...results.flatMap(
1176
+ (response) => Object.entries(response.keyTags)
1177
+ )
1178
+ ])
1179
+ };
1180
+ return previous;
1181
+ } catch (error) {
1182
+ for (const key of refreshedKeys) dirtyKeys.add(key);
1183
+ refreshAll ||= refreshedAll;
1184
+ throw error;
1185
+ }
1186
+ }).then((data) => {
1187
+ recordKeyedRead(client, queryKey, startedAt);
1188
+ return data;
1189
+ });
579
1190
  }
580
1191
  });
581
1192
  const listeners = /* @__PURE__ */ new Set();
@@ -634,7 +1245,7 @@ function useQuerySelection(subscribe, getSnapshot, select) {
634
1245
  if (cached && Object.is(cached.snapshot, snapshot)) return cached.value;
635
1246
  cached = {
636
1247
  snapshot,
637
- value: replaceEqualDeep2(
1248
+ value: replaceEqualDeep3(
638
1249
  cached?.value ?? committed.current?.value,
639
1250
  select(snapshot)
640
1251
  )
@@ -649,6 +1260,9 @@ function useQuerySelection(subscribe, getSnapshot, select) {
649
1260
  return value;
650
1261
  }
651
1262
 
1263
+ // ../domain/src/shared-types.ts
1264
+ import { z as z2 } from "zod";
1265
+
652
1266
  // ../domain/src/json-value.ts
653
1267
  import { z } from "zod";
654
1268
  var jsonValueSchema = z.lazy(
@@ -666,14 +1280,1149 @@ var jsonObjectSchema = z.record(
666
1280
  jsonValueSchema
667
1281
  );
668
1282
 
669
- // src/internal/rpc-query-host.ts
670
- import { z as z2 } from "zod";
671
- var envelopeSchema = z2.object({
672
- result: jsonValueSchema,
673
- tags: z2.array(z2.string()).default([]),
674
- keyTags: z2.record(z2.string(), z2.array(z2.string())).default({}),
675
- invalidated: z2.array(z2.string()).default([])
1283
+ // ../domain/src/shared-types.ts
1284
+ var reasoningLevelSchema = z2.string().min(1);
1285
+ var serviceTierSchema = z2.string().min(1);
1286
+ var instructionModeValues = ["append", "replace"];
1287
+ var instructionModeSchema = z2.enum(instructionModeValues);
1288
+ var permissionModeValues = ["accept-edits", "auto", "full"];
1289
+ var permissionModeSchema = z2.enum(permissionModeValues);
1290
+ var permissionModeInputSchema = z2.union([permissionModeSchema, z2.literal("workspace-write")]).transform(
1291
+ (permissionMode) => permissionMode === "workspace-write" ? "accept-edits" : permissionMode
1292
+ );
1293
+ var legacyRecordedPermissionModeValues = [
1294
+ "workspace-write",
1295
+ "readonly"
1296
+ ];
1297
+ var recordedPermissionModeSchema = z2.enum([
1298
+ ...permissionModeValues,
1299
+ ...legacyRecordedPermissionModeValues
1300
+ ]);
1301
+ var permissionEscalationValues = ["ask", "deny"];
1302
+ var permissionEscalationSchema = z2.enum(permissionEscalationValues);
1303
+ var promptInputVisibilityValues = ["agent-only"];
1304
+ var promptInputVisibilitySchema = z2.enum(promptInputVisibilityValues);
1305
+ var promptInputVisibilityFields = {
1306
+ visibility: promptInputVisibilitySchema.optional()
1307
+ };
1308
+ var promptMentionPathSourceValues = ["workspace", "thread-storage"];
1309
+ var promptMentionPathSourceSchema = z2.enum(promptMentionPathSourceValues);
1310
+ var promptMentionPathEntryKindValues = ["file", "directory"];
1311
+ var promptMentionPathEntryKindSchema = z2.enum(
1312
+ promptMentionPathEntryKindValues
1313
+ );
1314
+ var promptMentionCommandTriggerValues = ["/", "$"];
1315
+ var promptMentionCommandTriggerSchema = z2.enum(
1316
+ promptMentionCommandTriggerValues
1317
+ );
1318
+ var promptMentionCommandSourceValues = ["skill", "command"];
1319
+ var promptMentionCommandSourceSchema = z2.enum(
1320
+ promptMentionCommandSourceValues
1321
+ );
1322
+ var promptMentionCommandOriginValues = [
1323
+ "builtin",
1324
+ "project",
1325
+ "user"
1326
+ ];
1327
+ var promptMentionCommandOriginSchema = z2.enum(
1328
+ promptMentionCommandOriginValues
1329
+ );
1330
+ var canonicalPromptMentionResourceSchema = z2.discriminatedUnion("kind", [
1331
+ z2.object({
1332
+ kind: z2.literal("thread"),
1333
+ threadId: z2.string(),
1334
+ projectId: z2.string().optional(),
1335
+ label: z2.string()
1336
+ }),
1337
+ z2.object({
1338
+ kind: z2.literal("project"),
1339
+ projectId: z2.string(),
1340
+ label: z2.string()
1341
+ }),
1342
+ z2.object({
1343
+ kind: z2.literal("section"),
1344
+ sectionId: z2.string(),
1345
+ label: z2.string()
1346
+ }),
1347
+ z2.object({
1348
+ kind: z2.literal("path"),
1349
+ source: promptMentionPathSourceSchema,
1350
+ entryKind: promptMentionPathEntryKindSchema,
1351
+ path: z2.string(),
1352
+ label: z2.string()
1353
+ }),
1354
+ z2.object({
1355
+ kind: z2.literal("command"),
1356
+ trigger: promptMentionCommandTriggerSchema,
1357
+ name: z2.string(),
1358
+ source: promptMentionCommandSourceSchema,
1359
+ origin: promptMentionCommandOriginSchema,
1360
+ label: z2.string(),
1361
+ argumentHint: z2.string().nullable()
1362
+ }),
1363
+ z2.object({
1364
+ kind: z2.literal("plugin"),
1365
+ pluginId: z2.string(),
1366
+ icon: z2.string().nullable().optional(),
1367
+ itemId: z2.string(),
1368
+ label: z2.string()
1369
+ }),
1370
+ z2.object({
1371
+ kind: z2.literal("attachment"),
1372
+ path: z2.string(),
1373
+ label: z2.string()
1374
+ })
1375
+ ]);
1376
+ function normalizeLegacyPromptMentionResource(value) {
1377
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1378
+ return value;
1379
+ }
1380
+ const record = value;
1381
+ if (record.kind !== "folder" || typeof record.folderId !== "string") {
1382
+ return value;
1383
+ }
1384
+ const { folderId, ...rest } = record;
1385
+ return { ...rest, kind: "section", sectionId: folderId };
1386
+ }
1387
+ var promptMentionResourceSchema = z2.preprocess(
1388
+ normalizeLegacyPromptMentionResource,
1389
+ canonicalPromptMentionResourceSchema
1390
+ );
1391
+ var promptTextMentionSchema = z2.object({
1392
+ start: z2.number().int().nonnegative(),
1393
+ end: z2.number().int().nonnegative(),
1394
+ resource: promptMentionResourceSchema
1395
+ });
1396
+ var promptInputSchema = z2.discriminatedUnion("type", [
1397
+ z2.object({
1398
+ type: z2.literal("text"),
1399
+ text: z2.string(),
1400
+ mentions: z2.array(promptTextMentionSchema).default([]),
1401
+ ...promptInputVisibilityFields
1402
+ }),
1403
+ z2.object({
1404
+ type: z2.literal("image"),
1405
+ url: z2.string().url(),
1406
+ ...promptInputVisibilityFields
1407
+ }),
1408
+ z2.object({
1409
+ type: z2.literal("localImage"),
1410
+ path: z2.string(),
1411
+ sourceProjectId: z2.string().min(1).optional(),
1412
+ hostId: z2.string().min(1).optional(),
1413
+ ...promptInputVisibilityFields
1414
+ }),
1415
+ z2.object({
1416
+ type: z2.literal("localFile"),
1417
+ path: z2.string(),
1418
+ sourceProjectId: z2.string().min(1).optional(),
1419
+ hostId: z2.string().min(1).optional(),
1420
+ name: z2.string().optional(),
1421
+ sizeBytes: z2.number().int().nonnegative().optional(),
1422
+ mimeType: z2.string().optional(),
1423
+ ...promptInputVisibilityFields
1424
+ })
1425
+ ]);
1426
+ var threadExecutionSourceSchema = z2.enum([
1427
+ "client/thread/start",
1428
+ "client/turn/requested",
1429
+ "client/turn/start"
1430
+ ]);
1431
+ var callerExecutionInputSourceValues = [
1432
+ "explicit",
1433
+ "client-preference"
1434
+ ];
1435
+ var callerExecutionInputSourceSchema = z2.enum(
1436
+ callerExecutionInputSourceValues
1437
+ );
1438
+ var threadExecutionOptionsSchema = z2.object({
1439
+ model: z2.string().optional(),
1440
+ serviceTier: serviceTierSchema.optional(),
1441
+ reasoningLevel: reasoningLevelSchema.optional(),
1442
+ permissionMode: permissionModeSchema.optional(),
1443
+ source: threadExecutionSourceSchema.optional(),
1444
+ seq: z2.number().int().optional()
1445
+ });
1446
+ var resolvedThreadExecutionOptionsSchema = threadExecutionOptionsSchema.extend({
1447
+ model: z2.string().min(1),
1448
+ serviceTier: serviceTierSchema,
1449
+ reasoningLevel: reasoningLevelSchema,
1450
+ permissionMode: permissionModeSchema,
1451
+ source: threadExecutionSourceSchema
1452
+ });
1453
+ var recordedThreadExecutionOptionsSchema = resolvedThreadExecutionOptionsSchema.extend({
1454
+ permissionMode: recordedPermissionModeSchema
1455
+ });
1456
+ var runtimePermissionScopeValues = ["workspace", "full"];
1457
+ var runtimePermissionScopeSchema = z2.enum(runtimePermissionScopeValues);
1458
+ var runtimePermissionPolicySchema = z2.discriminatedUnion(
1459
+ "permissionMode",
1460
+ [
1461
+ z2.object({
1462
+ permissionMode: z2.literal("accept-edits"),
1463
+ permissionScope: z2.literal("workspace"),
1464
+ approvalReviewer: z2.literal("user"),
1465
+ permissionEscalation: permissionEscalationSchema
1466
+ }),
1467
+ z2.object({
1468
+ permissionMode: z2.literal("auto"),
1469
+ permissionScope: z2.literal("workspace"),
1470
+ approvalReviewer: z2.literal("automatic"),
1471
+ permissionEscalation: permissionEscalationSchema
1472
+ }),
1473
+ z2.object({
1474
+ permissionMode: z2.literal("full"),
1475
+ permissionScope: z2.literal("full"),
1476
+ approvalReviewer: z2.null(),
1477
+ permissionEscalation: z2.null()
1478
+ })
1479
+ ]
1480
+ );
1481
+ var promptModeSchema = z2.literal("plan");
1482
+ var sessionOptionValueSchema = z2.union([z2.string(), z2.boolean()]);
1483
+ var sessionOptionSelectionsSchema = z2.record(
1484
+ z2.string().min(1),
1485
+ sessionOptionValueSchema
1486
+ );
1487
+ var runtimeThreadExecutionBaseOptionsSchema = z2.object({
1488
+ model: z2.string().min(1),
1489
+ serviceTier: serviceTierSchema,
1490
+ reasoningLevel: reasoningLevelSchema,
1491
+ promptMode: promptModeSchema.optional(),
1492
+ sessionOptions: sessionOptionSelectionsSchema.optional(),
1493
+ providerOptions: jsonObjectSchema
1494
+ });
1495
+ var runtimeThreadExecutionOptionsSchema = runtimeThreadExecutionBaseOptionsSchema.and(runtimePermissionPolicySchema);
1496
+ var projectExecutionDefaultsSchema = z2.object({
1497
+ providerId: z2.string().min(1),
1498
+ model: z2.string().min(1),
1499
+ serviceTier: serviceTierSchema,
1500
+ reasoningLevel: reasoningLevelSchema,
1501
+ permissionMode: permissionModeSchema
1502
+ });
1503
+
1504
+ // ../domain/src/git-checkout.ts
1505
+ import { z as z3 } from "zod";
1506
+ var gitBranchForbiddenCharacterPattern = /[\u0000-\u001f\u007f\\:~^?*\[]/u;
1507
+ var gitBranchWhitespacePattern = /[ \t]/u;
1508
+ var gitReservedBranchNames = /* @__PURE__ */ new Set([
1509
+ "AUTO_MERGE",
1510
+ "BISECT_HEAD",
1511
+ "CHERRY_PICK_HEAD",
1512
+ "FETCH_HEAD",
1513
+ "HEAD",
1514
+ "MERGE_HEAD",
1515
+ "ORIG_HEAD",
1516
+ "REVERT_HEAD"
1517
+ ]);
1518
+ function isValidGitBranchName(name) {
1519
+ const components = name.split("/");
1520
+ return name.length > 0 && name.trim().length > 0 && !name.startsWith("-") && !name.startsWith("/") && name !== "@" && !gitReservedBranchNames.has(name) && !gitBranchForbiddenCharacterPattern.test(name) && !gitBranchWhitespacePattern.test(name) && !name.includes("..") && !name.includes("@{") && !name.includes("//") && !name.endsWith("/") && !name.endsWith(".") && components.every(
1521
+ (component) => component.length > 0 && !component.startsWith(".") && !component.endsWith(".lock")
1522
+ );
1523
+ }
1524
+ var gitBranchNameSchema = z3.string().refine(isValidGitBranchName, { message: "Invalid git branch name" });
1525
+ var gitBranchSelectionSchema = z3.discriminatedUnion("kind", [
1526
+ z3.object({ kind: z3.literal("named"), name: gitBranchNameSchema }),
1527
+ z3.object({ kind: z3.literal("default") })
1528
+ ]);
1529
+ var gitCheckoutRefSchema = z3.discriminatedUnion("kind", [
1530
+ z3.object({
1531
+ kind: z3.literal("branch"),
1532
+ branchName: z3.string().min(1),
1533
+ headSha: z3.string().min(1).nullable()
1534
+ }),
1535
+ z3.object({
1536
+ kind: z3.literal("detached"),
1537
+ headSha: z3.string().min(1).nullable()
1538
+ }),
1539
+ z3.object({
1540
+ kind: z3.literal("unborn"),
1541
+ branchName: z3.string().min(1).nullable()
1542
+ }),
1543
+ z3.object({
1544
+ kind: z3.literal("unknown"),
1545
+ reason: z3.string().min(1)
1546
+ })
1547
+ ]);
1548
+ var workspaceGitOperationSchema = z3.discriminatedUnion("kind", [
1549
+ z3.object({ kind: z3.literal("none") }),
1550
+ z3.object({
1551
+ kind: z3.literal("merge"),
1552
+ hasConflicts: z3.boolean()
1553
+ }),
1554
+ z3.object({
1555
+ kind: z3.literal("rebase"),
1556
+ hasConflicts: z3.boolean()
1557
+ }),
1558
+ z3.object({
1559
+ kind: z3.literal("cherry-pick"),
1560
+ hasConflicts: z3.boolean()
1561
+ }),
1562
+ z3.object({
1563
+ kind: z3.literal("revert"),
1564
+ hasConflicts: z3.boolean()
1565
+ }),
1566
+ z3.object({
1567
+ kind: z3.literal("unknown"),
1568
+ reason: z3.string().min(1),
1569
+ hasConflicts: z3.boolean()
1570
+ })
1571
+ ]);
1572
+ var gitBranchRefClassificationSchema = z3.object({
1573
+ name: z3.string().min(1),
1574
+ kind: z3.enum(["local", "remote", "missing"])
1575
+ });
1576
+ var defaultBranchRelationSchema = z3.enum([
1577
+ "equal",
1578
+ "local-behind",
1579
+ "local-ahead",
1580
+ "diverged",
1581
+ "unknown"
1582
+ ]);
1583
+ var gitSourceInspectionSchema = z3.object({
1584
+ checkout: gitCheckoutRefSchema,
1585
+ defaultBranch: z3.string().min(1).nullable(),
1586
+ isWorktree: z3.boolean(),
1587
+ defaultBranchRelation: defaultBranchRelationSchema.nullable(),
1588
+ hasUncommittedChanges: z3.boolean(),
1589
+ operation: workspaceGitOperationSchema,
1590
+ originDefaultBranch: z3.string().min(1).nullable()
1591
+ });
1592
+ var gitBranchOptionsSchema = z3.object({
1593
+ branches: z3.array(z3.string()),
1594
+ branchesTruncated: z3.boolean(),
1595
+ remoteBranches: z3.array(z3.string()),
1596
+ remoteBranchesTruncated: z3.boolean(),
1597
+ selectedBranch: gitBranchRefClassificationSchema.nullable()
1598
+ });
1599
+ var projectSourceCheckoutSchema = gitSourceInspectionSchema.extend(
1600
+ gitBranchOptionsSchema.shape
1601
+ );
1602
+
1603
+ // ../domain/src/change-kinds.ts
1604
+ import { z as z18 } from "zod";
1605
+
1606
+ // ../domain/src/thread-event-types.ts
1607
+ import { z as z4 } from "zod";
1608
+ var systemEventTypeValues = [
1609
+ "client/thread/start",
1610
+ "client/turn/requested",
1611
+ "client/turn/rejected",
1612
+ "client/turn/start",
1613
+ "system/error",
1614
+ "system/manager/user_message",
1615
+ "system/thread/interrupted",
1616
+ "system/operation",
1617
+ "system/interaction/lifecycle",
1618
+ "system/permissionGrant/lifecycle",
1619
+ "system/userQuestion/lifecycle",
1620
+ "system/thread-provisioning",
1621
+ "system/provider-turn-watchdog"
1622
+ ];
1623
+ var providerEventTypeValues = [
1624
+ "thread/started",
1625
+ "thread/identity",
1626
+ "turn/started",
1627
+ "turn/completed",
1628
+ "turn/input/accepted",
1629
+ "thread/name/updated",
1630
+ "thread/compacted",
1631
+ "thread/context/cleared",
1632
+ "thread/goal/updated",
1633
+ "thread/goal/cleared",
1634
+ "item/started",
1635
+ "item/completed",
1636
+ "item/agentMessage/delta",
1637
+ "item/commandExecution/outputDelta",
1638
+ "item/fileChange/outputDelta",
1639
+ "item/reasoning/summaryTextDelta",
1640
+ "item/reasoning/textDelta",
1641
+ "item/plan/delta",
1642
+ "item/mcpToolCall/progress",
1643
+ "item/toolCall/progress",
1644
+ "item/backgroundTask/progress",
1645
+ "item/backgroundTask/completed",
1646
+ "item/delegation/progress",
1647
+ "item/delegation/completed",
1648
+ "thread/tokenUsage/updated",
1649
+ "thread/contextWindowUsage/updated",
1650
+ "turn/plan/updated",
1651
+ "turn/mainRun/updated",
1652
+ "turn/diff/updated",
1653
+ "provider/error",
1654
+ "provider/rateLimits/updated",
1655
+ "provider.env-resolved",
1656
+ "thread/extensionState/updated",
1657
+ "provider/warning",
1658
+ "provider/modelFallback",
1659
+ "provider/unhandled"
1660
+ ];
1661
+ var threadEventTypeValues = [
1662
+ ...providerEventTypeValues,
1663
+ ...systemEventTypeValues
1664
+ ];
1665
+ var threadEventTypeSet = new Set(threadEventTypeValues);
1666
+ var threadEventTypeSchema = z4.string().refine(
1667
+ (value) => threadEventTypeSet.has(value),
1668
+ "Invalid thread event type"
1669
+ );
1670
+
1671
+ // ../domain/src/thread.ts
1672
+ import { z as z17 } from "zod";
1673
+
1674
+ // ../domain/src/thread-create-origin.ts
1675
+ import { z as z5 } from "zod";
1676
+ var threadCreateOriginValues = ["app", "cli", "sdk", "plugin"];
1677
+ var threadCreateOriginSchema = z5.enum(threadCreateOriginValues);
1678
+
1679
+ // ../domain/src/environment.ts
1680
+ import { z as z6 } from "zod";
1681
+ var environmentMachineSelectionSchema = z6.discriminatedUnion("type", [
1682
+ z6.object({ type: z6.literal("existing"), hostId: z6.string().min(1) }),
1683
+ z6.object({
1684
+ type: z6.literal("new"),
1685
+ machineProviderId: z6.string().min(1),
1686
+ inputs: jsonValueSchema.nullable()
1687
+ })
1688
+ ]);
1689
+ var environmentProviderSelectionSchema = z6.object({
1690
+ machine: environmentMachineSelectionSchema,
1691
+ inputs: jsonValueSchema.nullable()
1692
+ });
1693
+ var environmentStatusValues = [
1694
+ "creating",
1695
+ "provisioning",
1696
+ "ready",
1697
+ "error",
1698
+ "destroyed"
1699
+ ];
1700
+ var environmentStatusSchema = z6.enum(environmentStatusValues);
1701
+ var environmentHostLifecycleValues = [
1702
+ "active",
1703
+ "removing",
1704
+ "cleanup-failed",
1705
+ "removed"
1706
+ ];
1707
+ var environmentHostLifecycleSchema = z6.enum(
1708
+ environmentHostLifecycleValues
1709
+ );
1710
+ var WORKSPACE_PROVISION_TYPES = [
1711
+ "unmanaged",
1712
+ "managed-worktree",
1713
+ "personal"
1714
+ ];
1715
+ var workspaceProvisionTypeSchema = z6.enum(WORKSPACE_PROVISION_TYPES);
1716
+ var environmentWorkspaceDisplayKindValues = [
1717
+ "managed-worktree",
1718
+ "unmanaged-worktree",
1719
+ "other"
1720
+ ];
1721
+ var environmentWorkspaceDisplayKindSchema = z6.enum(
1722
+ environmentWorkspaceDisplayKindValues
1723
+ );
1724
+ var discoveredWorkspacePropertiesSchema = z6.object({
1725
+ path: z6.string().min(1),
1726
+ isGitRepo: z6.boolean(),
1727
+ isWorktree: z6.boolean(),
1728
+ branchName: z6.string().nullable(),
1729
+ defaultBranch: z6.string().nullable()
1730
+ });
1731
+ var environmentLifecycleSchema = z6.object({
1732
+ phase: z6.enum(["active", "retiring", "teardown", "destroyed"]),
1733
+ retireAt: z6.number().nullable(),
1734
+ teardown: z6.object({
1735
+ status: z6.enum(["running", "failed", "removed"]),
1736
+ attempt: z6.number().int().nonnegative(),
1737
+ message: z6.string().optional()
1738
+ }).nullable()
1739
+ });
1740
+ var environmentSchema = z6.object({
1741
+ id: z6.string(),
1742
+ name: z6.string().nullable(),
1743
+ projectId: z6.string(),
1744
+ hostId: z6.string(),
1745
+ path: z6.string().nullable(),
1746
+ isGitRepo: z6.boolean(),
1747
+ isWorktree: z6.boolean(),
1748
+ branchName: z6.string().nullable(),
1749
+ baseBranch: z6.string().nullable(),
1750
+ defaultBranch: z6.string().nullable(),
1751
+ mergeBaseBranch: z6.string().nullable(),
1752
+ status: environmentStatusSchema,
1753
+ environmentProviderId: z6.string().nullable(),
1754
+ lifecycle: environmentLifecycleSchema,
1755
+ hostLifecycle: environmentHostLifecycleSchema,
1756
+ environmentProviderSelection: environmentProviderSelectionSchema.nullable(),
1757
+ environmentProviderInstanceKey: z6.string().nullable(),
1758
+ managed: z6.boolean(),
1759
+ workspaceProvisionType: workspaceProvisionTypeSchema.nullable(),
1760
+ createdAt: z6.number(),
1761
+ updatedAt: z6.number()
1762
+ });
1763
+
1764
+ // ../domain/src/queued-message.ts
1765
+ import { z as z10 } from "zod";
1766
+
1767
+ // ../domain/src/plugin-id.ts
1768
+ import { z as z7 } from "zod";
1769
+ var pluginIdSchema = z7.string().regex(/^[a-z0-9][a-z0-9-]*$/u);
1770
+
1771
+ // ../domain/src/protocol-ids.ts
1772
+ import { z as z8 } from "zod";
1773
+ var clientTurnRequestIdSchema = z8.string().regex(/^creq_[23456789abcdefghijkmnpqrstuvwxyz]{10}$/u);
1774
+
1775
+ // ../domain/src/system-message.ts
1776
+ import { z as z9 } from "zod";
1777
+ var systemMessageKindValues = [
1778
+ "ownership-assigned",
1779
+ "ownership-removed",
1780
+ "child-needs-attention",
1781
+ "child-completed",
1782
+ "child-failed",
1783
+ "child-interrupted",
1784
+ "child-outcome-batch",
1785
+ "tool-result-delivered",
1786
+ "environment-directory-updated",
1787
+ "unlabeled"
1788
+ ];
1789
+ var systemMessageKindSchema = z9.enum(systemMessageKindValues);
1790
+ var systemThreadInterruptedReasonSchema = z9.enum([
1791
+ "manual-stop",
1792
+ "host-daemon-restarted",
1793
+ "host-removed",
1794
+ "provider-turn-idle"
1795
+ ]);
1796
+ var childThreadOutcomeSchema = z9.object({
1797
+ threadId: z9.string(),
1798
+ status: z9.enum(["completed", "failed", "interrupted"]),
1799
+ interruption: z9.object({
1800
+ reason: systemThreadInterruptedReasonSchema,
1801
+ cause: z9.literal("host-connection-lost").optional()
1802
+ }).optional()
1803
+ });
1804
+ var systemMessageSubjectSchema = z9.discriminatedUnion("kind", [
1805
+ z9.object({
1806
+ kind: z9.literal("thread"),
1807
+ threadId: z9.string(),
1808
+ threadName: z9.string(),
1809
+ outcomes: z9.array(childThreadOutcomeSchema).optional()
1810
+ }),
1811
+ z9.object({
1812
+ kind: z9.literal("thread-batch"),
1813
+ count: z9.number(),
1814
+ outcomes: z9.array(childThreadOutcomeSchema).optional()
1815
+ }),
1816
+ z9.object({
1817
+ kind: z9.literal("tool-call"),
1818
+ toolName: z9.string(),
1819
+ suppress: z9.boolean()
1820
+ }),
1821
+ z9.object({
1822
+ kind: z9.literal("directory"),
1823
+ path: z9.string()
1824
+ })
1825
+ ]);
1826
+
1827
+ // ../domain/src/queued-message.ts
1828
+ var queuedMessageWaitingOnKindValues = [
1829
+ "time",
1830
+ "thread-busy",
1831
+ "stopping",
1832
+ "turn-starting",
1833
+ "provisioning",
1834
+ "host-offline",
1835
+ "interaction",
1836
+ "plugin"
1837
+ ];
1838
+ var queuedMessageWaitingOnKindSchema = z10.enum(
1839
+ queuedMessageWaitingOnKindValues
1840
+ );
1841
+ var queuedMessageWaitHostNameSchema = z10.string().min(1).max(200);
1842
+ var QUEUED_MESSAGE_WAIT_REASON_MAX_LENGTH = 200;
1843
+ var queuedMessageWaitReasonSchema = z10.string().min(1).max(QUEUED_MESSAGE_WAIT_REASON_MAX_LENGTH);
1844
+ var queuedMessageWaitingOnSchema = z10.discriminatedUnion("kind", [
1845
+ z10.object({ kind: z10.literal("time") }),
1846
+ z10.object({ kind: z10.literal("thread-busy") }),
1847
+ z10.object({ kind: z10.literal("stopping") }),
1848
+ z10.object({ kind: z10.literal("turn-starting") }),
1849
+ z10.object({ kind: z10.literal("provisioning") }),
1850
+ z10.object({
1851
+ kind: z10.literal("host-offline"),
1852
+ hostName: queuedMessageWaitHostNameSchema
1853
+ }),
1854
+ z10.object({ kind: z10.literal("interaction") }),
1855
+ z10.object({
1856
+ kind: z10.literal("plugin"),
1857
+ pluginId: pluginIdSchema,
1858
+ reason: queuedMessageWaitReasonSchema
1859
+ })
1860
+ ]);
1861
+ var QUEUED_MESSAGE_FAILURE_REASON_MAX_LENGTH = 200;
1862
+ var queuedMessageFailureReasonSchema = z10.string().min(1).max(QUEUED_MESSAGE_FAILURE_REASON_MAX_LENGTH);
1863
+ var QUEUED_MESSAGE_PLUGIN_WAIT_HOLDER_PREFIX = "plugin:";
1864
+ var queuedMessageWaitHolderSchema = z10.templateLiteral([
1865
+ QUEUED_MESSAGE_PLUGIN_WAIT_HOLDER_PREFIX,
1866
+ pluginIdSchema
1867
+ ]);
1868
+ var queuedMessagePayloadKindValues = ["inline", "retry"];
1869
+ var queuedMessagePayloadKindSchema = z10.enum(
1870
+ queuedMessagePayloadKindValues
1871
+ );
1872
+ var queuedMessagePayloadSchema = z10.discriminatedUnion("kind", [
1873
+ z10.object({ kind: z10.literal("inline") }),
1874
+ z10.object({
1875
+ kind: z10.literal("retry"),
1876
+ /**
1877
+ * The ORIGINAL request, not the attempt that just failed. Retrying a retry
1878
+ * re-submits the same original blocks, so this id is carried forward
1879
+ * unchanged across attempts and `attempt` is what distinguishes them.
1880
+ */
1881
+ retryOfTurnRequestId: clientTurnRequestIdSchema,
1882
+ /** Which attempt this row will dispatch: 2 is the first retry. */
1883
+ attempt: z10.number().int().min(2),
1884
+ /**
1885
+ * Why this turn is being retried, in the retrier's words ("Rate limited"),
1886
+ * as the row's card and `bb thread queue list` render it.
1887
+ *
1888
+ * It lives on the payload rather than on `waitingOn` because a retry can
1889
+ * wait on the clock, on a limiter, or on nothing at all, and the reason
1890
+ * outlives all three: it is a fact about the retry, not about what is
1891
+ * currently holding it. Filled at the boundary, so every row has one.
1892
+ */
1893
+ reason: queuedMessageWaitReasonSchema
1894
+ })
1895
+ ]);
1896
+ var queuedMessageSystemNoticeSchema = z10.object({
1897
+ kind: systemMessageKindSchema,
1898
+ subject: systemMessageSubjectSchema.nullable()
1899
+ });
1900
+
1901
+ // ../domain/src/queued-message-lifecycle.ts
1902
+ import { z as z11 } from "zod";
1903
+ var queuedMessageStateValues = [
1904
+ "queued",
1905
+ "scheduled",
1906
+ "waiting",
1907
+ "failed_retrying",
1908
+ "failed_exhausted",
1909
+ "claimed"
1910
+ ];
1911
+ var queuedMessageStateSchema = z11.enum(queuedMessageStateValues);
1912
+
1913
+ // ../domain/src/thread-status.ts
1914
+ import { z as z12 } from "zod";
1915
+ var threadStatusValues = [
1916
+ "pending",
1917
+ "idle",
1918
+ "starting",
1919
+ "active",
1920
+ "stopping",
1921
+ "error"
1922
+ ];
1923
+ var threadStatusSchema = z12.enum(threadStatusValues);
1924
+
1925
+ // ../domain/src/thread-origin-kind.ts
1926
+ import { z as z13 } from "zod";
1927
+ var threadOriginKindValues = ["fork"];
1928
+ var threadOriginKindSchema = z13.enum(threadOriginKindValues);
1929
+
1930
+ // ../domain/src/thread-parent-notifications.ts
1931
+ import { z as z14 } from "zod";
1932
+ var threadParentNotificationsValues = [
1933
+ "auto",
1934
+ "stuck",
1935
+ "off"
1936
+ ];
1937
+ var threadParentNotificationsSchema = z14.enum(
1938
+ threadParentNotificationsValues
1939
+ );
1940
+
1941
+ // ../domain/src/thread-visibility.ts
1942
+ import { z as z15 } from "zod";
1943
+ var threadVisibilityValues = ["visible", "hidden"];
1944
+ var threadVisibilitySchema = z15.enum(threadVisibilityValues);
1945
+
1946
+ // ../domain/src/thread-runtime-state.ts
1947
+ import { z as z16 } from "zod";
1948
+ var threadRuntimeDisplayStatusValues = [
1949
+ ...threadStatusValues,
1950
+ "provisioning",
1951
+ "waiting-for-host"
1952
+ ];
1953
+ var threadRuntimeDisplayStatusSchema = z16.enum(
1954
+ threadRuntimeDisplayStatusValues
1955
+ );
1956
+ var threadRuntimeStateSchema = z16.object({
1957
+ displayStatus: threadRuntimeDisplayStatusSchema
1958
+ });
1959
+ var threadActivityStateSchema = z16.object({
1960
+ activeWorkflowCount: z16.number().int().nonnegative(),
1961
+ activeBackgroundAgentCount: z16.number().int().nonnegative(),
1962
+ activeBackgroundCommandCount: z16.number().int().nonnegative(),
1963
+ activePlanModeCount: z16.number().int().nonnegative(),
1964
+ activeGoalCount: z16.number().int().nonnegative()
1965
+ });
1966
+
1967
+ // ../domain/src/thread.ts
1968
+ var workspaceStateValues = [
1969
+ "clean",
1970
+ "untracked",
1971
+ "dirty_uncommitted",
1972
+ "committed_unmerged",
1973
+ "dirty_and_committed_unmerged"
1974
+ ];
1975
+ var workspaceStateSchema = z17.enum(workspaceStateValues);
1976
+ var workspaceFileStatusKindSchema = z17.enum([
1977
+ "M",
1978
+ "A",
1979
+ "D",
1980
+ "R",
1981
+ "C",
1982
+ "U",
1983
+ "??",
1984
+ "?"
1985
+ ]);
1986
+ var workspaceFileStatusSchema = z17.object({
1987
+ path: z17.string(),
1988
+ status: workspaceFileStatusKindSchema,
1989
+ insertions: z17.number().nullable(),
1990
+ deletions: z17.number().nullable()
1991
+ });
1992
+ var workspaceCommitSummarySchema = z17.object({
1993
+ sha: z17.string(),
1994
+ shortSha: z17.string(),
1995
+ subject: z17.string(),
1996
+ authorName: z17.string(),
1997
+ authoredAt: z17.number()
1998
+ });
1999
+ var workspaceChangeStatsSchema = z17.object({
2000
+ insertions: z17.number(),
2001
+ deletions: z17.number(),
2002
+ lineStatsComplete: z17.boolean(),
2003
+ fileCount: z17.number().int().nonnegative(),
2004
+ files: z17.array(workspaceFileStatusSchema)
2005
+ });
2006
+ var workspaceWorkingTreeSchema = workspaceChangeStatsSchema.extend({
2007
+ hasUncommittedChanges: z17.boolean(),
2008
+ state: workspaceStateSchema
2009
+ });
2010
+ var workspaceBranchSchema = z17.object({
2011
+ currentBranch: z17.string().nullable(),
2012
+ defaultBranch: z17.string()
2013
+ });
2014
+ var workspaceMergeBaseSchema = workspaceChangeStatsSchema.extend({
2015
+ mergeBaseBranch: z17.string(),
2016
+ baseRef: z17.string().nullable(),
2017
+ aheadCount: z17.number(),
2018
+ behindCount: z17.number(),
2019
+ squashMergeCheckComplete: z17.boolean(),
2020
+ hasCommittedUnmergedChanges: z17.boolean(),
2021
+ commits: z17.array(workspaceCommitSummarySchema)
2022
+ });
2023
+ var workspaceStatusSchema = z17.object({
2024
+ workingTree: workspaceWorkingTreeSchema,
2025
+ checkout: gitCheckoutRefSchema,
2026
+ branch: workspaceBranchSchema,
2027
+ mergeBase: workspaceMergeBaseSchema.nullable()
676
2028
  });
2029
+ var threadQueuedMessageSchema = z17.object({
2030
+ id: z17.string(),
2031
+ origin: threadCreateOriginSchema.nullable(),
2032
+ originPluginId: z17.string().nullable(),
2033
+ initiator: z17.enum(["user", "agent", "system"]),
2034
+ senderThreadId: z17.string().nullable(),
2035
+ /**
2036
+ * The thread this row is waiting on. Redundant on the thread-scoped list
2037
+ * route that first served this DTO, and load-bearing everywhere else it is
2038
+ * now served: a `queue.*` plugin event and a cross-thread wait-holder query
2039
+ * both hand out rows with no surrounding thread to read it from.
2040
+ */
2041
+ threadId: z17.string(),
2042
+ content: z17.array(promptInputSchema).min(1),
2043
+ model: z17.string().min(1),
2044
+ reasoningLevel: reasoningLevelSchema,
2045
+ permissionMode: permissionModeSchema,
2046
+ serviceTier: serviceTierSchema,
2047
+ groupWithNext: z17.boolean(),
2048
+ /**
2049
+ * Epoch ms this row is scheduled to attempt dispatch, or null when it is
2050
+ * eligible as soon as its other waits clear.
2051
+ */
2052
+ sendAt: z17.number().int().nonnegative().nullable(),
2053
+ state: queuedMessageStateSchema,
2054
+ /**
2055
+ * Why this row is queued, or null for a `queued` row that is simply next in
2056
+ * line behind the running turn.
2057
+ */
2058
+ waitingOn: queuedMessageWaitingOnSchema.nullable(),
2059
+ /**
2060
+ * Why this row's last DRAIN attempt failed outright, or null when it has not
2061
+ * failed one — which is every row that has never been re-attempted, and
2062
+ * every row whose latest attempt merely queued again. An inline attempt
2063
+ * reports its failure to the sender that is still listening and never lands
2064
+ * here.
2065
+ *
2066
+ * Independent of `waitingOn`, not folded into it: the row is still waiting on
2067
+ * whatever it was waiting on, and writing a wait rewrites it wholesale, so a
2068
+ * failure stored there would not survive the next attempt.
2069
+ */
2070
+ failureReason: queuedMessageFailureReasonSchema.nullable(),
2071
+ payload: queuedMessagePayloadSchema,
2072
+ /**
2073
+ * Whether the sender may still rewrite this row's input. Not derivable from
2074
+ * `payload` alone: a `retry` row is never editable, and an `inline` row
2075
+ * stops being editable once the drain has claimed it — and the claim is
2076
+ * deliberately not part of this response, since it is drain bookkeeping and
2077
+ * not something a client should reason about. The server folds both into
2078
+ * this one answer.
2079
+ */
2080
+ editable: z17.boolean(),
2081
+ createdAt: z17.number(),
2082
+ updatedAt: z17.number()
2083
+ });
2084
+ var threadSchema = z17.object({
2085
+ id: z17.string(),
2086
+ projectId: z17.string(),
2087
+ environmentId: z17.string().nullable(),
2088
+ providerId: z17.string(),
2089
+ title: z17.string().nullable(),
2090
+ titleFallback: z17.string().nullable(),
2091
+ sectionId: z17.string().nullable(),
2092
+ status: threadStatusSchema,
2093
+ parentThreadId: z17.string().nullable(),
2094
+ lifecycleOwnerThreadId: z17.string().nullable(),
2095
+ sourceThreadId: z17.string().nullable(),
2096
+ originKind: threadOriginKindSchema.nullable(),
2097
+ originPluginId: z17.string().nullable(),
2098
+ visibility: threadVisibilitySchema,
2099
+ parentNotifications: threadParentNotificationsSchema,
2100
+ archivedAt: z17.number().nullable(),
2101
+ pinnedAt: z17.number().nullable(),
2102
+ deletedAt: z17.number().nullable(),
2103
+ lastReadAt: z17.number().nullable(),
2104
+ latestAttentionAt: z17.number(),
2105
+ createdAt: z17.number(),
2106
+ updatedAt: z17.number()
2107
+ });
2108
+ var threadWithRuntimeSchema = threadSchema.extend({
2109
+ runtime: threadRuntimeStateSchema
2110
+ });
2111
+ var threadQueuedWorkValues = ["none", "waiting", "failed"];
2112
+ var threadQueuedWorkSchema = z17.enum(threadQueuedWorkValues);
2113
+ var threadListEntrySchema = threadWithRuntimeSchema.extend({
2114
+ activity: threadActivityStateSchema,
2115
+ queuedWork: threadQueuedWorkSchema,
2116
+ pinSortKey: z17.string().nullable(),
2117
+ hasPendingInteraction: z17.boolean(),
2118
+ environmentHostId: z17.string().nullable(),
2119
+ environmentName: z17.string().nullable(),
2120
+ environmentBranchName: z17.string().nullable(),
2121
+ environmentPath: z17.string().nullable(),
2122
+ environmentProviderId: z17.string().nullable(),
2123
+ environmentIsWorktree: z17.boolean().nullable(),
2124
+ environmentWorkspaceDisplayKind: environmentWorkspaceDisplayKindSchema
2125
+ });
2126
+
2127
+ // ../domain/src/change-kinds.ts
2128
+ var THREAD_CHANGE_KINDS = [
2129
+ "thread-created",
2130
+ "thread-deleted",
2131
+ "events-appended",
2132
+ "history-rewritten",
2133
+ "history-compacted",
2134
+ "interactions-changed",
2135
+ "status-changed",
2136
+ "title-changed",
2137
+ "queue-changed",
2138
+ "archived-changed",
2139
+ "pin-state-changed",
2140
+ "parent-changed",
2141
+ "environment-changed",
2142
+ "read-state-changed",
2143
+ "tabs-changed",
2144
+ "terminals-changed"
2145
+ ];
2146
+ var PROJECT_CHANGE_KINDS = [
2147
+ "project-created",
2148
+ "project-updated",
2149
+ "project-deleted",
2150
+ "project-sources-changed",
2151
+ "threads-changed",
2152
+ "project-order-changed"
2153
+ ];
2154
+ var ENVIRONMENT_CHANGE_KINDS = [
2155
+ "environment-created",
2156
+ "environment-deleted",
2157
+ "metadata-changed",
2158
+ "status-changed",
2159
+ "work-status-changed",
2160
+ "git-refs-changed",
2161
+ "thread-storage-changed",
2162
+ "diff-viewed-changed"
2163
+ ];
2164
+ var HOST_CHANGE_KINDS = [
2165
+ "host-connected",
2166
+ "host-disconnected",
2167
+ "provider-model-catalog-changed"
2168
+ ];
2169
+ var SYSTEM_CHANGE_KINDS = [
2170
+ "config-changed",
2171
+ "plugins-changed",
2172
+ "plugin-install-jobs-changed",
2173
+ "plugin-update-jobs-changed",
2174
+ "provider-registrations-changed",
2175
+ "environment-availability-changed",
2176
+ "server-move-changed",
2177
+ "app-update-changed"
2178
+ ];
2179
+ var threadChangeKindSchema = z18.enum(THREAD_CHANGE_KINDS);
2180
+ var projectChangeKindSchema = z18.enum(PROJECT_CHANGE_KINDS);
2181
+ var environmentChangeKindSchema = z18.enum(ENVIRONMENT_CHANGE_KINDS);
2182
+ var hostChangeKindSchema = z18.enum(HOST_CHANGE_KINDS);
2183
+ var systemChangeKindSchema = z18.enum(SYSTEM_CHANGE_KINDS);
2184
+ var threadTimelineSubscriptionTargetSchema = z18.object({
2185
+ kind: z18.literal("thread-timeline"),
2186
+ threadId: z18.string().min(1),
2187
+ segmentLimit: z18.number().int().positive().nullable(),
2188
+ deferContent: z18.boolean()
2189
+ }).strict();
2190
+ function canonicalPluginReadInput(value) {
2191
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
2192
+ if (Array.isArray(value))
2193
+ return `[${value.map(canonicalPluginReadInput).join(",")}]`;
2194
+ return `{${Object.keys(value).sort().map(
2195
+ (key) => `${JSON.stringify(key)}:${canonicalPluginReadInput(value[key])}`
2196
+ ).join(",")}}`;
2197
+ }
2198
+ var pluginReadSubscriptionTargetSchema = z18.object({
2199
+ kind: z18.literal("plugin-read"),
2200
+ pluginId: z18.string().min(1),
2201
+ method: z18.string().min(1),
2202
+ read: z18.union([
2203
+ z18.object({ input: jsonValueSchema }).strict(),
2204
+ z18.object({ key: z18.string() }).strict()
2205
+ ]).refine(
2206
+ (read) => new TextEncoder().encode(canonicalPluginReadInput(read)).byteLength <= 16384,
2207
+ "Plugin read input exceeds 16 KiB"
2208
+ )
2209
+ }).strict();
2210
+ var realtimeSubscriptionTargetSchema = z18.discriminatedUnion("kind", [
2211
+ pluginReadSubscriptionTargetSchema,
2212
+ z18.object({ kind: z18.literal("plugin"), pluginId: z18.string().min(1) }).strict(),
2213
+ z18.object({
2214
+ kind: z18.literal("thread-detail"),
2215
+ threadId: z18.string().min(1)
2216
+ }).strict(),
2217
+ threadTimelineSubscriptionTargetSchema,
2218
+ z18.object({
2219
+ kind: z18.literal("thread-list")
2220
+ }).strict(),
2221
+ z18.object({
2222
+ kind: z18.literal("project-detail"),
2223
+ projectId: z18.string().min(1)
2224
+ }).strict(),
2225
+ z18.object({
2226
+ kind: z18.literal("project-list")
2227
+ }).strict(),
2228
+ z18.object({
2229
+ kind: z18.literal("environment-detail"),
2230
+ environmentId: z18.string().min(1)
2231
+ }).strict(),
2232
+ z18.object({
2233
+ kind: z18.literal("environment-list")
2234
+ }).strict(),
2235
+ z18.object({
2236
+ kind: z18.literal("host-detail"),
2237
+ hostId: z18.string().min(1)
2238
+ }).strict(),
2239
+ z18.object({
2240
+ kind: z18.literal("host-list")
2241
+ }).strict(),
2242
+ z18.object({
2243
+ kind: z18.literal("system")
2244
+ }).strict()
2245
+ ]);
2246
+ function isValidSubscriptionTarget(value) {
2247
+ return realtimeSubscriptionTargetSchema.safeParse(value).success;
2248
+ }
2249
+ var validSubscriptionTargetsSchema = z18.preprocess(
2250
+ (value) => Array.isArray(value) ? value.filter(isValidSubscriptionTarget) : value,
2251
+ z18.array(realtimeSubscriptionTargetSchema)
2252
+ );
2253
+ var validSubscriptionTargetSchema = z18.preprocess(
2254
+ (value) => value === void 0 || isValidSubscriptionTarget(value) ? value : null,
2255
+ realtimeSubscriptionTargetSchema.nullable().optional()
2256
+ );
2257
+ var subscriptionFields = {
2258
+ target: validSubscriptionTargetSchema,
2259
+ targets: validSubscriptionTargetsSchema.optional()
2260
+ };
2261
+ var hasSubscriptionTargets = (value) => value.target !== void 0 !== (value.targets !== void 0);
2262
+ var subscribeMessageSchema = z18.object({ type: z18.literal("subscribe"), ...subscriptionFields }).refine(hasSubscriptionTargets);
2263
+ var unsubscribeMessageSchema = z18.object({ type: z18.literal("unsubscribe"), ...subscriptionFields }).refine(hasSubscriptionTargets);
2264
+ var pingMessageSchema = z18.object({
2265
+ type: z18.literal("ping")
2266
+ });
2267
+ var visibilityMessageSchema = z18.object({
2268
+ type: z18.literal("visibility"),
2269
+ visible: z18.boolean()
2270
+ });
2271
+ var clientMessageSchema = z18.discriminatedUnion("type", [
2272
+ subscribeMessageSchema,
2273
+ unsubscribeMessageSchema,
2274
+ pingMessageSchema,
2275
+ visibilityMessageSchema
2276
+ ]);
2277
+ var pongMessageSchema = z18.object({
2278
+ type: z18.literal("pong")
2279
+ }).strict();
2280
+ var pongMessageLenientSchema = z18.object({
2281
+ type: z18.literal("pong")
2282
+ });
2283
+ var threadStatusChangeMetadataSchema = z18.object({
2284
+ status: threadStatusSchema,
2285
+ runtime: threadRuntimeStateSchema,
2286
+ activity: threadActivityStateSchema,
2287
+ latestAttentionAt: z18.number(),
2288
+ updatedAt: z18.number()
2289
+ }).strict();
2290
+ var threadChangeMetadataSchema = z18.object({
2291
+ backgroundActivityChanged: z18.boolean().optional(),
2292
+ eventTypes: z18.array(threadEventTypeSchema).readonly().optional(),
2293
+ timelineSequence: z18.number().int().nonnegative().optional(),
2294
+ hasPendingInteraction: z18.boolean().optional(),
2295
+ projectId: z18.string().optional(),
2296
+ statusChange: threadStatusChangeMetadataSchema.optional()
2297
+ }).strict();
2298
+ var threadChangedMessageSchema = z18.object({
2299
+ type: z18.literal("changed"),
2300
+ entity: z18.literal("thread"),
2301
+ id: z18.string().optional(),
2302
+ metadata: threadChangeMetadataSchema.optional(),
2303
+ changes: z18.array(threadChangeKindSchema).readonly()
2304
+ }).strict();
2305
+ var projectChangedMessageSchema = z18.object({
2306
+ type: z18.literal("changed"),
2307
+ entity: z18.literal("project"),
2308
+ id: z18.string().optional(),
2309
+ changes: z18.array(projectChangeKindSchema).readonly()
2310
+ }).strict();
2311
+ var environmentChangedMessageSchema = z18.object({
2312
+ type: z18.literal("changed"),
2313
+ entity: z18.literal("environment"),
2314
+ id: z18.string().optional(),
2315
+ changes: z18.array(environmentChangeKindSchema).readonly()
2316
+ }).strict();
2317
+ var hostChangedMessageSchema = z18.object({
2318
+ type: z18.literal("changed"),
2319
+ entity: z18.literal("host"),
2320
+ id: z18.string().optional(),
2321
+ changes: z18.array(hostChangeKindSchema).readonly()
2322
+ }).strict();
2323
+ var systemChangedMessageSchema = z18.object({
2324
+ type: z18.literal("changed"),
2325
+ entity: z18.literal("system"),
2326
+ changes: z18.array(systemChangeKindSchema).readonly()
2327
+ }).strict();
2328
+ var tagsChangedMessageSchema = z18.object({
2329
+ type: z18.literal("changed"),
2330
+ entity: z18.literal("tags"),
2331
+ tags: z18.array(z18.string().min(1)).min(1)
2332
+ }).strict();
2333
+ var pluginChangedMessageSchema = z18.object({
2334
+ type: z18.literal("changed"),
2335
+ entity: z18.literal("plugin"),
2336
+ pluginId: z18.string().min(1),
2337
+ tags: z18.array(z18.string().min(1)).min(1).nullable()
2338
+ }).strict();
2339
+ var changedMessageSchema = z18.discriminatedUnion("entity", [
2340
+ threadChangedMessageSchema,
2341
+ projectChangedMessageSchema,
2342
+ environmentChangedMessageSchema,
2343
+ hostChangedMessageSchema,
2344
+ systemChangedMessageSchema,
2345
+ tagsChangedMessageSchema,
2346
+ pluginChangedMessageSchema
2347
+ ]);
2348
+ function lenientKinds(kinds) {
2349
+ const known = new Set(kinds);
2350
+ return z18.array(z18.string()).transform(
2351
+ (values) => values.filter((value) => known.has(value))
2352
+ );
2353
+ }
2354
+ var knownThreadEventTypes = new Set(
2355
+ threadEventTypeValues
2356
+ );
2357
+ var threadChangeMetadataLenientSchema = z18.object({
2358
+ timelineSequence: z18.number().int().nonnegative().optional(),
2359
+ backgroundActivityChanged: z18.boolean().optional(),
2360
+ eventTypes: z18.array(z18.string()).transform(
2361
+ (values) => values.filter(
2362
+ (value) => knownThreadEventTypes.has(value)
2363
+ )
2364
+ ).optional(),
2365
+ hasPendingInteraction: z18.boolean().optional(),
2366
+ projectId: z18.string().optional(),
2367
+ statusChange: threadStatusChangeMetadataSchema.optional().catch(void 0)
2368
+ });
2369
+ var threadChangedMessageLenientSchema = z18.object({
2370
+ type: z18.literal("changed"),
2371
+ entity: z18.literal("thread"),
2372
+ id: z18.string().optional(),
2373
+ metadata: threadChangeMetadataLenientSchema.optional(),
2374
+ changes: lenientKinds(THREAD_CHANGE_KINDS)
2375
+ });
2376
+ var projectChangedMessageLenientSchema = z18.object({
2377
+ type: z18.literal("changed"),
2378
+ entity: z18.literal("project"),
2379
+ id: z18.string().optional(),
2380
+ changes: lenientKinds(PROJECT_CHANGE_KINDS)
2381
+ });
2382
+ var environmentChangedMessageLenientSchema = z18.object({
2383
+ type: z18.literal("changed"),
2384
+ entity: z18.literal("environment"),
2385
+ id: z18.string().optional(),
2386
+ changes: lenientKinds(ENVIRONMENT_CHANGE_KINDS)
2387
+ });
2388
+ var hostChangedMessageLenientSchema = z18.object({
2389
+ type: z18.literal("changed"),
2390
+ entity: z18.literal("host"),
2391
+ id: z18.string().optional(),
2392
+ changes: lenientKinds(HOST_CHANGE_KINDS)
2393
+ });
2394
+ var systemChangedMessageLenientSchema = z18.object({
2395
+ type: z18.literal("changed"),
2396
+ entity: z18.literal("system"),
2397
+ changes: lenientKinds(SYSTEM_CHANGE_KINDS)
2398
+ });
2399
+ var changedMessageLenientSchema = z18.discriminatedUnion("entity", [
2400
+ threadChangedMessageLenientSchema,
2401
+ projectChangedMessageLenientSchema,
2402
+ environmentChangedMessageLenientSchema,
2403
+ hostChangedMessageLenientSchema,
2404
+ systemChangedMessageLenientSchema,
2405
+ tagsChangedMessageSchema.strip(),
2406
+ pluginChangedMessageSchema.strip()
2407
+ ]);
2408
+
2409
+ // src/internal/rpc-tags.ts
2410
+ import { z as z19 } from "zod";
2411
+ var rpcInvalidationTags = z19.array(z19.string().min(1)).min(1);
2412
+ function rpcResponseTags(declarations, input, output) {
2413
+ const tags = z19.array(z19.string().min(1)).parse(declarations.tags?.(input, output) ?? []);
2414
+ const keyTags = {};
2415
+ if (declarations.keyTags && typeof output === "object" && output !== null && !Array.isArray(output)) {
2416
+ for (const [key, value] of Object.entries(output)) {
2417
+ keyTags[key] = z19.array(z19.string().min(1)).parse(declarations.keyTags(key, value));
2418
+ }
2419
+ }
2420
+ const invalidated = z19.array(z19.string().min(1)).parse(declarations.invalidates?.(input, output) ?? []);
2421
+ return { tags, keyTags, invalidated };
2422
+ }
2423
+
2424
+ // src/internal/rpc-query-host.ts
2425
+ import { z as z20 } from "zod";
677
2426
  var rpcQueryKey = (pluginId, method, input) => [
678
2427
  "plugin-rpc",
679
2428
  pluginId,
@@ -681,47 +2430,79 @@ var rpcQueryKey = (pluginId, method, input) => [
681
2430
  input
682
2431
  ];
683
2432
  var keyedQueryKey = (pluginId, method) => rpcQueryKey(pluginId, method, { keyed: true });
2433
+ var keyedCollections = /* @__PURE__ */ new Map();
2434
+ function keyedCollection(pluginId, method) {
2435
+ const name = JSON.stringify([pluginId, method]);
2436
+ let collection = keyedCollections.get(name);
2437
+ if (!collection) {
2438
+ collection = new KeyedCollection(name);
2439
+ keyedCollections.set(name, collection);
2440
+ }
2441
+ return collection;
2442
+ }
2443
+ function parsedUpdate(update) {
2444
+ return (current) => jsonValueSchema.parse(update(current));
2445
+ }
684
2446
  function optimisticCache(pluginId, updates) {
685
- const add = (prediction) => {
686
- updates.push({
687
- ...prediction,
688
- update: (current) => jsonValueSchema.parse(prediction.update(current))
689
- });
690
- };
691
2447
  return {
692
2448
  update(method, input, update) {
693
- add(
2449
+ updates.push(
694
2450
  optimisticQueryUpdate(
695
2451
  rpcQueryKey(pluginId, method, jsonValueSchema.parse(input ?? null)),
696
- update,
2452
+ parsedUpdate(update),
697
2453
  ["result"]
698
2454
  )
699
2455
  );
700
2456
  },
701
2457
  updateKey(method, key, update) {
702
- add(
703
- optimisticQueryUpdate(keyedQueryKey(pluginId, method), update, [
704
- "result",
705
- key
706
- ])
2458
+ updates.push(
2459
+ optimisticKeyedUpdate(
2460
+ keyedCollection(pluginId, method),
2461
+ key,
2462
+ parsedUpdate(update)
2463
+ )
707
2464
  );
708
2465
  }
709
2466
  };
710
2467
  }
711
- async function callRpcEnvelope(host, pluginId, method, input) {
2468
+ async function callRpc(host, pluginId, contract, method, input) {
712
2469
  let raw;
713
2470
  try {
714
2471
  raw = await host.call(pluginId, method, input);
715
2472
  } catch (error) {
716
2473
  throw experimental_PluginRpcCallError.from(error);
717
2474
  }
718
- const parsed = envelopeSchema.safeParse(raw);
719
- if (!parsed.success)
2475
+ const result = jsonValueSchema.safeParse(raw);
2476
+ if (!result.success)
720
2477
  throw new experimental_PluginRpcCallError({
721
2478
  code: "invalid_response",
722
2479
  message: `Invalid RPC response for ${method}`
723
2480
  });
724
- return parsed.data;
2481
+ const methodContract = contract[method];
2482
+ if (methodContract === void 0)
2483
+ throw new experimental_PluginRpcCallError({
2484
+ code: "unknown_method",
2485
+ message: `rpc method "${method}" isn't in the contract`
2486
+ });
2487
+ const parsedInput = await methodContract.input["~standard"].validate(input);
2488
+ if (parsedInput.issues !== void 0)
2489
+ throw new experimental_PluginRpcCallError({
2490
+ code: "invalid_input",
2491
+ message: `rpc input validation failed for ${method}`
2492
+ });
2493
+ return {
2494
+ result: result.data,
2495
+ ...rpcResponseTags(methodContract, parsedInput.value, result.data)
2496
+ };
2497
+ }
2498
+ function resolvePluginId(host, pluginId) {
2499
+ const resolved = pluginId ?? host.pluginId;
2500
+ if (resolved === null) {
2501
+ throw new Error(
2502
+ "plugin RPC hooks outside a plugin slot component need an explicit pluginId"
2503
+ );
2504
+ }
2505
+ return resolved;
725
2506
  }
726
2507
  var tagsOf = (data) => [
727
2508
  ...data.tags,
@@ -737,10 +2518,17 @@ function createRpcQueryHooks(useHost) {
737
2518
  }
738
2519
  const experimental_useRpcQuery = (options) => {
739
2520
  const host = useHost();
740
- const pluginId = options.pluginId ?? host.pluginId;
2521
+ const pluginId = resolvePluginId(host, options.pluginId);
741
2522
  const input = jsonValueSchema.parse(options.input ?? null);
742
2523
  const queryKey = rpcQueryKey(pluginId, options.method, input);
743
2524
  useSubscription(host, pluginId, options.enabled ?? true);
2525
+ const watchIdentity = canonicalPluginReadInput(input);
2526
+ useEffect2(() => {
2527
+ if (options.enabled === false) return;
2528
+ return host.watch?.(pluginId, options.method, {
2529
+ input: jsonValueSchema.parse(JSON.parse(watchIdentity))
2530
+ });
2531
+ }, [host, pluginId, options.method, watchIdentity, options.enabled]);
744
2532
  const query = useTaggedQuery(
745
2533
  {
746
2534
  queryKey,
@@ -752,7 +2540,7 @@ function createRpcQueryHooks(useHost) {
752
2540
  queryFn: () => runTaggedRead(
753
2541
  host.queryClient,
754
2542
  queryKey,
755
- async () => callRpcEnvelope(host, pluginId, options.method, input)
2543
+ async () => callRpc(host, pluginId, options.contract, options.method, input)
756
2544
  )
757
2545
  },
758
2546
  host.queryClient
@@ -772,11 +2560,11 @@ function createRpcQueryHooks(useHost) {
772
2560
  };
773
2561
  function experimental_useRpcKeyedQuery(options) {
774
2562
  const host = useHost();
775
- const pluginId = options.pluginId ?? host.pluginId;
2563
+ const pluginId = resolvePluginId(host, options.pluginId);
776
2564
  const enabled = options.enabled ?? true;
777
2565
  const identity = JSON.stringify([...new Set(options.keys)].sort());
778
2566
  const keys = useMemo2(
779
- () => z2.array(z2.string()).parse(JSON.parse(identity)),
2567
+ () => z20.array(z20.string()).parse(JSON.parse(identity)),
780
2568
  [identity]
781
2569
  );
782
2570
  let cache = owners.get(host.queryClient);
@@ -791,16 +2579,18 @@ function createRpcQueryHooks(useHost) {
791
2579
  client: host.queryClient,
792
2580
  queryKey: keyedQueryKey(pluginId, options.method),
793
2581
  scope: pluginTagScope(pluginId),
2582
+ collection: keyedCollection(pluginId, options.method),
794
2583
  read: async (keys2) => {
795
- const response = await callRpcEnvelope(
2584
+ const response = await callRpc(
796
2585
  host,
797
2586
  pluginId,
2587
+ options.contract,
798
2588
  options.method,
799
2589
  { keys: [...keys2] }
800
2590
  );
801
2591
  return {
802
2592
  ...response,
803
- result: z2.record(z2.string(), jsonValueSchema).parse(response.result)
2593
+ result: z20.record(z20.string(), jsonValueSchema).parse(response.result)
804
2594
  };
805
2595
  }
806
2596
  });
@@ -837,6 +2627,15 @@ function createRpcQueryHooks(useHost) {
837
2627
  [keys, enabled, selectRows]
838
2628
  );
839
2629
  const query = useQuerySelection(subscribe, getSnapshot, select);
2630
+ useEffect2(() => {
2631
+ if (!enabled) return;
2632
+ const releases = keys.map(
2633
+ (key) => host.watch?.(pluginId, options.method, { key })
2634
+ );
2635
+ return () => {
2636
+ releases.forEach((release) => release?.());
2637
+ };
2638
+ }, [host, pluginId, options.method, keys, enabled]);
840
2639
  const refetch = useCallback2(async () => {
841
2640
  await current.observer.refetch();
842
2641
  }, [current]);
@@ -847,14 +2646,15 @@ function createRpcQueryHooks(useHost) {
847
2646
  }
848
2647
  function experimental_useRpcMutation(options) {
849
2648
  const host = useHost();
850
- const pluginId = options.pluginId ?? host.pluginId;
851
- const mutation = useTaggedMutation(
852
- host.queryClient,
853
- (tags) => invalidateTags(host.queryClient, pluginTagScope(pluginId), tags),
854
- async (input) => {
855
- const response = await callRpcEnvelope(
2649
+ const pluginId = resolvePluginId(host, options.pluginId);
2650
+ const mutation = useTaggedMutation({
2651
+ client: host.queryClient,
2652
+ invalidate: (tags) => invalidateTags(host.queryClient, pluginTagScope(pluginId), tags),
2653
+ call: async (input) => {
2654
+ const response = await callRpc(
856
2655
  host,
857
2656
  pluginId,
2657
+ options.contract,
858
2658
  options.method,
859
2659
  jsonValueSchema.parse(input)
860
2660
  );
@@ -863,7 +2663,7 @@ function createRpcQueryHooks(useHost) {
863
2663
  result: response.result
864
2664
  };
865
2665
  },
866
- (input) => {
2666
+ optimistic: (input) => {
867
2667
  const updates = [];
868
2668
  options.optimistic?.(
869
2669
  input,
@@ -871,7 +2671,7 @@ function createRpcQueryHooks(useHost) {
871
2671
  );
872
2672
  return updates;
873
2673
  }
874
- );
2674
+ });
875
2675
  const { mutate } = mutation;
876
2676
  return {
877
2677
  ...mutation,
@@ -895,18 +2695,12 @@ function createRpcQueryHooks(useHost) {
895
2695
  }
896
2696
  function experimental_useRpcRefresh() {
897
2697
  const host = useHost();
898
- const isRefreshing = useIsFetching(
899
- { queryKey: ["plugin-rpc", host.pluginId] },
900
- host.queryClient
901
- ) > 0;
2698
+ const pluginId = resolvePluginId(host, void 0);
2699
+ const isRefreshing = useIsFetching({ queryKey: ["plugin-rpc", pluginId] }, host.queryClient) > 0;
902
2700
  return {
903
2701
  isRefreshing,
904
2702
  refresh: () => {
905
- void invalidateTags(
906
- host.queryClient,
907
- pluginTagScope(host.pluginId),
908
- null
909
- );
2703
+ void invalidateTags(host.queryClient, pluginTagScope(pluginId), null);
910
2704
  }
911
2705
  };
912
2706
  }