@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.
@@ -94,24 +94,454 @@ import {
94
94
  useQueryClient,
95
95
  useMutation,
96
96
  useMutationState,
97
- replaceEqualDeep as replaceEqualDeep2
97
+ replaceEqualDeep as replaceEqualDeep3
98
98
  } from "@tanstack/react-query";
99
99
 
100
- // ../query-tags/src/optimistic.ts
100
+ // ../query-tags/src/clock.ts
101
+ var order = 0;
102
+ function tick() {
103
+ return ++order;
104
+ }
105
+
106
+ // ../query-tags/src/keyed-store.ts
101
107
  import {
102
108
  notifyManager,
103
109
  replaceEqualDeep
104
110
  } from "@tanstack/react-query";
111
+ var KeyedCollection = class {
112
+ constructor(name) {
113
+ this.name = name;
114
+ }
115
+ name;
116
+ };
117
+ var stores = /* @__PURE__ */ new WeakMap();
118
+ function isObject(value) {
119
+ return typeof value === "object" && value !== null;
120
+ }
121
+ function collectionOf(store, token) {
122
+ let collection = store.collections.get(token);
123
+ if (collection === void 0) {
124
+ collection = {
125
+ base: /* @__PURE__ */ new Map(),
126
+ visible: /* @__PURE__ */ new Map(),
127
+ layers: [],
128
+ acknowledgedAt: /* @__PURE__ */ new Map(),
129
+ views: /* @__PURE__ */ new Map()
130
+ };
131
+ store.collections.set(token, collection);
132
+ }
133
+ return collection;
134
+ }
135
+ function readEntity(collection, id) {
136
+ const cached = collection.visible.get(id);
137
+ if (cached !== void 0) return cached;
138
+ let entity = collection.base.get(id);
139
+ if (entity === void 0) return void 0;
140
+ for (const layer of collection.layers)
141
+ if (layer.ids.has(id)) entity = layer.apply(entity, id);
142
+ collection.visible.set(id, entity);
143
+ return entity;
144
+ }
145
+ function changed(store, collection, ids) {
146
+ const dirty = new Set(ids);
147
+ for (const id of dirty) collection.visible.delete(id);
148
+ if (store.batching > 0) {
149
+ const pending = store.dirtyIds.get(collection) ?? /* @__PURE__ */ new Set();
150
+ for (const id of dirty) pending.add(id);
151
+ store.dirtyIds.set(collection, pending);
152
+ return;
153
+ }
154
+ const views = /* @__PURE__ */ new Map();
155
+ for (const id of dirty)
156
+ for (const view of collection.views.get(id) ?? []) {
157
+ const viewIds = views.get(view) ?? /* @__PURE__ */ new Set();
158
+ viewIds.add(id);
159
+ views.set(view, viewIds);
160
+ }
161
+ notifyManager.batch(() => {
162
+ for (const [view, viewIds] of views) rematerialize(store, view, viewIds);
163
+ });
164
+ }
165
+ function writeBase(store, collection, id, update) {
166
+ const current = collection.base.get(id);
167
+ const next = update(current);
168
+ if (next === void 0 || next === current) return;
169
+ collection.base.set(id, next);
170
+ changed(store, collection, [id]);
171
+ }
172
+ function ingest(store, skeleton, id, item, readStart) {
173
+ const fresh = readStart > (skeleton.collection.acknowledgedAt.get(id) ?? -1);
174
+ writeBase(
175
+ store,
176
+ skeleton.collection,
177
+ id,
178
+ (current) => skeleton.view.read(item, current, fresh)
179
+ );
180
+ }
181
+ function materializeItem(store, view, item, entity) {
182
+ if (!isObject(item) || !isObject(entity)) return view.render(item, entity);
183
+ let byEntity = store.rows.get(item);
184
+ if (byEntity === void 0) {
185
+ byEntity = /* @__PURE__ */ new WeakMap();
186
+ store.rows.set(item, byEntity);
187
+ }
188
+ const cached = byEntity.get(entity);
189
+ if (cached !== void 0) return cached;
190
+ const row = view.render(item, entity);
191
+ byEntity.set(entity, row);
192
+ return row;
193
+ }
194
+ function rematerialize(store, query, dirty) {
195
+ const skeleton = store.skeletons.get(query);
196
+ if (skeleton === void 0) return;
197
+ const { view, collection } = skeleton;
198
+ const previous = store.materialized.get(query);
199
+ const incremental = dirty !== void 0 && previous !== void 0;
200
+ const slotKeys = /* @__PURE__ */ new Set();
201
+ if (incremental) {
202
+ for (const id of dirty)
203
+ for (const slot of skeleton.slotsById.get(id) ?? []) slotKeys.add(slot);
204
+ } else for (const slot of skeleton.slots.keys()) slotKeys.add(slot);
205
+ if (slotKeys.size === 0) return;
206
+ const items = /* @__PURE__ */ new Map();
207
+ const materialized = new Map(previous);
208
+ for (const slot of slotKeys) {
209
+ const prior = previous?.get(slot);
210
+ const visible = /* @__PURE__ */ new Map();
211
+ const rows = [];
212
+ for (const entry of skeleton.slots.get(slot) ?? []) {
213
+ if (entry.id === null) {
214
+ rows.push(entry.item);
215
+ continue;
216
+ }
217
+ const entity = readEntity(collection, entry.id);
218
+ if (entity !== void 0 && view.shows !== void 0 && !view.shows(entity, query.queryKey))
219
+ continue;
220
+ const previousRow = incremental ? prior?.get(entry.id) : void 0;
221
+ const row = previousRow !== void 0 && dirty?.has(entry.id) === false ? previousRow : replaceEqualDeep(
222
+ previousRow,
223
+ entity === void 0 ? entry.item : materializeItem(store, view, entry.item, entity)
224
+ );
225
+ visible.set(entry.id, row);
226
+ rows.push(row);
227
+ }
228
+ const unchanged = prior !== void 0 && prior.size === rows.length && [...prior.values()].every((row, index) => row === rows[index]);
229
+ if (incremental && unchanged) continue;
230
+ items.set(slot, rows);
231
+ materialized.set(slot, visible);
232
+ }
233
+ if (items.size === 0) return;
234
+ let next = view.rebuild(
235
+ incremental ? query.state.data : skeleton.data,
236
+ items
237
+ );
238
+ if (!incremental) {
239
+ next = replaceEqualDeep(query.state.data, next);
240
+ for (const slot of view.slots(next) ?? []) {
241
+ const visible = /* @__PURE__ */ new Map();
242
+ for (const item of slot.items) {
243
+ const id = view.keyOf(item);
244
+ if (id !== void 0) visible.set(id, item);
245
+ }
246
+ materialized.set(slot.key, visible);
247
+ }
248
+ }
249
+ store.materialized.set(query, materialized);
250
+ if (next !== query.state.data) query.setState({ data: next });
251
+ }
252
+ function skeletonIds(skeleton) {
253
+ const ids = /* @__PURE__ */ new Set();
254
+ for (const entries of skeleton?.slots.values() ?? [])
255
+ for (const { id } of entries) if (id !== null) ids.add(id);
256
+ return ids;
257
+ }
258
+ function setSkeleton(store, query, skeleton) {
259
+ const previous = store.skeletons.get(query);
260
+ const previousIds = skeletonIds(previous);
261
+ const nextIds = skeletonIds(skeleton);
262
+ if (skeleton === void 0) {
263
+ store.skeletons.delete(query);
264
+ store.materialized.delete(query);
265
+ } else store.skeletons.set(query, skeleton);
266
+ const collection = skeleton?.collection ?? previous?.collection;
267
+ if (collection === void 0) return;
268
+ for (const id of nextIds) {
269
+ let views = collection.views.get(id);
270
+ if (views === void 0) {
271
+ views = /* @__PURE__ */ new Set();
272
+ collection.views.set(id, views);
273
+ }
274
+ views.add(query);
275
+ }
276
+ for (const id of previousIds) {
277
+ if (nextIds.has(id)) continue;
278
+ const views = collection.views.get(id);
279
+ views?.delete(query);
280
+ if (views === void 0 || views.size === 0) {
281
+ collection.views.delete(id);
282
+ collection.base.delete(id);
283
+ collection.visible.delete(id);
284
+ }
285
+ }
286
+ }
287
+ function priorItem(materialized, slot, id) {
288
+ const same = materialized?.get(slot)?.get(id);
289
+ if (same !== void 0) return same;
290
+ for (const visible of materialized?.values() ?? []) {
291
+ const item = visible.get(id);
292
+ if (item !== void 0) return item;
293
+ }
294
+ return void 0;
295
+ }
296
+ function isHidden(entry, visible) {
297
+ return entry.id !== null && !visible.has(entry.id);
298
+ }
299
+ function keepHiddenEntries(previous, next, visible) {
300
+ if (!previous.some((entry) => isHidden(entry, visible))) return next;
301
+ const result = [...next];
302
+ let insertAt = result.length;
303
+ for (let index = previous.length - 1; index >= 0; index--) {
304
+ const entry = previous[index];
305
+ const existing = entry.id === null ? -1 : result.findIndex(({ id }) => id === entry.id);
306
+ if (existing >= 0) insertAt = existing;
307
+ else if (isHidden(entry, visible)) result.splice(insertAt, 0, entry);
308
+ }
309
+ return result;
310
+ }
311
+ function keptInsertions(store, query, slot, readStart) {
312
+ const insertions = (store.insertions.get(query) ?? []).filter(
313
+ (insertion) => insertion.at > readStart
314
+ );
315
+ store.insertions.set(query, insertions);
316
+ return insertions.filter((insertion) => insertion.slot === slot);
317
+ }
318
+ function batch(store, run) {
319
+ store.batching++;
320
+ try {
321
+ notifyManager.batch(run);
322
+ } finally {
323
+ store.batching--;
324
+ }
325
+ if (store.batching > 0) return;
326
+ const full = new Set(store.dirtyViews);
327
+ const partial = /* @__PURE__ */ new Map();
328
+ for (const [collection, ids] of store.dirtyIds)
329
+ for (const id of ids)
330
+ for (const view of collection.views.get(id) ?? []) {
331
+ if (full.has(view)) continue;
332
+ const viewIds = partial.get(view) ?? /* @__PURE__ */ new Set();
333
+ viewIds.add(id);
334
+ partial.set(view, viewIds);
335
+ }
336
+ store.dirtyIds.clear();
337
+ store.dirtyViews.clear();
338
+ notifyManager.batch(() => {
339
+ for (const view of full) rematerialize(store, view);
340
+ for (const [view, ids] of partial) rematerialize(store, view, ids);
341
+ });
342
+ }
343
+ function onViewWritten(store, query, view, manual) {
344
+ const data = query.state.data;
345
+ const slots = data === void 0 ? void 0 : view.slots(data);
346
+ if (slots === void 0) {
347
+ setSkeleton(store, query, void 0);
348
+ return;
349
+ }
350
+ const collection = collectionOf(store, view.collection);
351
+ const target = { view, collection };
352
+ const previous = store.skeletons.get(query);
353
+ const materialized = manual ? store.materialized.get(query) : void 0;
354
+ const readStart = manual ? -1 : store.fetchStartedAt.get(query) ?? 0;
355
+ const receipt = manual ? void 0 : store.receipts.get(query);
356
+ if (receipt !== void 0) store.receipts.delete(query);
357
+ batch(store, () => {
358
+ const nextSlots = /* @__PURE__ */ new Map();
359
+ const slotsById = /* @__PURE__ */ new Map();
360
+ for (const slot of slots) {
361
+ const entries = [];
362
+ for (const item of slot.items) {
363
+ const id = view.keyOf(item);
364
+ entries.push({ id: id ?? null, item });
365
+ if (id === void 0) continue;
366
+ const prior = priorItem(materialized, slot.key, id);
367
+ if (prior !== void 0) {
368
+ if (prior !== item)
369
+ writeBase(
370
+ store,
371
+ collection,
372
+ id,
373
+ (current) => current === void 0 ? current : view.write(item, prior, current)
374
+ );
375
+ continue;
376
+ }
377
+ const start = receipt === void 0 ? readStart : receipt.get(id);
378
+ if (start !== void 0) ingest(store, target, id, item, start);
379
+ else if (!collection.base.has(id))
380
+ ingest(store, target, id, item, readStart);
381
+ }
382
+ const previousEntries = previous?.slots.get(slot.key);
383
+ const visible = materialized?.get(slot.key);
384
+ const kept = previousEntries !== void 0 && visible !== void 0 ? keepHiddenEntries(previousEntries, entries, visible) : entries;
385
+ if (!manual) {
386
+ for (const insertion of keptInsertions(
387
+ store,
388
+ query,
389
+ slot.key,
390
+ readStart
391
+ ))
392
+ if (!kept.some(({ id }) => id === insertion.entry.id))
393
+ kept.push(insertion.entry);
394
+ }
395
+ nextSlots.set(slot.key, kept);
396
+ for (const { id } of kept) {
397
+ if (id === null) continue;
398
+ const slotKeys = slotsById.get(id) ?? /* @__PURE__ */ new Set();
399
+ slotKeys.add(slot.key);
400
+ slotsById.set(id, slotKeys);
401
+ }
402
+ }
403
+ setSkeleton(store, query, {
404
+ view,
405
+ collection,
406
+ data,
407
+ slots: nextSlots,
408
+ slotsById
409
+ });
410
+ store.dirtyViews.add(query);
411
+ });
412
+ }
413
+ function viewOf(store, query) {
414
+ const exact = store.exact.get(query.queryHash);
415
+ if (exact !== void 0) return exact;
416
+ for (const resolve of store.resolvers) {
417
+ const view = resolve(query.queryKey);
418
+ if (view !== void 0) return view;
419
+ }
420
+ return void 0;
421
+ }
422
+ function storeOf(client) {
423
+ const existing = stores.get(client);
424
+ if (existing !== void 0) return existing;
425
+ const store = {
426
+ client,
427
+ collections: /* @__PURE__ */ new Map(),
428
+ resolvers: [],
429
+ exact: /* @__PURE__ */ new Map(),
430
+ skeletons: /* @__PURE__ */ new Map(),
431
+ insertions: /* @__PURE__ */ new WeakMap(),
432
+ materialized: /* @__PURE__ */ new WeakMap(),
433
+ fetchStartedAt: /* @__PURE__ */ new WeakMap(),
434
+ receipts: /* @__PURE__ */ new WeakMap(),
435
+ rows: /* @__PURE__ */ new WeakMap(),
436
+ batching: 0,
437
+ dirtyIds: /* @__PURE__ */ new Map(),
438
+ dirtyViews: /* @__PURE__ */ new Set()
439
+ };
440
+ stores.set(client, store);
441
+ client.getQueryCache().subscribe((event) => {
442
+ const { query } = event;
443
+ if (event.type === "removed") {
444
+ if (store.skeletons.has(query)) setSkeleton(store, query, void 0);
445
+ return;
446
+ }
447
+ if (event.type !== "updated") return;
448
+ const { type } = event.action;
449
+ if (type !== "fetch" && type !== "success") return;
450
+ const view = viewOf(store, query);
451
+ if (view === void 0) return;
452
+ if (event.action.type === "fetch") {
453
+ store.fetchStartedAt.set(query, tick());
454
+ return;
455
+ }
456
+ if (event.action.type === "success")
457
+ onViewWritten(store, query, view, event.action.manual === true);
458
+ });
459
+ return store;
460
+ }
461
+ function adopt(store, matches) {
462
+ for (const query of store.client.getQueryCache().getAll()) {
463
+ const view = matches(query);
464
+ if (view !== void 0 && query.state.data !== void 0)
465
+ onViewWritten(store, query, view, true);
466
+ }
467
+ }
468
+ function registerKeyedView(client, queryKey, view) {
469
+ const store = storeOf(client);
470
+ const { queryHash } = client.defaultQueryOptions({ queryKey });
471
+ if (store.exact.has(queryHash)) return;
472
+ store.exact.set(queryHash, view);
473
+ adopt(store, (query) => query.queryHash === queryHash ? view : void 0);
474
+ }
475
+ function recordKeyedRead(client, queryKey, startedAt) {
476
+ const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
477
+ if (query !== void 0) storeOf(client).receipts.set(query, startedAt);
478
+ }
479
+ function bakeSettledLayers(collection) {
480
+ const baked = /* @__PURE__ */ new Set();
481
+ const pending = /* @__PURE__ */ new Set();
482
+ collection.layers = collection.layers.filter((layer) => {
483
+ const blocked = [...layer.ids].some((id) => pending.has(id));
484
+ if (!layer.settled || blocked) {
485
+ for (const id of layer.ids) pending.add(id);
486
+ return true;
487
+ }
488
+ for (const id of layer.ids) {
489
+ const current = collection.base.get(id);
490
+ if (current !== void 0)
491
+ collection.base.set(id, layer.apply(current, id));
492
+ baked.add(id);
493
+ }
494
+ return false;
495
+ });
496
+ return baked;
497
+ }
498
+ function predictKeyed(client, token, ids, apply) {
499
+ const store = storeOf(client);
500
+ const collection = collectionOf(store, token);
501
+ const layer = { ids, apply, settled: false };
502
+ collection.layers.push(layer);
503
+ changed(store, collection, ids);
504
+ const live = () => !layer.settled && collection.layers.includes(layer);
505
+ return {
506
+ accept() {
507
+ if (!live()) return;
508
+ const at = tick();
509
+ for (const id of ids) collection.acknowledgedAt.set(id, at);
510
+ layer.settled = true;
511
+ changed(store, collection, [...ids, ...bakeSettledLayers(collection)]);
512
+ },
513
+ remove() {
514
+ if (!live()) return;
515
+ collection.layers = collection.layers.filter((other) => other !== layer);
516
+ changed(store, collection, [...ids, ...bakeSettledLayers(collection)]);
517
+ }
518
+ };
519
+ }
520
+
521
+ // ../query-tags/src/optimistic.ts
522
+ import {
523
+ matchQuery,
524
+ notifyManager as notifyManager2,
525
+ replaceEqualDeep as replaceEqualDeep2
526
+ } from "@tanstack/react-query";
527
+ function optimisticKeyedUpdate(collection, key, update) {
528
+ return {
529
+ collection,
530
+ key,
531
+ update: (current, result) => update(current, result)
532
+ };
533
+ }
105
534
  function optimisticQueryUpdate(queryKey, update, path = []) {
106
535
  return {
107
536
  queryKey,
108
537
  path: [...path],
109
- update: (current) => update(current)
538
+ update: (current, result) => update(current, result)
110
539
  };
111
540
  }
112
541
  var predictions = /* @__PURE__ */ new WeakMap();
113
542
  var receipts = /* @__PURE__ */ new WeakMap();
114
- var order = 0;
543
+ var taggedMeta = /* @__PURE__ */ new WeakSet();
544
+ var syncedClients = /* @__PURE__ */ new WeakMap();
115
545
  function valueAt(data, path) {
116
546
  let value = data;
117
547
  for (const key of path) {
@@ -160,6 +590,22 @@ function confirmedValue(current, predicted, confirmed) {
160
590
  }
161
591
  return next;
162
592
  }
593
+ function rebase(base, visible, next) {
594
+ if (Object.is(visible, next)) return base;
595
+ 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))
596
+ return next;
597
+ const result = {};
598
+ for (const key of Object.keys(base))
599
+ if (!Object.hasOwn(visible, key) && !Object.hasOwn(next, key))
600
+ result[key] = Reflect.get(base, key);
601
+ for (const key of Object.keys(next))
602
+ result[key] = Object.hasOwn(visible, key) && Object.hasOwn(base, key) ? rebase(
603
+ Reflect.get(base, key),
604
+ Reflect.get(visible, key),
605
+ Reflect.get(next, key)
606
+ ) : Reflect.get(next, key);
607
+ return result;
608
+ }
163
609
  function projected(state) {
164
610
  return state.layers.reduce((data, layer) => {
165
611
  const current = valueAt(data, layer.path);
@@ -185,38 +631,98 @@ function subscribeOptimisticQuery(query, listener) {
185
631
  if (listeners.size === 0) predictionListeners.delete(query);
186
632
  };
187
633
  }
634
+ function isTaggedQuery(query) {
635
+ return query.meta !== void 0 && taggedMeta.has(query.meta);
636
+ }
637
+ function applyLayer(data, layer) {
638
+ const current = valueAt(data, layer.path);
639
+ return replaceAt(
640
+ data,
641
+ layer.path,
642
+ layer.update(current === void 0 ? layer.initial : current.value)
643
+ );
644
+ }
645
+ function confirmLayers(query, state, ready) {
646
+ const tagged = isTaggedQuery(query);
647
+ while (state.layers[0] !== void 0 && ready(state.layers[0])) {
648
+ const layer = state.layers.shift();
649
+ state.base = applyLayer(state.base, layer);
650
+ if (tagged && !layer.fresh) state.guards.push(layer);
651
+ }
652
+ }
653
+ function confirmBeforeWrite(query, state) {
654
+ confirmLayers(query, state, (layer) => layer.acceptedAt !== null);
655
+ }
656
+ function isIdle(state) {
657
+ return state.layers.length === 0 && state.guards.length === 0;
658
+ }
659
+ function untrack(query, state) {
660
+ predictions.delete(query);
661
+ const synced = syncedClients.get(state.client);
662
+ if (synced === void 0) return;
663
+ synced.queries.delete(query);
664
+ if (synced.queries.size === 0) {
665
+ synced.unsubscribe();
666
+ syncedClients.delete(state.client);
667
+ }
668
+ }
669
+ function track(query, state) {
670
+ predictions.set(query, state);
671
+ let synced = syncedClients.get(state.client);
672
+ if (synced === void 0) {
673
+ const queries = /* @__PURE__ */ new Set();
674
+ const unsubscribe = state.client.getQueryCache().subscribe((event) => {
675
+ if (event.type !== "updated" || event.action.type !== "success") return;
676
+ const current = predictions.get(event.query);
677
+ if (current === void 0 || isTaggedQuery(event.query)) return;
678
+ const data = event.query.state.data;
679
+ if (event.action.manual) {
680
+ confirmBeforeWrite(event.query, current);
681
+ current.base = rebase(current.base, current.visible, data);
682
+ } else {
683
+ current.base = data;
684
+ }
685
+ publish(event.query, current);
686
+ });
687
+ synced = { queries, unsubscribe };
688
+ syncedClients.set(state.client, synced);
689
+ }
690
+ synced.queries.add(query);
691
+ }
188
692
  function publish(query, state) {
189
- query.setState({
190
- data: replaceEqualDeep(query.state.data, projected(state))
191
- });
192
- if (state.layers.length === 0) predictions.delete(query);
693
+ if (!isTaggedQuery(query))
694
+ confirmLayers(query, state, (layer) => layer.settled);
695
+ const data = replaceEqualDeep2(query.state.data, projected(state));
696
+ state.visible = data;
697
+ query.setState({ data });
698
+ if (isIdle(state)) untrack(query, state);
193
699
  for (const listener of predictionListeners.get(query) ?? []) listener();
194
700
  }
195
- function taggedReadReceipt(query) {
196
- const paths = [];
197
- return {
198
- start: () => ++order,
199
- record(started, loaded) {
200
- paths.push(...loaded.map((path) => ({ path, started })));
201
- },
202
- commit(data) {
203
- receipts.set(query, { data, paths });
204
- }
205
- };
701
+ function markTaggedQueryMeta(meta) {
702
+ taggedMeta.add(meta);
703
+ }
704
+ function commitTaggedReadReceipt(query, data, started) {
705
+ receipts.set(query, { data, started });
706
+ }
707
+ function consumeReceipt(query, next) {
708
+ const receipt = receipts.get(query);
709
+ if (receipt === void 0 || !Object.is(receipt.data, next)) return;
710
+ receipts.delete(query);
711
+ return receipt;
712
+ }
713
+ function refreshedBy(receipt, layer) {
714
+ return layer.acceptedAt !== null && receipt.started > layer.acceptedAt;
206
715
  }
207
716
  function taggedStructuralSharing(client, queryKey, previous, next) {
208
717
  const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
209
- const state = query === void 0 ? void 0 : predictions.get(query);
210
- if (query !== void 0) {
211
- const receipt = receipts.get(query);
212
- if (receipt !== void 0 && Object.is(receipt.data, next)) {
213
- receipts.delete(query);
214
- if (state !== void 0) {
718
+ if (query !== void 0 && Object.is(previous, query.state.data)) {
719
+ const receipt = consumeReceipt(query, next);
720
+ const state = predictions.get(query);
721
+ if (state !== void 0) {
722
+ if (receipt !== void 0) {
215
723
  const refreshed = /* @__PURE__ */ new Set();
216
724
  for (const layer of state.layers) {
217
- if (layer.acceptedAt !== null && receipt.paths.some(
218
- ({ path, started }) => started > layer.acceptedAt && prefix(path, layer.path)
219
- )) {
725
+ if (refreshedBy(receipt, layer)) {
220
726
  layer.fresh = true;
221
727
  refreshed.add(layer);
222
728
  }
@@ -225,60 +731,129 @@ function taggedStructuralSharing(client, queryKey, previous, next) {
225
731
  (layer) => !layer.settled || !refreshed.has(layer) || olderPending(state, layer)
226
732
  );
227
733
  }
228
- }
229
- if (state !== void 0) {
230
- state.base = next;
734
+ if (receipt !== void 0) {
735
+ state.guards = state.guards.filter(
736
+ (guard) => !refreshedBy(receipt, guard)
737
+ );
738
+ state.base = state.guards.reduce(applyLayer, next);
739
+ } else {
740
+ confirmBeforeWrite(query, state);
741
+ state.base = rebase(state.base, previous, next);
742
+ }
231
743
  next = projected(state);
232
- if (state.layers.length === 0) predictions.delete(query);
744
+ state.visible = next;
745
+ if (isIdle(state)) untrack(query, state);
233
746
  }
234
747
  }
235
748
  const sharing = client.defaultQueryOptions({ queryKey }).structuralSharing;
236
- return sharing === false ? next : typeof sharing === "function" ? sharing(previous, next) : replaceEqualDeep(previous, next);
749
+ return sharing === false ? next : typeof sharing === "function" ? sharing(previous, next) : replaceEqualDeep2(previous, next);
237
750
  }
238
751
  function getTaggedReadData(client, queryKey) {
239
752
  const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
240
753
  const state = query === void 0 ? void 0 : predictions.get(query);
241
754
  return state === void 0 ? query?.state.data : state.base;
242
755
  }
243
- function beginOptimisticMutation(client, updates) {
756
+ function isKeyedUpdate(update) {
757
+ return "collection" in update;
758
+ }
759
+ function beginKeyedPredictions(client, updates, result) {
760
+ const byCollection = /* @__PURE__ */ new Map();
761
+ for (const update of updates) {
762
+ const byKey = byCollection.get(update.collection) ?? /* @__PURE__ */ new Map();
763
+ byKey.set(update.key, [...byKey.get(update.key) ?? [], update]);
764
+ byCollection.set(update.collection, byKey);
765
+ }
766
+ return [...byCollection].map(
767
+ ([collection, byKey]) => predictKeyed(
768
+ client,
769
+ collection,
770
+ new Set(byKey.keys()),
771
+ (entity, key) => (byKey.get(key) ?? []).reduce(
772
+ (current, update) => update.update(current, result()),
773
+ entity
774
+ )
775
+ )
776
+ );
777
+ }
778
+ function beginOptimisticMutation(client, allUpdates) {
244
779
  const owner = {};
245
- const mutationOrder = ++order;
246
- let accepted = false;
780
+ const mutationOrder = tick();
781
+ let accepted;
782
+ let done = false;
783
+ const updates = allUpdates.filter(
784
+ (update) => !isKeyedUpdate(update)
785
+ );
786
+ const keyed = beginKeyedPredictions(
787
+ client,
788
+ allUpdates.filter(isKeyedUpdate),
789
+ () => accepted?.result.value === void 0 ? void 0 : accepted.result
790
+ );
247
791
  const affected = /* @__PURE__ */ new Map();
248
- const rollback = () => notifyManager.batch(() => {
249
- if (accepted) return;
792
+ const attached = new Map(
793
+ updates.map((update) => [update, /* @__PURE__ */ new Set()])
794
+ );
795
+ const attach = (query, update) => {
796
+ const queries = attached.get(update);
797
+ if (queries.has(query) || query.state.data === void 0) return;
798
+ const state = predictions.get(query) ?? {
799
+ client,
800
+ base: query.state.data,
801
+ visible: query.state.data,
802
+ layers: [],
803
+ guards: []
804
+ };
805
+ const current = valueAt(projected(state), update.path);
806
+ if (current === void 0) return;
807
+ queries.add(query);
808
+ const layer = {
809
+ owner,
810
+ order: mutationOrder,
811
+ path: update.path,
812
+ initial: current.value,
813
+ update: (value) => update.update(value, accepted?.result),
814
+ acceptedAt: accepted?.at ?? null,
815
+ fresh: false,
816
+ settled: false
817
+ };
818
+ const index = state.layers.findIndex((other) => other.order > layer.order);
819
+ if (index < 0) state.layers.push(layer);
820
+ else state.layers.splice(index, 0, layer);
821
+ track(query, state);
822
+ affected.set(query, state);
823
+ publish(query, state);
824
+ };
825
+ const unsubscribe = updates.length === 0 ? () => {
826
+ } : client.getQueryCache().subscribe((event) => {
827
+ if (event.type !== "updated" || event.action.type !== "success")
828
+ return;
829
+ for (const update of updates)
830
+ if (matchQuery(
831
+ { queryKey: update.queryKey, exact: true },
832
+ event.query
833
+ ))
834
+ attach(event.query, update);
835
+ });
836
+ const finish = () => {
837
+ done = true;
838
+ unsubscribe();
839
+ };
840
+ const rollback = () => notifyManager2.batch(() => {
841
+ if (accepted !== void 0 || done) return;
842
+ finish();
843
+ for (const prediction of keyed) prediction.remove();
250
844
  for (const [query, state] of affected) {
251
845
  state.layers = state.layers.filter((layer) => layer.owner !== owner);
252
846
  publish(query, state);
253
847
  }
254
848
  });
255
849
  try {
256
- notifyManager.batch(() => {
257
- for (const update of updates) {
258
- const query = client.getQueryCache().get(
259
- client.defaultQueryOptions({ queryKey: update.queryKey }).queryHash
260
- );
261
- if (query === void 0 || query.state.data === void 0) continue;
262
- const state = predictions.get(query) ?? {
263
- base: query.state.data,
264
- layers: []
265
- };
266
- const current = valueAt(projected(state), update.path);
267
- if (current === void 0) continue;
268
- state.layers.push({
269
- owner,
270
- order: mutationOrder,
271
- path: update.path,
272
- initial: current.value,
273
- update: update.update,
274
- acceptedAt: null,
275
- fresh: false,
276
- settled: false
277
- });
278
- predictions.set(query, state);
279
- affected.set(query, state);
280
- publish(query, state);
281
- }
850
+ notifyManager2.batch(() => {
851
+ for (const update of updates)
852
+ for (const query of client.getQueryCache().findAll({
853
+ queryKey: update.queryKey,
854
+ exact: true
855
+ }))
856
+ attach(query, update);
282
857
  });
283
858
  } catch (error) {
284
859
  rollback();
@@ -286,19 +861,27 @@ function beginOptimisticMutation(client, updates) {
286
861
  }
287
862
  return {
288
863
  rollback,
289
- accept() {
290
- accepted = true;
291
- const acceptedAt = ++order;
292
- for (const state of affected.values())
293
- for (const layer of state.layers)
294
- if (layer.owner === owner) layer.acceptedAt = acceptedAt;
864
+ accept(result) {
865
+ accepted = { at: tick(), result: { value: result } };
866
+ notifyManager2.batch(() => {
867
+ for (const prediction of keyed) prediction.accept();
868
+ for (const [query, state] of affected) {
869
+ for (const layer of state.layers)
870
+ if (layer.owner === owner) layer.acceptedAt = accepted.at;
871
+ publish(query, state);
872
+ }
873
+ });
295
874
  },
296
875
  settle() {
297
- notifyManager.batch(() => {
876
+ if (done) return;
877
+ finish();
878
+ notifyManager2.batch(() => {
298
879
  for (const [query, state] of affected) {
880
+ const tagged = isTaggedQuery(query);
299
881
  state.layers = state.layers.filter((layer) => {
300
882
  if (layer.owner !== owner) return true;
301
883
  layer.settled = true;
884
+ if (!tagged) return true;
302
885
  if (!layer.fresh) return true;
303
886
  if (!olderPending(state, layer)) return false;
304
887
  const current = valueAt(state.base, layer.path);
@@ -335,6 +918,7 @@ var registrations = /* @__PURE__ */ new WeakMap();
335
918
  var reads = /* @__PURE__ */ new WeakMap();
336
919
  function taggedQueryOptions(client, queryKey, registration) {
337
920
  const meta = {};
921
+ markTaggedQueryMeta(meta);
338
922
  registrations.set(meta, {
339
923
  scope: registration.scope,
340
924
  tagsOf: (data) => registration.tagsOf(data),
@@ -348,22 +932,20 @@ function taggedQueryOptions(client, queryKey, registration) {
348
932
  function registrationOf(query) {
349
933
  return query.meta === void 0 ? void 0 : registrations.get(query.meta);
350
934
  }
351
- async function runTaggedRead(client, queryKey, read, paths = () => [[]]) {
935
+ async function runTaggedRead(client, queryKey, read) {
352
936
  const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
353
937
  if (query === void 0) return read();
354
938
  const registration = registrationOf(query);
355
- const receipt = taggedReadReceipt(query);
356
939
  for (; ; ) {
357
940
  const pending = { tags: /* @__PURE__ */ new Set(), restart: false };
358
941
  reads.set(query, pending);
359
- const started = receipt.start();
942
+ const started = tick();
360
943
  try {
361
944
  const result = await read();
362
- receipt.record(started, paths());
363
945
  const overlap = registration?.tagsOf(result).some((tag) => pending.tags.has(tag));
364
946
  if (overlap) registration?.onInvalidate?.(result, [...pending.tags]);
365
947
  if (pending.restart || overlap) continue;
366
- receipt.commit(result);
948
+ commitTaggedReadReceipt(query, result, started);
367
949
  return result;
368
950
  } catch (error) {
369
951
  if (pending.restart) continue;
@@ -411,10 +993,11 @@ async function invalidateTags(client, scope, tags) {
411
993
  }
412
994
  async function executeTaggedMutation(invalidate, call, prediction) {
413
995
  const { result, invalidated } = await call();
414
- prediction?.accept();
996
+ prediction?.accept(result);
415
997
  const refresh = async () => {
416
998
  try {
417
- if (invalidated.length > 0) await invalidate(invalidated);
999
+ if (invalidate !== void 0 && invalidated.length > 0)
1000
+ await invalidate(invalidated);
418
1001
  } finally {
419
1002
  prediction?.settle();
420
1003
  }
@@ -428,7 +1011,13 @@ function restartTaggedRead(query) {
428
1011
  const pending = reads.get(query);
429
1012
  if (pending) pending.restart = true;
430
1013
  }
431
- function useTaggedMutation(client, invalidate, call, optimistic) {
1014
+ function useTaggedMutation({
1015
+ client,
1016
+ invalidate,
1017
+ call,
1018
+ optimistic,
1019
+ meta
1020
+ }) {
432
1021
  const [owner] = useState(() => ({}));
433
1022
  const predict = useRef(optimistic);
434
1023
  useEffect(() => {
@@ -436,7 +1025,7 @@ function useTaggedMutation(client, invalidate, call, optimistic) {
436
1025
  }, [optimistic]);
437
1026
  const mutation = useMutation(
438
1027
  {
439
- meta: { taggedMutationOwner: owner },
1028
+ meta: { ...meta, taggedMutationOwner: owner },
440
1029
  mutationFn: ({ input, prediction }) => executeTaggedMutation(invalidate, () => call(input), prediction)
441
1030
  },
442
1031
  client
@@ -473,8 +1062,33 @@ function useTaggedMutation(client, invalidate, call, optimistic) {
473
1062
  reset: mutation.reset
474
1063
  };
475
1064
  }
1065
+ function hasRows(data) {
1066
+ return typeof data === "object" && data !== null && "result" in data && typeof data.result === "object" && data.result !== null;
1067
+ }
1068
+ var rowKey = (item) => Array.isArray(item) && typeof item[0] === "string" ? item[0] : void 0;
1069
+ var rowValue = (item) => Array.isArray(item) ? item[1] : void 0;
1070
+ function keyedRowsView(collection) {
1071
+ return {
1072
+ collection,
1073
+ slots: (data) => hasRows(data) ? [{ key: "result", items: Object.entries(data.result) }] : void 0,
1074
+ rebuild: (data, items) => hasRows(data) ? {
1075
+ ...data,
1076
+ result: Object.fromEntries(
1077
+ (items.get("result") ?? []).flatMap((item) => {
1078
+ const key = rowKey(item);
1079
+ return key === void 0 ? [] : [[key, rowValue(item)]];
1080
+ })
1081
+ )
1082
+ } : data,
1083
+ keyOf: rowKey,
1084
+ read: (item, current, fresh) => current === void 0 || fresh ? rowValue(item) : current,
1085
+ write: rowValue,
1086
+ render: (item, entity) => Object.is(rowValue(item), entity) ? item : [rowKey(item), entity]
1087
+ };
1088
+ }
476
1089
  function createTaggedKeyedQueryOwner(options) {
477
- const { client, queryKey, scope, read } = options;
1090
+ const { client, queryKey, scope, collection, read } = options;
1091
+ registerKeyedView(client, queryKey, keyedRowsView(collection));
478
1092
  const keys = /* @__PURE__ */ new Map();
479
1093
  let readingKeys = /* @__PURE__ */ new Set();
480
1094
  let missingOnly = false;
@@ -502,76 +1116,73 @@ function createTaggedKeyedQueryOwner(options) {
502
1116
  }),
503
1117
  queryFn: () => {
504
1118
  let previous = getTaggedReadData(client, queryKey);
505
- let loaded = [];
1119
+ const startedAt = /* @__PURE__ */ new Map();
506
1120
  let refresh = !missingOnly && dirtyKeys.size === 0;
507
1121
  missingOnly = false;
508
1122
  const refreshedKeys = /* @__PURE__ */ new Set();
509
1123
  let refreshedAll = false;
510
- return runTaggedRead(
511
- client,
512
- queryKey,
513
- async () => {
514
- const subscribed = await collectSubscribedKeys();
515
- const all = refreshAll || refresh;
516
- refresh = false;
517
- const dirty = new Set(dirtyKeys);
518
- for (const key of dirty) refreshedKeys.add(key);
519
- refreshedAll ||= all;
520
- dirtyKeys.clear();
521
- refreshAll = false;
522
- const requested = subscribed.filter(
523
- (key) => all || dirty.has(key) || !Object.hasOwn(previous?.result ?? {}, key)
1124
+ return runTaggedRead(client, queryKey, async () => {
1125
+ const subscribed = await collectSubscribedKeys();
1126
+ const all = refreshAll || refresh;
1127
+ refresh = false;
1128
+ const dirty = new Set(dirtyKeys);
1129
+ for (const key of dirty) refreshedKeys.add(key);
1130
+ refreshedAll ||= all;
1131
+ dirtyKeys.clear();
1132
+ refreshAll = false;
1133
+ const requested = subscribed.filter(
1134
+ (key) => all || dirty.has(key) || !Object.hasOwn(previous?.result ?? {}, key)
1135
+ );
1136
+ readingKeys = new Set(requested);
1137
+ const started = tick();
1138
+ try {
1139
+ const results = await Promise.all(
1140
+ Array.from(
1141
+ { length: Math.ceil(requested.length / 200) },
1142
+ async (_, i) => {
1143
+ const batch2 = requested.slice(i * 200, (i + 1) * 200);
1144
+ const response = await read(batch2);
1145
+ for (const key of batch2)
1146
+ if (!Object.hasOwn(response.result, key))
1147
+ throw new Error(`Keyed read omitted key ${key}`);
1148
+ return response;
1149
+ }
1150
+ )
524
1151
  );
525
- readingKeys = new Set(requested);
526
- try {
527
- const results = await Promise.all(
528
- Array.from(
529
- { length: Math.ceil(requested.length / 200) },
530
- async (_, i) => {
531
- const batch = requested.slice(i * 200, (i + 1) * 200);
532
- const response = await read(batch);
533
- for (const key of batch)
534
- if (!Object.hasOwn(response.result, key))
535
- throw new Error(`Keyed read omitted key ${key}`);
536
- return response;
537
- }
538
- )
539
- );
540
- const retained = (key) => !all && !dirty.has(key) && !readingKeys.has(key);
541
- loaded = requested;
542
- previous = {
543
- result: Object.fromEntries([
544
- ...Object.entries(previous?.result ?? {}).filter(
545
- ([key]) => retained(key)
546
- ),
547
- ...results.flatMap(
548
- (response) => Object.entries(response.result)
549
- )
550
- ]),
551
- tags: [
552
- .../* @__PURE__ */ new Set([
553
- ...all ? [] : previous?.tags ?? [],
554
- ...results.flatMap((r) => r.tags)
555
- ])
556
- ],
557
- keyTags: Object.fromEntries([
558
- ...Object.entries(previous?.keyTags ?? {}).filter(
559
- ([key]) => retained(key)
560
- ),
561
- ...results.flatMap(
562
- (response) => Object.entries(response.keyTags)
563
- )
1152
+ const retained = (key) => !all && !dirty.has(key) && !readingKeys.has(key);
1153
+ for (const key of requested) startedAt.set(key, started);
1154
+ previous = {
1155
+ result: Object.fromEntries([
1156
+ ...Object.entries(previous?.result ?? {}).filter(
1157
+ ([key]) => retained(key)
1158
+ ),
1159
+ ...results.flatMap((response) => Object.entries(response.result))
1160
+ ]),
1161
+ tags: [
1162
+ .../* @__PURE__ */ new Set([
1163
+ ...all ? [] : previous?.tags ?? [],
1164
+ ...results.flatMap((r) => r.tags)
564
1165
  ])
565
- };
566
- return previous;
567
- } catch (error) {
568
- for (const key of refreshedKeys) dirtyKeys.add(key);
569
- refreshAll ||= refreshedAll;
570
- throw error;
571
- }
572
- },
573
- () => loaded.map((key) => ["result", key])
574
- );
1166
+ ],
1167
+ keyTags: Object.fromEntries([
1168
+ ...Object.entries(previous?.keyTags ?? {}).filter(
1169
+ ([key]) => retained(key)
1170
+ ),
1171
+ ...results.flatMap(
1172
+ (response) => Object.entries(response.keyTags)
1173
+ )
1174
+ ])
1175
+ };
1176
+ return previous;
1177
+ } catch (error) {
1178
+ for (const key of refreshedKeys) dirtyKeys.add(key);
1179
+ refreshAll ||= refreshedAll;
1180
+ throw error;
1181
+ }
1182
+ }).then((data) => {
1183
+ recordKeyedRead(client, queryKey, startedAt);
1184
+ return data;
1185
+ });
575
1186
  }
576
1187
  });
577
1188
  const listeners = /* @__PURE__ */ new Set();
@@ -630,7 +1241,7 @@ function useQuerySelection(subscribe, getSnapshot, select) {
630
1241
  if (cached && Object.is(cached.snapshot, snapshot)) return cached.value;
631
1242
  cached = {
632
1243
  snapshot,
633
- value: replaceEqualDeep2(
1244
+ value: replaceEqualDeep3(
634
1245
  cached?.value ?? committed.current?.value,
635
1246
  select(snapshot)
636
1247
  )
@@ -652,6 +1263,9 @@ import { QueryClient } from "@tanstack/react-query";
652
1263
  import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2 } from "react";
653
1264
  import { useIsFetching } from "@tanstack/react-query";
654
1265
 
1266
+ // ../domain/src/shared-types.ts
1267
+ import { z as z2 } from "zod";
1268
+
655
1269
  // ../domain/src/json-value.ts
656
1270
  import { z } from "zod";
657
1271
  var jsonValueSchema = z.lazy(
@@ -669,14 +1283,1149 @@ var jsonObjectSchema = z.record(
669
1283
  jsonValueSchema
670
1284
  );
671
1285
 
672
- // src/internal/rpc-query-host.ts
673
- import { z as z2 } from "zod";
674
- var envelopeSchema = z2.object({
675
- result: jsonValueSchema,
676
- tags: z2.array(z2.string()).default([]),
677
- keyTags: z2.record(z2.string(), z2.array(z2.string())).default({}),
678
- invalidated: z2.array(z2.string()).default([])
1286
+ // ../domain/src/shared-types.ts
1287
+ var reasoningLevelSchema = z2.string().min(1);
1288
+ var serviceTierSchema = z2.string().min(1);
1289
+ var instructionModeValues = ["append", "replace"];
1290
+ var instructionModeSchema = z2.enum(instructionModeValues);
1291
+ var permissionModeValues = ["accept-edits", "auto", "full"];
1292
+ var permissionModeSchema = z2.enum(permissionModeValues);
1293
+ var permissionModeInputSchema = z2.union([permissionModeSchema, z2.literal("workspace-write")]).transform(
1294
+ (permissionMode) => permissionMode === "workspace-write" ? "accept-edits" : permissionMode
1295
+ );
1296
+ var legacyRecordedPermissionModeValues = [
1297
+ "workspace-write",
1298
+ "readonly"
1299
+ ];
1300
+ var recordedPermissionModeSchema = z2.enum([
1301
+ ...permissionModeValues,
1302
+ ...legacyRecordedPermissionModeValues
1303
+ ]);
1304
+ var permissionEscalationValues = ["ask", "deny"];
1305
+ var permissionEscalationSchema = z2.enum(permissionEscalationValues);
1306
+ var promptInputVisibilityValues = ["agent-only"];
1307
+ var promptInputVisibilitySchema = z2.enum(promptInputVisibilityValues);
1308
+ var promptInputVisibilityFields = {
1309
+ visibility: promptInputVisibilitySchema.optional()
1310
+ };
1311
+ var promptMentionPathSourceValues = ["workspace", "thread-storage"];
1312
+ var promptMentionPathSourceSchema = z2.enum(promptMentionPathSourceValues);
1313
+ var promptMentionPathEntryKindValues = ["file", "directory"];
1314
+ var promptMentionPathEntryKindSchema = z2.enum(
1315
+ promptMentionPathEntryKindValues
1316
+ );
1317
+ var promptMentionCommandTriggerValues = ["/", "$"];
1318
+ var promptMentionCommandTriggerSchema = z2.enum(
1319
+ promptMentionCommandTriggerValues
1320
+ );
1321
+ var promptMentionCommandSourceValues = ["skill", "command"];
1322
+ var promptMentionCommandSourceSchema = z2.enum(
1323
+ promptMentionCommandSourceValues
1324
+ );
1325
+ var promptMentionCommandOriginValues = [
1326
+ "builtin",
1327
+ "project",
1328
+ "user"
1329
+ ];
1330
+ var promptMentionCommandOriginSchema = z2.enum(
1331
+ promptMentionCommandOriginValues
1332
+ );
1333
+ var canonicalPromptMentionResourceSchema = z2.discriminatedUnion("kind", [
1334
+ z2.object({
1335
+ kind: z2.literal("thread"),
1336
+ threadId: z2.string(),
1337
+ projectId: z2.string().optional(),
1338
+ label: z2.string()
1339
+ }),
1340
+ z2.object({
1341
+ kind: z2.literal("project"),
1342
+ projectId: z2.string(),
1343
+ label: z2.string()
1344
+ }),
1345
+ z2.object({
1346
+ kind: z2.literal("section"),
1347
+ sectionId: z2.string(),
1348
+ label: z2.string()
1349
+ }),
1350
+ z2.object({
1351
+ kind: z2.literal("path"),
1352
+ source: promptMentionPathSourceSchema,
1353
+ entryKind: promptMentionPathEntryKindSchema,
1354
+ path: z2.string(),
1355
+ label: z2.string()
1356
+ }),
1357
+ z2.object({
1358
+ kind: z2.literal("command"),
1359
+ trigger: promptMentionCommandTriggerSchema,
1360
+ name: z2.string(),
1361
+ source: promptMentionCommandSourceSchema,
1362
+ origin: promptMentionCommandOriginSchema,
1363
+ label: z2.string(),
1364
+ argumentHint: z2.string().nullable()
1365
+ }),
1366
+ z2.object({
1367
+ kind: z2.literal("plugin"),
1368
+ pluginId: z2.string(),
1369
+ icon: z2.string().nullable().optional(),
1370
+ itemId: z2.string(),
1371
+ label: z2.string()
1372
+ }),
1373
+ z2.object({
1374
+ kind: z2.literal("attachment"),
1375
+ path: z2.string(),
1376
+ label: z2.string()
1377
+ })
1378
+ ]);
1379
+ function normalizeLegacyPromptMentionResource(value) {
1380
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1381
+ return value;
1382
+ }
1383
+ const record = value;
1384
+ if (record.kind !== "folder" || typeof record.folderId !== "string") {
1385
+ return value;
1386
+ }
1387
+ const { folderId, ...rest } = record;
1388
+ return { ...rest, kind: "section", sectionId: folderId };
1389
+ }
1390
+ var promptMentionResourceSchema = z2.preprocess(
1391
+ normalizeLegacyPromptMentionResource,
1392
+ canonicalPromptMentionResourceSchema
1393
+ );
1394
+ var promptTextMentionSchema = z2.object({
1395
+ start: z2.number().int().nonnegative(),
1396
+ end: z2.number().int().nonnegative(),
1397
+ resource: promptMentionResourceSchema
1398
+ });
1399
+ var promptInputSchema = z2.discriminatedUnion("type", [
1400
+ z2.object({
1401
+ type: z2.literal("text"),
1402
+ text: z2.string(),
1403
+ mentions: z2.array(promptTextMentionSchema).default([]),
1404
+ ...promptInputVisibilityFields
1405
+ }),
1406
+ z2.object({
1407
+ type: z2.literal("image"),
1408
+ url: z2.string().url(),
1409
+ ...promptInputVisibilityFields
1410
+ }),
1411
+ z2.object({
1412
+ type: z2.literal("localImage"),
1413
+ path: z2.string(),
1414
+ sourceProjectId: z2.string().min(1).optional(),
1415
+ hostId: z2.string().min(1).optional(),
1416
+ ...promptInputVisibilityFields
1417
+ }),
1418
+ z2.object({
1419
+ type: z2.literal("localFile"),
1420
+ path: z2.string(),
1421
+ sourceProjectId: z2.string().min(1).optional(),
1422
+ hostId: z2.string().min(1).optional(),
1423
+ name: z2.string().optional(),
1424
+ sizeBytes: z2.number().int().nonnegative().optional(),
1425
+ mimeType: z2.string().optional(),
1426
+ ...promptInputVisibilityFields
1427
+ })
1428
+ ]);
1429
+ var threadExecutionSourceSchema = z2.enum([
1430
+ "client/thread/start",
1431
+ "client/turn/requested",
1432
+ "client/turn/start"
1433
+ ]);
1434
+ var callerExecutionInputSourceValues = [
1435
+ "explicit",
1436
+ "client-preference"
1437
+ ];
1438
+ var callerExecutionInputSourceSchema = z2.enum(
1439
+ callerExecutionInputSourceValues
1440
+ );
1441
+ var threadExecutionOptionsSchema = z2.object({
1442
+ model: z2.string().optional(),
1443
+ serviceTier: serviceTierSchema.optional(),
1444
+ reasoningLevel: reasoningLevelSchema.optional(),
1445
+ permissionMode: permissionModeSchema.optional(),
1446
+ source: threadExecutionSourceSchema.optional(),
1447
+ seq: z2.number().int().optional()
1448
+ });
1449
+ var resolvedThreadExecutionOptionsSchema = threadExecutionOptionsSchema.extend({
1450
+ model: z2.string().min(1),
1451
+ serviceTier: serviceTierSchema,
1452
+ reasoningLevel: reasoningLevelSchema,
1453
+ permissionMode: permissionModeSchema,
1454
+ source: threadExecutionSourceSchema
679
1455
  });
1456
+ var recordedThreadExecutionOptionsSchema = resolvedThreadExecutionOptionsSchema.extend({
1457
+ permissionMode: recordedPermissionModeSchema
1458
+ });
1459
+ var runtimePermissionScopeValues = ["workspace", "full"];
1460
+ var runtimePermissionScopeSchema = z2.enum(runtimePermissionScopeValues);
1461
+ var runtimePermissionPolicySchema = z2.discriminatedUnion(
1462
+ "permissionMode",
1463
+ [
1464
+ z2.object({
1465
+ permissionMode: z2.literal("accept-edits"),
1466
+ permissionScope: z2.literal("workspace"),
1467
+ approvalReviewer: z2.literal("user"),
1468
+ permissionEscalation: permissionEscalationSchema
1469
+ }),
1470
+ z2.object({
1471
+ permissionMode: z2.literal("auto"),
1472
+ permissionScope: z2.literal("workspace"),
1473
+ approvalReviewer: z2.literal("automatic"),
1474
+ permissionEscalation: permissionEscalationSchema
1475
+ }),
1476
+ z2.object({
1477
+ permissionMode: z2.literal("full"),
1478
+ permissionScope: z2.literal("full"),
1479
+ approvalReviewer: z2.null(),
1480
+ permissionEscalation: z2.null()
1481
+ })
1482
+ ]
1483
+ );
1484
+ var promptModeSchema = z2.literal("plan");
1485
+ var sessionOptionValueSchema = z2.union([z2.string(), z2.boolean()]);
1486
+ var sessionOptionSelectionsSchema = z2.record(
1487
+ z2.string().min(1),
1488
+ sessionOptionValueSchema
1489
+ );
1490
+ var runtimeThreadExecutionBaseOptionsSchema = z2.object({
1491
+ model: z2.string().min(1),
1492
+ serviceTier: serviceTierSchema,
1493
+ reasoningLevel: reasoningLevelSchema,
1494
+ promptMode: promptModeSchema.optional(),
1495
+ sessionOptions: sessionOptionSelectionsSchema.optional(),
1496
+ providerOptions: jsonObjectSchema
1497
+ });
1498
+ var runtimeThreadExecutionOptionsSchema = runtimeThreadExecutionBaseOptionsSchema.and(runtimePermissionPolicySchema);
1499
+ var projectExecutionDefaultsSchema = z2.object({
1500
+ providerId: z2.string().min(1),
1501
+ model: z2.string().min(1),
1502
+ serviceTier: serviceTierSchema,
1503
+ reasoningLevel: reasoningLevelSchema,
1504
+ permissionMode: permissionModeSchema
1505
+ });
1506
+
1507
+ // ../domain/src/git-checkout.ts
1508
+ import { z as z3 } from "zod";
1509
+ var gitBranchForbiddenCharacterPattern = /[\u0000-\u001f\u007f\\:~^?*\[]/u;
1510
+ var gitBranchWhitespacePattern = /[ \t]/u;
1511
+ var gitReservedBranchNames = /* @__PURE__ */ new Set([
1512
+ "AUTO_MERGE",
1513
+ "BISECT_HEAD",
1514
+ "CHERRY_PICK_HEAD",
1515
+ "FETCH_HEAD",
1516
+ "HEAD",
1517
+ "MERGE_HEAD",
1518
+ "ORIG_HEAD",
1519
+ "REVERT_HEAD"
1520
+ ]);
1521
+ function isValidGitBranchName(name) {
1522
+ const components = name.split("/");
1523
+ 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(
1524
+ (component) => component.length > 0 && !component.startsWith(".") && !component.endsWith(".lock")
1525
+ );
1526
+ }
1527
+ var gitBranchNameSchema = z3.string().refine(isValidGitBranchName, { message: "Invalid git branch name" });
1528
+ var gitBranchSelectionSchema = z3.discriminatedUnion("kind", [
1529
+ z3.object({ kind: z3.literal("named"), name: gitBranchNameSchema }),
1530
+ z3.object({ kind: z3.literal("default") })
1531
+ ]);
1532
+ var gitCheckoutRefSchema = z3.discriminatedUnion("kind", [
1533
+ z3.object({
1534
+ kind: z3.literal("branch"),
1535
+ branchName: z3.string().min(1),
1536
+ headSha: z3.string().min(1).nullable()
1537
+ }),
1538
+ z3.object({
1539
+ kind: z3.literal("detached"),
1540
+ headSha: z3.string().min(1).nullable()
1541
+ }),
1542
+ z3.object({
1543
+ kind: z3.literal("unborn"),
1544
+ branchName: z3.string().min(1).nullable()
1545
+ }),
1546
+ z3.object({
1547
+ kind: z3.literal("unknown"),
1548
+ reason: z3.string().min(1)
1549
+ })
1550
+ ]);
1551
+ var workspaceGitOperationSchema = z3.discriminatedUnion("kind", [
1552
+ z3.object({ kind: z3.literal("none") }),
1553
+ z3.object({
1554
+ kind: z3.literal("merge"),
1555
+ hasConflicts: z3.boolean()
1556
+ }),
1557
+ z3.object({
1558
+ kind: z3.literal("rebase"),
1559
+ hasConflicts: z3.boolean()
1560
+ }),
1561
+ z3.object({
1562
+ kind: z3.literal("cherry-pick"),
1563
+ hasConflicts: z3.boolean()
1564
+ }),
1565
+ z3.object({
1566
+ kind: z3.literal("revert"),
1567
+ hasConflicts: z3.boolean()
1568
+ }),
1569
+ z3.object({
1570
+ kind: z3.literal("unknown"),
1571
+ reason: z3.string().min(1),
1572
+ hasConflicts: z3.boolean()
1573
+ })
1574
+ ]);
1575
+ var gitBranchRefClassificationSchema = z3.object({
1576
+ name: z3.string().min(1),
1577
+ kind: z3.enum(["local", "remote", "missing"])
1578
+ });
1579
+ var defaultBranchRelationSchema = z3.enum([
1580
+ "equal",
1581
+ "local-behind",
1582
+ "local-ahead",
1583
+ "diverged",
1584
+ "unknown"
1585
+ ]);
1586
+ var gitSourceInspectionSchema = z3.object({
1587
+ checkout: gitCheckoutRefSchema,
1588
+ defaultBranch: z3.string().min(1).nullable(),
1589
+ isWorktree: z3.boolean(),
1590
+ defaultBranchRelation: defaultBranchRelationSchema.nullable(),
1591
+ hasUncommittedChanges: z3.boolean(),
1592
+ operation: workspaceGitOperationSchema,
1593
+ originDefaultBranch: z3.string().min(1).nullable()
1594
+ });
1595
+ var gitBranchOptionsSchema = z3.object({
1596
+ branches: z3.array(z3.string()),
1597
+ branchesTruncated: z3.boolean(),
1598
+ remoteBranches: z3.array(z3.string()),
1599
+ remoteBranchesTruncated: z3.boolean(),
1600
+ selectedBranch: gitBranchRefClassificationSchema.nullable()
1601
+ });
1602
+ var projectSourceCheckoutSchema = gitSourceInspectionSchema.extend(
1603
+ gitBranchOptionsSchema.shape
1604
+ );
1605
+
1606
+ // ../domain/src/change-kinds.ts
1607
+ import { z as z18 } from "zod";
1608
+
1609
+ // ../domain/src/thread-event-types.ts
1610
+ import { z as z4 } from "zod";
1611
+ var systemEventTypeValues = [
1612
+ "client/thread/start",
1613
+ "client/turn/requested",
1614
+ "client/turn/rejected",
1615
+ "client/turn/start",
1616
+ "system/error",
1617
+ "system/manager/user_message",
1618
+ "system/thread/interrupted",
1619
+ "system/operation",
1620
+ "system/interaction/lifecycle",
1621
+ "system/permissionGrant/lifecycle",
1622
+ "system/userQuestion/lifecycle",
1623
+ "system/thread-provisioning",
1624
+ "system/provider-turn-watchdog"
1625
+ ];
1626
+ var providerEventTypeValues = [
1627
+ "thread/started",
1628
+ "thread/identity",
1629
+ "turn/started",
1630
+ "turn/completed",
1631
+ "turn/input/accepted",
1632
+ "thread/name/updated",
1633
+ "thread/compacted",
1634
+ "thread/context/cleared",
1635
+ "thread/goal/updated",
1636
+ "thread/goal/cleared",
1637
+ "item/started",
1638
+ "item/completed",
1639
+ "item/agentMessage/delta",
1640
+ "item/commandExecution/outputDelta",
1641
+ "item/fileChange/outputDelta",
1642
+ "item/reasoning/summaryTextDelta",
1643
+ "item/reasoning/textDelta",
1644
+ "item/plan/delta",
1645
+ "item/mcpToolCall/progress",
1646
+ "item/toolCall/progress",
1647
+ "item/backgroundTask/progress",
1648
+ "item/backgroundTask/completed",
1649
+ "item/delegation/progress",
1650
+ "item/delegation/completed",
1651
+ "thread/tokenUsage/updated",
1652
+ "thread/contextWindowUsage/updated",
1653
+ "turn/plan/updated",
1654
+ "turn/mainRun/updated",
1655
+ "turn/diff/updated",
1656
+ "provider/error",
1657
+ "provider/rateLimits/updated",
1658
+ "provider.env-resolved",
1659
+ "thread/extensionState/updated",
1660
+ "provider/warning",
1661
+ "provider/modelFallback",
1662
+ "provider/unhandled"
1663
+ ];
1664
+ var threadEventTypeValues = [
1665
+ ...providerEventTypeValues,
1666
+ ...systemEventTypeValues
1667
+ ];
1668
+ var threadEventTypeSet = new Set(threadEventTypeValues);
1669
+ var threadEventTypeSchema = z4.string().refine(
1670
+ (value) => threadEventTypeSet.has(value),
1671
+ "Invalid thread event type"
1672
+ );
1673
+
1674
+ // ../domain/src/thread.ts
1675
+ import { z as z17 } from "zod";
1676
+
1677
+ // ../domain/src/thread-create-origin.ts
1678
+ import { z as z5 } from "zod";
1679
+ var threadCreateOriginValues = ["app", "cli", "sdk", "plugin"];
1680
+ var threadCreateOriginSchema = z5.enum(threadCreateOriginValues);
1681
+
1682
+ // ../domain/src/environment.ts
1683
+ import { z as z6 } from "zod";
1684
+ var environmentMachineSelectionSchema = z6.discriminatedUnion("type", [
1685
+ z6.object({ type: z6.literal("existing"), hostId: z6.string().min(1) }),
1686
+ z6.object({
1687
+ type: z6.literal("new"),
1688
+ machineProviderId: z6.string().min(1),
1689
+ inputs: jsonValueSchema.nullable()
1690
+ })
1691
+ ]);
1692
+ var environmentProviderSelectionSchema = z6.object({
1693
+ machine: environmentMachineSelectionSchema,
1694
+ inputs: jsonValueSchema.nullable()
1695
+ });
1696
+ var environmentStatusValues = [
1697
+ "creating",
1698
+ "provisioning",
1699
+ "ready",
1700
+ "error",
1701
+ "destroyed"
1702
+ ];
1703
+ var environmentStatusSchema = z6.enum(environmentStatusValues);
1704
+ var environmentHostLifecycleValues = [
1705
+ "active",
1706
+ "removing",
1707
+ "cleanup-failed",
1708
+ "removed"
1709
+ ];
1710
+ var environmentHostLifecycleSchema = z6.enum(
1711
+ environmentHostLifecycleValues
1712
+ );
1713
+ var WORKSPACE_PROVISION_TYPES = [
1714
+ "unmanaged",
1715
+ "managed-worktree",
1716
+ "personal"
1717
+ ];
1718
+ var workspaceProvisionTypeSchema = z6.enum(WORKSPACE_PROVISION_TYPES);
1719
+ var environmentWorkspaceDisplayKindValues = [
1720
+ "managed-worktree",
1721
+ "unmanaged-worktree",
1722
+ "other"
1723
+ ];
1724
+ var environmentWorkspaceDisplayKindSchema = z6.enum(
1725
+ environmentWorkspaceDisplayKindValues
1726
+ );
1727
+ var discoveredWorkspacePropertiesSchema = z6.object({
1728
+ path: z6.string().min(1),
1729
+ isGitRepo: z6.boolean(),
1730
+ isWorktree: z6.boolean(),
1731
+ branchName: z6.string().nullable(),
1732
+ defaultBranch: z6.string().nullable()
1733
+ });
1734
+ var environmentLifecycleSchema = z6.object({
1735
+ phase: z6.enum(["active", "retiring", "teardown", "destroyed"]),
1736
+ retireAt: z6.number().nullable(),
1737
+ teardown: z6.object({
1738
+ status: z6.enum(["running", "failed", "removed"]),
1739
+ attempt: z6.number().int().nonnegative(),
1740
+ message: z6.string().optional()
1741
+ }).nullable()
1742
+ });
1743
+ var environmentSchema = z6.object({
1744
+ id: z6.string(),
1745
+ name: z6.string().nullable(),
1746
+ projectId: z6.string(),
1747
+ hostId: z6.string(),
1748
+ path: z6.string().nullable(),
1749
+ isGitRepo: z6.boolean(),
1750
+ isWorktree: z6.boolean(),
1751
+ branchName: z6.string().nullable(),
1752
+ baseBranch: z6.string().nullable(),
1753
+ defaultBranch: z6.string().nullable(),
1754
+ mergeBaseBranch: z6.string().nullable(),
1755
+ status: environmentStatusSchema,
1756
+ environmentProviderId: z6.string().nullable(),
1757
+ lifecycle: environmentLifecycleSchema,
1758
+ hostLifecycle: environmentHostLifecycleSchema,
1759
+ environmentProviderSelection: environmentProviderSelectionSchema.nullable(),
1760
+ environmentProviderInstanceKey: z6.string().nullable(),
1761
+ managed: z6.boolean(),
1762
+ workspaceProvisionType: workspaceProvisionTypeSchema.nullable(),
1763
+ createdAt: z6.number(),
1764
+ updatedAt: z6.number()
1765
+ });
1766
+
1767
+ // ../domain/src/queued-message.ts
1768
+ import { z as z10 } from "zod";
1769
+
1770
+ // ../domain/src/plugin-id.ts
1771
+ import { z as z7 } from "zod";
1772
+ var pluginIdSchema = z7.string().regex(/^[a-z0-9][a-z0-9-]*$/u);
1773
+
1774
+ // ../domain/src/protocol-ids.ts
1775
+ import { z as z8 } from "zod";
1776
+ var clientTurnRequestIdSchema = z8.string().regex(/^creq_[23456789abcdefghijkmnpqrstuvwxyz]{10}$/u);
1777
+
1778
+ // ../domain/src/system-message.ts
1779
+ import { z as z9 } from "zod";
1780
+ var systemMessageKindValues = [
1781
+ "ownership-assigned",
1782
+ "ownership-removed",
1783
+ "child-needs-attention",
1784
+ "child-completed",
1785
+ "child-failed",
1786
+ "child-interrupted",
1787
+ "child-outcome-batch",
1788
+ "tool-result-delivered",
1789
+ "environment-directory-updated",
1790
+ "unlabeled"
1791
+ ];
1792
+ var systemMessageKindSchema = z9.enum(systemMessageKindValues);
1793
+ var systemThreadInterruptedReasonSchema = z9.enum([
1794
+ "manual-stop",
1795
+ "host-daemon-restarted",
1796
+ "host-removed",
1797
+ "provider-turn-idle"
1798
+ ]);
1799
+ var childThreadOutcomeSchema = z9.object({
1800
+ threadId: z9.string(),
1801
+ status: z9.enum(["completed", "failed", "interrupted"]),
1802
+ interruption: z9.object({
1803
+ reason: systemThreadInterruptedReasonSchema,
1804
+ cause: z9.literal("host-connection-lost").optional()
1805
+ }).optional()
1806
+ });
1807
+ var systemMessageSubjectSchema = z9.discriminatedUnion("kind", [
1808
+ z9.object({
1809
+ kind: z9.literal("thread"),
1810
+ threadId: z9.string(),
1811
+ threadName: z9.string(),
1812
+ outcomes: z9.array(childThreadOutcomeSchema).optional()
1813
+ }),
1814
+ z9.object({
1815
+ kind: z9.literal("thread-batch"),
1816
+ count: z9.number(),
1817
+ outcomes: z9.array(childThreadOutcomeSchema).optional()
1818
+ }),
1819
+ z9.object({
1820
+ kind: z9.literal("tool-call"),
1821
+ toolName: z9.string(),
1822
+ suppress: z9.boolean()
1823
+ }),
1824
+ z9.object({
1825
+ kind: z9.literal("directory"),
1826
+ path: z9.string()
1827
+ })
1828
+ ]);
1829
+
1830
+ // ../domain/src/queued-message.ts
1831
+ var queuedMessageWaitingOnKindValues = [
1832
+ "time",
1833
+ "thread-busy",
1834
+ "stopping",
1835
+ "turn-starting",
1836
+ "provisioning",
1837
+ "host-offline",
1838
+ "interaction",
1839
+ "plugin"
1840
+ ];
1841
+ var queuedMessageWaitingOnKindSchema = z10.enum(
1842
+ queuedMessageWaitingOnKindValues
1843
+ );
1844
+ var queuedMessageWaitHostNameSchema = z10.string().min(1).max(200);
1845
+ var QUEUED_MESSAGE_WAIT_REASON_MAX_LENGTH = 200;
1846
+ var queuedMessageWaitReasonSchema = z10.string().min(1).max(QUEUED_MESSAGE_WAIT_REASON_MAX_LENGTH);
1847
+ var queuedMessageWaitingOnSchema = z10.discriminatedUnion("kind", [
1848
+ z10.object({ kind: z10.literal("time") }),
1849
+ z10.object({ kind: z10.literal("thread-busy") }),
1850
+ z10.object({ kind: z10.literal("stopping") }),
1851
+ z10.object({ kind: z10.literal("turn-starting") }),
1852
+ z10.object({ kind: z10.literal("provisioning") }),
1853
+ z10.object({
1854
+ kind: z10.literal("host-offline"),
1855
+ hostName: queuedMessageWaitHostNameSchema
1856
+ }),
1857
+ z10.object({ kind: z10.literal("interaction") }),
1858
+ z10.object({
1859
+ kind: z10.literal("plugin"),
1860
+ pluginId: pluginIdSchema,
1861
+ reason: queuedMessageWaitReasonSchema
1862
+ })
1863
+ ]);
1864
+ var QUEUED_MESSAGE_FAILURE_REASON_MAX_LENGTH = 200;
1865
+ var queuedMessageFailureReasonSchema = z10.string().min(1).max(QUEUED_MESSAGE_FAILURE_REASON_MAX_LENGTH);
1866
+ var QUEUED_MESSAGE_PLUGIN_WAIT_HOLDER_PREFIX = "plugin:";
1867
+ var queuedMessageWaitHolderSchema = z10.templateLiteral([
1868
+ QUEUED_MESSAGE_PLUGIN_WAIT_HOLDER_PREFIX,
1869
+ pluginIdSchema
1870
+ ]);
1871
+ var queuedMessagePayloadKindValues = ["inline", "retry"];
1872
+ var queuedMessagePayloadKindSchema = z10.enum(
1873
+ queuedMessagePayloadKindValues
1874
+ );
1875
+ var queuedMessagePayloadSchema = z10.discriminatedUnion("kind", [
1876
+ z10.object({ kind: z10.literal("inline") }),
1877
+ z10.object({
1878
+ kind: z10.literal("retry"),
1879
+ /**
1880
+ * The ORIGINAL request, not the attempt that just failed. Retrying a retry
1881
+ * re-submits the same original blocks, so this id is carried forward
1882
+ * unchanged across attempts and `attempt` is what distinguishes them.
1883
+ */
1884
+ retryOfTurnRequestId: clientTurnRequestIdSchema,
1885
+ /** Which attempt this row will dispatch: 2 is the first retry. */
1886
+ attempt: z10.number().int().min(2),
1887
+ /**
1888
+ * Why this turn is being retried, in the retrier's words ("Rate limited"),
1889
+ * as the row's card and `bb thread queue list` render it.
1890
+ *
1891
+ * It lives on the payload rather than on `waitingOn` because a retry can
1892
+ * wait on the clock, on a limiter, or on nothing at all, and the reason
1893
+ * outlives all three: it is a fact about the retry, not about what is
1894
+ * currently holding it. Filled at the boundary, so every row has one.
1895
+ */
1896
+ reason: queuedMessageWaitReasonSchema
1897
+ })
1898
+ ]);
1899
+ var queuedMessageSystemNoticeSchema = z10.object({
1900
+ kind: systemMessageKindSchema,
1901
+ subject: systemMessageSubjectSchema.nullable()
1902
+ });
1903
+
1904
+ // ../domain/src/queued-message-lifecycle.ts
1905
+ import { z as z11 } from "zod";
1906
+ var queuedMessageStateValues = [
1907
+ "queued",
1908
+ "scheduled",
1909
+ "waiting",
1910
+ "failed_retrying",
1911
+ "failed_exhausted",
1912
+ "claimed"
1913
+ ];
1914
+ var queuedMessageStateSchema = z11.enum(queuedMessageStateValues);
1915
+
1916
+ // ../domain/src/thread-status.ts
1917
+ import { z as z12 } from "zod";
1918
+ var threadStatusValues = [
1919
+ "pending",
1920
+ "idle",
1921
+ "starting",
1922
+ "active",
1923
+ "stopping",
1924
+ "error"
1925
+ ];
1926
+ var threadStatusSchema = z12.enum(threadStatusValues);
1927
+
1928
+ // ../domain/src/thread-origin-kind.ts
1929
+ import { z as z13 } from "zod";
1930
+ var threadOriginKindValues = ["fork"];
1931
+ var threadOriginKindSchema = z13.enum(threadOriginKindValues);
1932
+
1933
+ // ../domain/src/thread-parent-notifications.ts
1934
+ import { z as z14 } from "zod";
1935
+ var threadParentNotificationsValues = [
1936
+ "auto",
1937
+ "stuck",
1938
+ "off"
1939
+ ];
1940
+ var threadParentNotificationsSchema = z14.enum(
1941
+ threadParentNotificationsValues
1942
+ );
1943
+
1944
+ // ../domain/src/thread-visibility.ts
1945
+ import { z as z15 } from "zod";
1946
+ var threadVisibilityValues = ["visible", "hidden"];
1947
+ var threadVisibilitySchema = z15.enum(threadVisibilityValues);
1948
+
1949
+ // ../domain/src/thread-runtime-state.ts
1950
+ import { z as z16 } from "zod";
1951
+ var threadRuntimeDisplayStatusValues = [
1952
+ ...threadStatusValues,
1953
+ "provisioning",
1954
+ "waiting-for-host"
1955
+ ];
1956
+ var threadRuntimeDisplayStatusSchema = z16.enum(
1957
+ threadRuntimeDisplayStatusValues
1958
+ );
1959
+ var threadRuntimeStateSchema = z16.object({
1960
+ displayStatus: threadRuntimeDisplayStatusSchema
1961
+ });
1962
+ var threadActivityStateSchema = z16.object({
1963
+ activeWorkflowCount: z16.number().int().nonnegative(),
1964
+ activeBackgroundAgentCount: z16.number().int().nonnegative(),
1965
+ activeBackgroundCommandCount: z16.number().int().nonnegative(),
1966
+ activePlanModeCount: z16.number().int().nonnegative(),
1967
+ activeGoalCount: z16.number().int().nonnegative()
1968
+ });
1969
+
1970
+ // ../domain/src/thread.ts
1971
+ var workspaceStateValues = [
1972
+ "clean",
1973
+ "untracked",
1974
+ "dirty_uncommitted",
1975
+ "committed_unmerged",
1976
+ "dirty_and_committed_unmerged"
1977
+ ];
1978
+ var workspaceStateSchema = z17.enum(workspaceStateValues);
1979
+ var workspaceFileStatusKindSchema = z17.enum([
1980
+ "M",
1981
+ "A",
1982
+ "D",
1983
+ "R",
1984
+ "C",
1985
+ "U",
1986
+ "??",
1987
+ "?"
1988
+ ]);
1989
+ var workspaceFileStatusSchema = z17.object({
1990
+ path: z17.string(),
1991
+ status: workspaceFileStatusKindSchema,
1992
+ insertions: z17.number().nullable(),
1993
+ deletions: z17.number().nullable()
1994
+ });
1995
+ var workspaceCommitSummarySchema = z17.object({
1996
+ sha: z17.string(),
1997
+ shortSha: z17.string(),
1998
+ subject: z17.string(),
1999
+ authorName: z17.string(),
2000
+ authoredAt: z17.number()
2001
+ });
2002
+ var workspaceChangeStatsSchema = z17.object({
2003
+ insertions: z17.number(),
2004
+ deletions: z17.number(),
2005
+ lineStatsComplete: z17.boolean(),
2006
+ fileCount: z17.number().int().nonnegative(),
2007
+ files: z17.array(workspaceFileStatusSchema)
2008
+ });
2009
+ var workspaceWorkingTreeSchema = workspaceChangeStatsSchema.extend({
2010
+ hasUncommittedChanges: z17.boolean(),
2011
+ state: workspaceStateSchema
2012
+ });
2013
+ var workspaceBranchSchema = z17.object({
2014
+ currentBranch: z17.string().nullable(),
2015
+ defaultBranch: z17.string()
2016
+ });
2017
+ var workspaceMergeBaseSchema = workspaceChangeStatsSchema.extend({
2018
+ mergeBaseBranch: z17.string(),
2019
+ baseRef: z17.string().nullable(),
2020
+ aheadCount: z17.number(),
2021
+ behindCount: z17.number(),
2022
+ squashMergeCheckComplete: z17.boolean(),
2023
+ hasCommittedUnmergedChanges: z17.boolean(),
2024
+ commits: z17.array(workspaceCommitSummarySchema)
2025
+ });
2026
+ var workspaceStatusSchema = z17.object({
2027
+ workingTree: workspaceWorkingTreeSchema,
2028
+ checkout: gitCheckoutRefSchema,
2029
+ branch: workspaceBranchSchema,
2030
+ mergeBase: workspaceMergeBaseSchema.nullable()
2031
+ });
2032
+ var threadQueuedMessageSchema = z17.object({
2033
+ id: z17.string(),
2034
+ origin: threadCreateOriginSchema.nullable(),
2035
+ originPluginId: z17.string().nullable(),
2036
+ initiator: z17.enum(["user", "agent", "system"]),
2037
+ senderThreadId: z17.string().nullable(),
2038
+ /**
2039
+ * The thread this row is waiting on. Redundant on the thread-scoped list
2040
+ * route that first served this DTO, and load-bearing everywhere else it is
2041
+ * now served: a `queue.*` plugin event and a cross-thread wait-holder query
2042
+ * both hand out rows with no surrounding thread to read it from.
2043
+ */
2044
+ threadId: z17.string(),
2045
+ content: z17.array(promptInputSchema).min(1),
2046
+ model: z17.string().min(1),
2047
+ reasoningLevel: reasoningLevelSchema,
2048
+ permissionMode: permissionModeSchema,
2049
+ serviceTier: serviceTierSchema,
2050
+ groupWithNext: z17.boolean(),
2051
+ /**
2052
+ * Epoch ms this row is scheduled to attempt dispatch, or null when it is
2053
+ * eligible as soon as its other waits clear.
2054
+ */
2055
+ sendAt: z17.number().int().nonnegative().nullable(),
2056
+ state: queuedMessageStateSchema,
2057
+ /**
2058
+ * Why this row is queued, or null for a `queued` row that is simply next in
2059
+ * line behind the running turn.
2060
+ */
2061
+ waitingOn: queuedMessageWaitingOnSchema.nullable(),
2062
+ /**
2063
+ * Why this row's last DRAIN attempt failed outright, or null when it has not
2064
+ * failed one — which is every row that has never been re-attempted, and
2065
+ * every row whose latest attempt merely queued again. An inline attempt
2066
+ * reports its failure to the sender that is still listening and never lands
2067
+ * here.
2068
+ *
2069
+ * Independent of `waitingOn`, not folded into it: the row is still waiting on
2070
+ * whatever it was waiting on, and writing a wait rewrites it wholesale, so a
2071
+ * failure stored there would not survive the next attempt.
2072
+ */
2073
+ failureReason: queuedMessageFailureReasonSchema.nullable(),
2074
+ payload: queuedMessagePayloadSchema,
2075
+ /**
2076
+ * Whether the sender may still rewrite this row's input. Not derivable from
2077
+ * `payload` alone: a `retry` row is never editable, and an `inline` row
2078
+ * stops being editable once the drain has claimed it — and the claim is
2079
+ * deliberately not part of this response, since it is drain bookkeeping and
2080
+ * not something a client should reason about. The server folds both into
2081
+ * this one answer.
2082
+ */
2083
+ editable: z17.boolean(),
2084
+ createdAt: z17.number(),
2085
+ updatedAt: z17.number()
2086
+ });
2087
+ var threadSchema = z17.object({
2088
+ id: z17.string(),
2089
+ projectId: z17.string(),
2090
+ environmentId: z17.string().nullable(),
2091
+ providerId: z17.string(),
2092
+ title: z17.string().nullable(),
2093
+ titleFallback: z17.string().nullable(),
2094
+ sectionId: z17.string().nullable(),
2095
+ status: threadStatusSchema,
2096
+ parentThreadId: z17.string().nullable(),
2097
+ lifecycleOwnerThreadId: z17.string().nullable(),
2098
+ sourceThreadId: z17.string().nullable(),
2099
+ originKind: threadOriginKindSchema.nullable(),
2100
+ originPluginId: z17.string().nullable(),
2101
+ visibility: threadVisibilitySchema,
2102
+ parentNotifications: threadParentNotificationsSchema,
2103
+ archivedAt: z17.number().nullable(),
2104
+ pinnedAt: z17.number().nullable(),
2105
+ deletedAt: z17.number().nullable(),
2106
+ lastReadAt: z17.number().nullable(),
2107
+ latestAttentionAt: z17.number(),
2108
+ createdAt: z17.number(),
2109
+ updatedAt: z17.number()
2110
+ });
2111
+ var threadWithRuntimeSchema = threadSchema.extend({
2112
+ runtime: threadRuntimeStateSchema
2113
+ });
2114
+ var threadQueuedWorkValues = ["none", "waiting", "failed"];
2115
+ var threadQueuedWorkSchema = z17.enum(threadQueuedWorkValues);
2116
+ var threadListEntrySchema = threadWithRuntimeSchema.extend({
2117
+ activity: threadActivityStateSchema,
2118
+ queuedWork: threadQueuedWorkSchema,
2119
+ pinSortKey: z17.string().nullable(),
2120
+ hasPendingInteraction: z17.boolean(),
2121
+ environmentHostId: z17.string().nullable(),
2122
+ environmentName: z17.string().nullable(),
2123
+ environmentBranchName: z17.string().nullable(),
2124
+ environmentPath: z17.string().nullable(),
2125
+ environmentProviderId: z17.string().nullable(),
2126
+ environmentIsWorktree: z17.boolean().nullable(),
2127
+ environmentWorkspaceDisplayKind: environmentWorkspaceDisplayKindSchema
2128
+ });
2129
+
2130
+ // ../domain/src/change-kinds.ts
2131
+ var THREAD_CHANGE_KINDS = [
2132
+ "thread-created",
2133
+ "thread-deleted",
2134
+ "events-appended",
2135
+ "history-rewritten",
2136
+ "history-compacted",
2137
+ "interactions-changed",
2138
+ "status-changed",
2139
+ "title-changed",
2140
+ "queue-changed",
2141
+ "archived-changed",
2142
+ "pin-state-changed",
2143
+ "parent-changed",
2144
+ "environment-changed",
2145
+ "read-state-changed",
2146
+ "tabs-changed",
2147
+ "terminals-changed"
2148
+ ];
2149
+ var PROJECT_CHANGE_KINDS = [
2150
+ "project-created",
2151
+ "project-updated",
2152
+ "project-deleted",
2153
+ "project-sources-changed",
2154
+ "threads-changed",
2155
+ "project-order-changed"
2156
+ ];
2157
+ var ENVIRONMENT_CHANGE_KINDS = [
2158
+ "environment-created",
2159
+ "environment-deleted",
2160
+ "metadata-changed",
2161
+ "status-changed",
2162
+ "work-status-changed",
2163
+ "git-refs-changed",
2164
+ "thread-storage-changed",
2165
+ "diff-viewed-changed"
2166
+ ];
2167
+ var HOST_CHANGE_KINDS = [
2168
+ "host-connected",
2169
+ "host-disconnected",
2170
+ "provider-model-catalog-changed"
2171
+ ];
2172
+ var SYSTEM_CHANGE_KINDS = [
2173
+ "config-changed",
2174
+ "plugins-changed",
2175
+ "plugin-install-jobs-changed",
2176
+ "plugin-update-jobs-changed",
2177
+ "provider-registrations-changed",
2178
+ "environment-availability-changed",
2179
+ "server-move-changed",
2180
+ "app-update-changed"
2181
+ ];
2182
+ var threadChangeKindSchema = z18.enum(THREAD_CHANGE_KINDS);
2183
+ var projectChangeKindSchema = z18.enum(PROJECT_CHANGE_KINDS);
2184
+ var environmentChangeKindSchema = z18.enum(ENVIRONMENT_CHANGE_KINDS);
2185
+ var hostChangeKindSchema = z18.enum(HOST_CHANGE_KINDS);
2186
+ var systemChangeKindSchema = z18.enum(SYSTEM_CHANGE_KINDS);
2187
+ var threadTimelineSubscriptionTargetSchema = z18.object({
2188
+ kind: z18.literal("thread-timeline"),
2189
+ threadId: z18.string().min(1),
2190
+ segmentLimit: z18.number().int().positive().nullable(),
2191
+ deferContent: z18.boolean()
2192
+ }).strict();
2193
+ function canonicalPluginReadInput(value) {
2194
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
2195
+ if (Array.isArray(value))
2196
+ return `[${value.map(canonicalPluginReadInput).join(",")}]`;
2197
+ return `{${Object.keys(value).sort().map(
2198
+ (key) => `${JSON.stringify(key)}:${canonicalPluginReadInput(value[key])}`
2199
+ ).join(",")}}`;
2200
+ }
2201
+ var pluginReadSubscriptionTargetSchema = z18.object({
2202
+ kind: z18.literal("plugin-read"),
2203
+ pluginId: z18.string().min(1),
2204
+ method: z18.string().min(1),
2205
+ read: z18.union([
2206
+ z18.object({ input: jsonValueSchema }).strict(),
2207
+ z18.object({ key: z18.string() }).strict()
2208
+ ]).refine(
2209
+ (read) => new TextEncoder().encode(canonicalPluginReadInput(read)).byteLength <= 16384,
2210
+ "Plugin read input exceeds 16 KiB"
2211
+ )
2212
+ }).strict();
2213
+ var realtimeSubscriptionTargetSchema = z18.discriminatedUnion("kind", [
2214
+ pluginReadSubscriptionTargetSchema,
2215
+ z18.object({ kind: z18.literal("plugin"), pluginId: z18.string().min(1) }).strict(),
2216
+ z18.object({
2217
+ kind: z18.literal("thread-detail"),
2218
+ threadId: z18.string().min(1)
2219
+ }).strict(),
2220
+ threadTimelineSubscriptionTargetSchema,
2221
+ z18.object({
2222
+ kind: z18.literal("thread-list")
2223
+ }).strict(),
2224
+ z18.object({
2225
+ kind: z18.literal("project-detail"),
2226
+ projectId: z18.string().min(1)
2227
+ }).strict(),
2228
+ z18.object({
2229
+ kind: z18.literal("project-list")
2230
+ }).strict(),
2231
+ z18.object({
2232
+ kind: z18.literal("environment-detail"),
2233
+ environmentId: z18.string().min(1)
2234
+ }).strict(),
2235
+ z18.object({
2236
+ kind: z18.literal("environment-list")
2237
+ }).strict(),
2238
+ z18.object({
2239
+ kind: z18.literal("host-detail"),
2240
+ hostId: z18.string().min(1)
2241
+ }).strict(),
2242
+ z18.object({
2243
+ kind: z18.literal("host-list")
2244
+ }).strict(),
2245
+ z18.object({
2246
+ kind: z18.literal("system")
2247
+ }).strict()
2248
+ ]);
2249
+ function isValidSubscriptionTarget(value) {
2250
+ return realtimeSubscriptionTargetSchema.safeParse(value).success;
2251
+ }
2252
+ var validSubscriptionTargetsSchema = z18.preprocess(
2253
+ (value) => Array.isArray(value) ? value.filter(isValidSubscriptionTarget) : value,
2254
+ z18.array(realtimeSubscriptionTargetSchema)
2255
+ );
2256
+ var validSubscriptionTargetSchema = z18.preprocess(
2257
+ (value) => value === void 0 || isValidSubscriptionTarget(value) ? value : null,
2258
+ realtimeSubscriptionTargetSchema.nullable().optional()
2259
+ );
2260
+ var subscriptionFields = {
2261
+ target: validSubscriptionTargetSchema,
2262
+ targets: validSubscriptionTargetsSchema.optional()
2263
+ };
2264
+ var hasSubscriptionTargets = (value) => value.target !== void 0 !== (value.targets !== void 0);
2265
+ var subscribeMessageSchema = z18.object({ type: z18.literal("subscribe"), ...subscriptionFields }).refine(hasSubscriptionTargets);
2266
+ var unsubscribeMessageSchema = z18.object({ type: z18.literal("unsubscribe"), ...subscriptionFields }).refine(hasSubscriptionTargets);
2267
+ var pingMessageSchema = z18.object({
2268
+ type: z18.literal("ping")
2269
+ });
2270
+ var visibilityMessageSchema = z18.object({
2271
+ type: z18.literal("visibility"),
2272
+ visible: z18.boolean()
2273
+ });
2274
+ var clientMessageSchema = z18.discriminatedUnion("type", [
2275
+ subscribeMessageSchema,
2276
+ unsubscribeMessageSchema,
2277
+ pingMessageSchema,
2278
+ visibilityMessageSchema
2279
+ ]);
2280
+ var pongMessageSchema = z18.object({
2281
+ type: z18.literal("pong")
2282
+ }).strict();
2283
+ var pongMessageLenientSchema = z18.object({
2284
+ type: z18.literal("pong")
2285
+ });
2286
+ var threadStatusChangeMetadataSchema = z18.object({
2287
+ status: threadStatusSchema,
2288
+ runtime: threadRuntimeStateSchema,
2289
+ activity: threadActivityStateSchema,
2290
+ latestAttentionAt: z18.number(),
2291
+ updatedAt: z18.number()
2292
+ }).strict();
2293
+ var threadChangeMetadataSchema = z18.object({
2294
+ backgroundActivityChanged: z18.boolean().optional(),
2295
+ eventTypes: z18.array(threadEventTypeSchema).readonly().optional(),
2296
+ timelineSequence: z18.number().int().nonnegative().optional(),
2297
+ hasPendingInteraction: z18.boolean().optional(),
2298
+ projectId: z18.string().optional(),
2299
+ statusChange: threadStatusChangeMetadataSchema.optional()
2300
+ }).strict();
2301
+ var threadChangedMessageSchema = z18.object({
2302
+ type: z18.literal("changed"),
2303
+ entity: z18.literal("thread"),
2304
+ id: z18.string().optional(),
2305
+ metadata: threadChangeMetadataSchema.optional(),
2306
+ changes: z18.array(threadChangeKindSchema).readonly()
2307
+ }).strict();
2308
+ var projectChangedMessageSchema = z18.object({
2309
+ type: z18.literal("changed"),
2310
+ entity: z18.literal("project"),
2311
+ id: z18.string().optional(),
2312
+ changes: z18.array(projectChangeKindSchema).readonly()
2313
+ }).strict();
2314
+ var environmentChangedMessageSchema = z18.object({
2315
+ type: z18.literal("changed"),
2316
+ entity: z18.literal("environment"),
2317
+ id: z18.string().optional(),
2318
+ changes: z18.array(environmentChangeKindSchema).readonly()
2319
+ }).strict();
2320
+ var hostChangedMessageSchema = z18.object({
2321
+ type: z18.literal("changed"),
2322
+ entity: z18.literal("host"),
2323
+ id: z18.string().optional(),
2324
+ changes: z18.array(hostChangeKindSchema).readonly()
2325
+ }).strict();
2326
+ var systemChangedMessageSchema = z18.object({
2327
+ type: z18.literal("changed"),
2328
+ entity: z18.literal("system"),
2329
+ changes: z18.array(systemChangeKindSchema).readonly()
2330
+ }).strict();
2331
+ var tagsChangedMessageSchema = z18.object({
2332
+ type: z18.literal("changed"),
2333
+ entity: z18.literal("tags"),
2334
+ tags: z18.array(z18.string().min(1)).min(1)
2335
+ }).strict();
2336
+ var pluginChangedMessageSchema = z18.object({
2337
+ type: z18.literal("changed"),
2338
+ entity: z18.literal("plugin"),
2339
+ pluginId: z18.string().min(1),
2340
+ tags: z18.array(z18.string().min(1)).min(1).nullable()
2341
+ }).strict();
2342
+ var changedMessageSchema = z18.discriminatedUnion("entity", [
2343
+ threadChangedMessageSchema,
2344
+ projectChangedMessageSchema,
2345
+ environmentChangedMessageSchema,
2346
+ hostChangedMessageSchema,
2347
+ systemChangedMessageSchema,
2348
+ tagsChangedMessageSchema,
2349
+ pluginChangedMessageSchema
2350
+ ]);
2351
+ function lenientKinds(kinds) {
2352
+ const known = new Set(kinds);
2353
+ return z18.array(z18.string()).transform(
2354
+ (values) => values.filter((value) => known.has(value))
2355
+ );
2356
+ }
2357
+ var knownThreadEventTypes = new Set(
2358
+ threadEventTypeValues
2359
+ );
2360
+ var threadChangeMetadataLenientSchema = z18.object({
2361
+ timelineSequence: z18.number().int().nonnegative().optional(),
2362
+ backgroundActivityChanged: z18.boolean().optional(),
2363
+ eventTypes: z18.array(z18.string()).transform(
2364
+ (values) => values.filter(
2365
+ (value) => knownThreadEventTypes.has(value)
2366
+ )
2367
+ ).optional(),
2368
+ hasPendingInteraction: z18.boolean().optional(),
2369
+ projectId: z18.string().optional(),
2370
+ statusChange: threadStatusChangeMetadataSchema.optional().catch(void 0)
2371
+ });
2372
+ var threadChangedMessageLenientSchema = z18.object({
2373
+ type: z18.literal("changed"),
2374
+ entity: z18.literal("thread"),
2375
+ id: z18.string().optional(),
2376
+ metadata: threadChangeMetadataLenientSchema.optional(),
2377
+ changes: lenientKinds(THREAD_CHANGE_KINDS)
2378
+ });
2379
+ var projectChangedMessageLenientSchema = z18.object({
2380
+ type: z18.literal("changed"),
2381
+ entity: z18.literal("project"),
2382
+ id: z18.string().optional(),
2383
+ changes: lenientKinds(PROJECT_CHANGE_KINDS)
2384
+ });
2385
+ var environmentChangedMessageLenientSchema = z18.object({
2386
+ type: z18.literal("changed"),
2387
+ entity: z18.literal("environment"),
2388
+ id: z18.string().optional(),
2389
+ changes: lenientKinds(ENVIRONMENT_CHANGE_KINDS)
2390
+ });
2391
+ var hostChangedMessageLenientSchema = z18.object({
2392
+ type: z18.literal("changed"),
2393
+ entity: z18.literal("host"),
2394
+ id: z18.string().optional(),
2395
+ changes: lenientKinds(HOST_CHANGE_KINDS)
2396
+ });
2397
+ var systemChangedMessageLenientSchema = z18.object({
2398
+ type: z18.literal("changed"),
2399
+ entity: z18.literal("system"),
2400
+ changes: lenientKinds(SYSTEM_CHANGE_KINDS)
2401
+ });
2402
+ var changedMessageLenientSchema = z18.discriminatedUnion("entity", [
2403
+ threadChangedMessageLenientSchema,
2404
+ projectChangedMessageLenientSchema,
2405
+ environmentChangedMessageLenientSchema,
2406
+ hostChangedMessageLenientSchema,
2407
+ systemChangedMessageLenientSchema,
2408
+ tagsChangedMessageSchema.strip(),
2409
+ pluginChangedMessageSchema.strip()
2410
+ ]);
2411
+
2412
+ // src/internal/rpc-tags.ts
2413
+ import { z as z19 } from "zod";
2414
+ var rpcInvalidationTags = z19.array(z19.string().min(1)).min(1);
2415
+ function rpcResponseTags(declarations, input, output) {
2416
+ const tags = z19.array(z19.string().min(1)).parse(declarations.tags?.(input, output) ?? []);
2417
+ const keyTags = {};
2418
+ if (declarations.keyTags && typeof output === "object" && output !== null && !Array.isArray(output)) {
2419
+ for (const [key, value] of Object.entries(output)) {
2420
+ keyTags[key] = z19.array(z19.string().min(1)).parse(declarations.keyTags(key, value));
2421
+ }
2422
+ }
2423
+ const invalidated = z19.array(z19.string().min(1)).parse(declarations.invalidates?.(input, output) ?? []);
2424
+ return { tags, keyTags, invalidated };
2425
+ }
2426
+
2427
+ // src/internal/rpc-query-host.ts
2428
+ import { z as z20 } from "zod";
680
2429
  var rpcQueryKey = (pluginId, method, input) => [
681
2430
  "plugin-rpc",
682
2431
  pluginId,
@@ -684,47 +2433,79 @@ var rpcQueryKey = (pluginId, method, input) => [
684
2433
  input
685
2434
  ];
686
2435
  var keyedQueryKey = (pluginId, method) => rpcQueryKey(pluginId, method, { keyed: true });
2436
+ var keyedCollections = /* @__PURE__ */ new Map();
2437
+ function keyedCollection(pluginId, method) {
2438
+ const name = JSON.stringify([pluginId, method]);
2439
+ let collection = keyedCollections.get(name);
2440
+ if (!collection) {
2441
+ collection = new KeyedCollection(name);
2442
+ keyedCollections.set(name, collection);
2443
+ }
2444
+ return collection;
2445
+ }
2446
+ function parsedUpdate(update) {
2447
+ return (current) => jsonValueSchema.parse(update(current));
2448
+ }
687
2449
  function optimisticCache(pluginId, updates) {
688
- const add = (prediction) => {
689
- updates.push({
690
- ...prediction,
691
- update: (current) => jsonValueSchema.parse(prediction.update(current))
692
- });
693
- };
694
2450
  return {
695
2451
  update(method, input, update) {
696
- add(
2452
+ updates.push(
697
2453
  optimisticQueryUpdate(
698
2454
  rpcQueryKey(pluginId, method, jsonValueSchema.parse(input ?? null)),
699
- update,
2455
+ parsedUpdate(update),
700
2456
  ["result"]
701
2457
  )
702
2458
  );
703
2459
  },
704
2460
  updateKey(method, key, update) {
705
- add(
706
- optimisticQueryUpdate(keyedQueryKey(pluginId, method), update, [
707
- "result",
708
- key
709
- ])
2461
+ updates.push(
2462
+ optimisticKeyedUpdate(
2463
+ keyedCollection(pluginId, method),
2464
+ key,
2465
+ parsedUpdate(update)
2466
+ )
710
2467
  );
711
2468
  }
712
2469
  };
713
2470
  }
714
- async function callRpcEnvelope(host, pluginId, method, input) {
2471
+ async function callRpc(host, pluginId, contract, method, input) {
715
2472
  let raw;
716
2473
  try {
717
2474
  raw = await host.call(pluginId, method, input);
718
2475
  } catch (error) {
719
2476
  throw experimental_PluginRpcCallError.from(error);
720
2477
  }
721
- const parsed = envelopeSchema.safeParse(raw);
722
- if (!parsed.success)
723
- throw new experimental_PluginRpcCallError({
724
- code: "invalid_response",
725
- message: `Invalid RPC response for ${method}`
726
- });
727
- return parsed.data;
2478
+ const result = jsonValueSchema.safeParse(raw);
2479
+ if (!result.success)
2480
+ throw new experimental_PluginRpcCallError({
2481
+ code: "invalid_response",
2482
+ message: `Invalid RPC response for ${method}`
2483
+ });
2484
+ const methodContract = contract[method];
2485
+ if (methodContract === void 0)
2486
+ throw new experimental_PluginRpcCallError({
2487
+ code: "unknown_method",
2488
+ message: `rpc method "${method}" isn't in the contract`
2489
+ });
2490
+ const parsedInput = await methodContract.input["~standard"].validate(input);
2491
+ if (parsedInput.issues !== void 0)
2492
+ throw new experimental_PluginRpcCallError({
2493
+ code: "invalid_input",
2494
+ message: `rpc input validation failed for ${method}`
2495
+ });
2496
+ return {
2497
+ result: result.data,
2498
+ ...rpcResponseTags(methodContract, parsedInput.value, result.data)
2499
+ };
2500
+ }
2501
+ function resolvePluginId(host, pluginId) {
2502
+ const resolved = pluginId ?? host.pluginId;
2503
+ if (resolved === null) {
2504
+ throw new Error(
2505
+ "plugin RPC hooks outside a plugin slot component need an explicit pluginId"
2506
+ );
2507
+ }
2508
+ return resolved;
728
2509
  }
729
2510
  var tagsOf = (data) => [
730
2511
  ...data.tags,
@@ -740,10 +2521,17 @@ function createRpcQueryHooks(useHost) {
740
2521
  }
741
2522
  const experimental_useRpcQuery = (options) => {
742
2523
  const host = useHost();
743
- const pluginId = options.pluginId ?? host.pluginId;
2524
+ const pluginId = resolvePluginId(host, options.pluginId);
744
2525
  const input = jsonValueSchema.parse(options.input ?? null);
745
2526
  const queryKey = rpcQueryKey(pluginId, options.method, input);
746
2527
  useSubscription(host, pluginId, options.enabled ?? true);
2528
+ const watchIdentity = canonicalPluginReadInput(input);
2529
+ useEffect2(() => {
2530
+ if (options.enabled === false) return;
2531
+ return host.watch?.(pluginId, options.method, {
2532
+ input: jsonValueSchema.parse(JSON.parse(watchIdentity))
2533
+ });
2534
+ }, [host, pluginId, options.method, watchIdentity, options.enabled]);
747
2535
  const query = useTaggedQuery(
748
2536
  {
749
2537
  queryKey,
@@ -755,7 +2543,7 @@ function createRpcQueryHooks(useHost) {
755
2543
  queryFn: () => runTaggedRead(
756
2544
  host.queryClient,
757
2545
  queryKey,
758
- async () => callRpcEnvelope(host, pluginId, options.method, input)
2546
+ async () => callRpc(host, pluginId, options.contract, options.method, input)
759
2547
  )
760
2548
  },
761
2549
  host.queryClient
@@ -775,11 +2563,11 @@ function createRpcQueryHooks(useHost) {
775
2563
  };
776
2564
  function experimental_useRpcKeyedQuery(options) {
777
2565
  const host = useHost();
778
- const pluginId = options.pluginId ?? host.pluginId;
2566
+ const pluginId = resolvePluginId(host, options.pluginId);
779
2567
  const enabled = options.enabled ?? true;
780
2568
  const identity = JSON.stringify([...new Set(options.keys)].sort());
781
2569
  const keys = useMemo2(
782
- () => z2.array(z2.string()).parse(JSON.parse(identity)),
2570
+ () => z20.array(z20.string()).parse(JSON.parse(identity)),
783
2571
  [identity]
784
2572
  );
785
2573
  let cache = owners.get(host.queryClient);
@@ -794,16 +2582,18 @@ function createRpcQueryHooks(useHost) {
794
2582
  client: host.queryClient,
795
2583
  queryKey: keyedQueryKey(pluginId, options.method),
796
2584
  scope: pluginTagScope(pluginId),
2585
+ collection: keyedCollection(pluginId, options.method),
797
2586
  read: async (keys2) => {
798
- const response = await callRpcEnvelope(
2587
+ const response = await callRpc(
799
2588
  host,
800
2589
  pluginId,
2590
+ options.contract,
801
2591
  options.method,
802
2592
  { keys: [...keys2] }
803
2593
  );
804
2594
  return {
805
2595
  ...response,
806
- result: z2.record(z2.string(), jsonValueSchema).parse(response.result)
2596
+ result: z20.record(z20.string(), jsonValueSchema).parse(response.result)
807
2597
  };
808
2598
  }
809
2599
  });
@@ -840,6 +2630,15 @@ function createRpcQueryHooks(useHost) {
840
2630
  [keys, enabled, selectRows]
841
2631
  );
842
2632
  const query = useQuerySelection(subscribe, getSnapshot, select);
2633
+ useEffect2(() => {
2634
+ if (!enabled) return;
2635
+ const releases = keys.map(
2636
+ (key) => host.watch?.(pluginId, options.method, { key })
2637
+ );
2638
+ return () => {
2639
+ releases.forEach((release) => release?.());
2640
+ };
2641
+ }, [host, pluginId, options.method, keys, enabled]);
843
2642
  const refetch = useCallback2(async () => {
844
2643
  await current.observer.refetch();
845
2644
  }, [current]);
@@ -850,14 +2649,15 @@ function createRpcQueryHooks(useHost) {
850
2649
  }
851
2650
  function experimental_useRpcMutation(options) {
852
2651
  const host = useHost();
853
- const pluginId = options.pluginId ?? host.pluginId;
854
- const mutation = useTaggedMutation(
855
- host.queryClient,
856
- (tags) => invalidateTags(host.queryClient, pluginTagScope(pluginId), tags),
857
- async (input) => {
858
- const response = await callRpcEnvelope(
2652
+ const pluginId = resolvePluginId(host, options.pluginId);
2653
+ const mutation = useTaggedMutation({
2654
+ client: host.queryClient,
2655
+ invalidate: (tags) => invalidateTags(host.queryClient, pluginTagScope(pluginId), tags),
2656
+ call: async (input) => {
2657
+ const response = await callRpc(
859
2658
  host,
860
2659
  pluginId,
2660
+ options.contract,
861
2661
  options.method,
862
2662
  jsonValueSchema.parse(input)
863
2663
  );
@@ -866,7 +2666,7 @@ function createRpcQueryHooks(useHost) {
866
2666
  result: response.result
867
2667
  };
868
2668
  },
869
- (input) => {
2669
+ optimistic: (input) => {
870
2670
  const updates = [];
871
2671
  options.optimistic?.(
872
2672
  input,
@@ -874,7 +2674,7 @@ function createRpcQueryHooks(useHost) {
874
2674
  );
875
2675
  return updates;
876
2676
  }
877
- );
2677
+ });
878
2678
  const { mutate } = mutation;
879
2679
  return {
880
2680
  ...mutation,
@@ -898,18 +2698,12 @@ function createRpcQueryHooks(useHost) {
898
2698
  }
899
2699
  function experimental_useRpcRefresh() {
900
2700
  const host = useHost();
901
- const isRefreshing = useIsFetching(
902
- { queryKey: ["plugin-rpc", host.pluginId] },
903
- host.queryClient
904
- ) > 0;
2701
+ const pluginId = resolvePluginId(host, void 0);
2702
+ const isRefreshing = useIsFetching({ queryKey: ["plugin-rpc", pluginId] }, host.queryClient) > 0;
905
2703
  return {
906
2704
  isRefreshing,
907
2705
  refresh: () => {
908
- void invalidateTags(
909
- host.queryClient,
910
- pluginTagScope(host.pluginId),
911
- null
912
- );
2706
+ void invalidateTags(host.queryClient, pluginTagScope(pluginId), null);
913
2707
  }
914
2708
  };
915
2709
  }
@@ -921,25 +2715,11 @@ function createRpcQueryHooks(useHost) {
921
2715
  };
922
2716
  }
923
2717
 
924
- // src/internal/rpc-tags.ts
925
- import { z as z3 } from "zod";
926
- var rpcInvalidationTags = z3.array(z3.string().min(1)).min(1);
927
- function rpcResponseTags(declarations, input, output) {
928
- const tags = z3.array(z3.string().min(1)).parse(declarations.tags?.(input, output) ?? []);
929
- const keyTags = {};
930
- if (declarations.keyTags && typeof output === "object" && output !== null && !Array.isArray(output)) {
931
- for (const [key, value] of Object.entries(output)) {
932
- keyTags[key] = z3.array(z3.string().min(1)).parse(declarations.keyTags(key, value));
933
- }
934
- }
935
- const invalidated = z3.array(z3.string().min(1)).parse(declarations.invalidates?.(input, output) ?? []);
936
- return { tags, keyTags, invalidated };
937
- }
938
-
939
2718
  // src/testing/app.tsx
940
2719
  import * as React from "react";
941
2720
  import {
942
2721
  createContext,
2722
+ Fragment,
943
2723
  useCallback as useCallback3,
944
2724
  useContext,
945
2725
  useLayoutEffect,
@@ -1013,71 +2793,71 @@ function reconcileComposerMentions(currentText, nextText, mentions) {
1013
2793
  }
1014
2794
 
1015
2795
  // src/internal/composer-draft-actions.ts
1016
- import { z as z4 } from "zod";
2796
+ import { z as z21 } from "zod";
1017
2797
  var range = {
1018
- from: z4.number().int().nonnegative(),
1019
- to: z4.number().int().nonnegative(),
1020
- label: z4.string()
2798
+ from: z21.number().int().nonnegative(),
2799
+ to: z21.number().int().nonnegative(),
2800
+ label: z21.string()
1021
2801
  };
1022
- var mentionSchema = z4.discriminatedUnion("kind", [
1023
- z4.object({
2802
+ var mentionSchema = z21.discriminatedUnion("kind", [
2803
+ z21.object({
1024
2804
  ...range,
1025
- kind: z4.literal("thread"),
1026
- threadId: z4.string(),
1027
- projectId: z4.string().optional()
2805
+ kind: z21.literal("thread"),
2806
+ threadId: z21.string(),
2807
+ projectId: z21.string().optional()
1028
2808
  }),
1029
- z4.object({ ...range, kind: z4.literal("project"), projectId: z4.string() }),
1030
- z4.object({ ...range, kind: z4.literal("section"), sectionId: z4.string() }),
1031
- z4.object({
2809
+ z21.object({ ...range, kind: z21.literal("project"), projectId: z21.string() }),
2810
+ z21.object({ ...range, kind: z21.literal("section"), sectionId: z21.string() }),
2811
+ z21.object({
1032
2812
  ...range,
1033
- kind: z4.literal("path"),
1034
- path: z4.string(),
1035
- source: z4.enum(["workspace", "thread-storage"]),
1036
- entryKind: z4.enum(["file", "directory"])
2813
+ kind: z21.literal("path"),
2814
+ path: z21.string(),
2815
+ source: z21.enum(["workspace", "thread-storage"]),
2816
+ entryKind: z21.enum(["file", "directory"])
1037
2817
  }),
1038
- z4.object({
2818
+ z21.object({
1039
2819
  ...range,
1040
- kind: z4.literal("command"),
1041
- trigger: z4.enum(["/", "$"]),
1042
- name: z4.string(),
1043
- source: z4.enum(["skill", "command"]),
1044
- origin: z4.enum(["builtin", "project", "user"]),
1045
- argumentHint: z4.string().nullable()
2820
+ kind: z21.literal("command"),
2821
+ trigger: z21.enum(["/", "$"]),
2822
+ name: z21.string(),
2823
+ source: z21.enum(["skill", "command"]),
2824
+ origin: z21.enum(["builtin", "project", "user"]),
2825
+ argumentHint: z21.string().nullable()
1046
2826
  }),
1047
- z4.object({ ...range, kind: z4.literal("attachment"), path: z4.string() }),
1048
- z4.object({
2827
+ z21.object({ ...range, kind: z21.literal("attachment"), path: z21.string() }),
2828
+ z21.object({
1049
2829
  ...range,
1050
- kind: z4.literal("plugin"),
1051
- pluginId: z4.string(),
1052
- provider: z4.string().min(1).refine((value) => !value.includes(":")),
1053
- id: z4.string(),
1054
- icon: z4.string().nullable().optional()
2830
+ kind: z21.literal("plugin"),
2831
+ pluginId: z21.string(),
2832
+ provider: z21.string().min(1).refine((value) => !value.includes(":")),
2833
+ id: z21.string(),
2834
+ icon: z21.string().nullable().optional()
1055
2835
  })
1056
2836
  ]);
1057
2837
  var attachmentFields = {
1058
- type: z4.enum(["localImage", "localFile"]),
1059
- path: z4.string().min(1),
1060
- name: z4.string(),
1061
- mimeType: z4.string().optional(),
1062
- sizeBytes: z4.number().nonnegative().optional()
2838
+ type: z21.enum(["localImage", "localFile"]),
2839
+ path: z21.string().min(1),
2840
+ name: z21.string(),
2841
+ mimeType: z21.string().optional(),
2842
+ sizeBytes: z21.number().nonnegative().optional()
1063
2843
  };
1064
- var attachmentsSchema = z4.array(
1065
- z4.union([
1066
- z4.object({
2844
+ var attachmentsSchema = z21.array(
2845
+ z21.union([
2846
+ z21.object({
1067
2847
  ...attachmentFields,
1068
- hostId: z4.string().min(1),
1069
- sourceProjectId: z4.undefined().optional()
2848
+ hostId: z21.string().min(1),
2849
+ sourceProjectId: z21.undefined().optional()
1070
2850
  }),
1071
- z4.object({
2851
+ z21.object({
1072
2852
  ...attachmentFields,
1073
- sourceProjectId: z4.string().min(1).optional(),
1074
- hostId: z4.undefined().optional()
2853
+ sourceProjectId: z21.string().min(1).optional(),
2854
+ hostId: z21.undefined().optional()
1075
2855
  })
1076
2856
  ])
1077
2857
  );
1078
- var replacementSchema = z4.object({
1079
- text: z4.string(),
1080
- mentions: z4.array(mentionSchema),
2858
+ var replacementSchema = z21.object({
2859
+ text: z21.string(),
2860
+ mentions: z21.array(mentionSchema),
1081
2861
  attachments: attachmentsSchema.optional()
1082
2862
  }).superRefine((draft, context) => {
1083
2863
  let end = 0;
@@ -1314,30 +3094,29 @@ function createComposerHandleBinding(key, initial) {
1314
3094
  }
1315
3095
  target().setDraft(appendComposerDraft(target().getDraft(), value, block));
1316
3096
  };
1317
- const submit = async (options) => {
3097
+ const submit = async (options = {}) => {
1318
3098
  requireAvailable();
1319
- const hostSubmit = target().submit;
1320
- if (hostSubmit === void 0) {
1321
- throw new Error("This composer cannot submit programmatically.");
1322
- }
1323
3099
  if (options.sendAt !== void 0 && (!Number.isFinite(options.sendAt) || options.sendAt <= Date.now())) {
1324
3100
  throw new Error("Pick a time in the future.");
1325
3101
  }
1326
3102
  const errorBefore = editorState().attachmentError;
1327
- await waitForUploads(target());
3103
+ if (editorState().isAttaching) await waitForUploads(target());
1328
3104
  const state = editorState();
1329
3105
  if (state.attachmentError !== null && state.attachmentError !== errorBefore) {
1330
3106
  throw new Error(state.attachmentError);
1331
3107
  }
1332
- if (state.isSubmittingBlocked) {
1333
- throw new Error(
1334
- state.submittingBlockedReason ?? "This composer can't submit right now."
1335
- );
1336
- }
1337
- await hostSubmit(
1338
- options,
1339
- options.experimental_data === void 0 ? void 0 : { pluginId: controller.pluginId, data: options.experimental_data }
1340
- );
3108
+ const submission = target().editorSubmit({
3109
+ mode: options.experimental_mode ?? "enter",
3110
+ ...options.sendAt === void 0 ? {} : { sendAt: options.sendAt },
3111
+ ...options.experimental_data === void 0 ? {} : {
3112
+ pluginSubmission: {
3113
+ pluginId: controller.pluginId,
3114
+ data: options.experimental_data
3115
+ }
3116
+ }
3117
+ });
3118
+ if (submission === null) throw new Error(OFF_SCREEN_MESSAGE);
3119
+ await submission;
1341
3120
  };
1342
3121
  const setSelection = async (selection) => {
1343
3122
  requireAvailable();
@@ -1904,24 +3683,22 @@ var experimental_THREAD_ACTION_GROUPS = {
1904
3683
  lifecycle: "4_lifecycle"
1905
3684
  };
1906
3685
 
1907
- // src/internal/plugin-app-collector.ts
1908
- import { z as z5 } from "zod";
1909
- var CODE_FENCE_LANGUAGE_PATTERN = /^[a-z0-9][a-z0-9+#._-]*$/;
3686
+ // src/thread-info-groups.ts
3687
+ var experimental_THREAD_INFO_ROW_GROUPS = {
3688
+ thread: "1_thread",
3689
+ environment: "2_environment",
3690
+ git: "3_git",
3691
+ pullRequest: "4_pullRequest",
3692
+ lifecycle: "5_lifecycle"
3693
+ };
3694
+ var experimental_THREAD_INFO_SECTION_GROUPS = {
3695
+ related: "1_related",
3696
+ changes: "2_changes",
3697
+ storage: "3_storage"
3698
+ };
3699
+
3700
+ // src/internal/sidebar-footer-runtime.ts
1910
3701
  var sidebarFooterCommandSequence = 0;
1911
- var SIDEBAR_FOOTER_ACTION_KEYS = /* @__PURE__ */ new Set([
1912
- "id",
1913
- "label",
1914
- "icon",
1915
- "kind",
1916
- "onActivate"
1917
- ]);
1918
- var SIDEBAR_FOOTER_DISCLOSURE_KEYS = /* @__PURE__ */ new Set([
1919
- "id",
1920
- "label",
1921
- "icon",
1922
- "kind",
1923
- "component"
1924
- ]);
1925
3702
  var SidebarFooterItemRuntime = class {
1926
3703
  listeners = /* @__PURE__ */ new Set();
1927
3704
  snapshot = {
@@ -1967,6 +3744,25 @@ function adaptSidebarFooterAction(registration) {
1967
3744
  runtime: new SidebarFooterItemRuntime()
1968
3745
  };
1969
3746
  }
3747
+ var sidebarFooterItemsByRegistrationSet = /* @__PURE__ */ new WeakMap();
3748
+
3749
+ // src/internal/plugin-app-registration-collector.ts
3750
+ import { z as z22 } from "zod";
3751
+ var CODE_FENCE_LANGUAGE_PATTERN = /^[a-z0-9][a-z0-9+#._-]*$/;
3752
+ var SIDEBAR_FOOTER_ACTION_KEYS = /* @__PURE__ */ new Set([
3753
+ "id",
3754
+ "label",
3755
+ "icon",
3756
+ "kind",
3757
+ "onActivate"
3758
+ ]);
3759
+ var SIDEBAR_FOOTER_DISCLOSURE_KEYS = /* @__PURE__ */ new Set([
3760
+ "id",
3761
+ "label",
3762
+ "icon",
3763
+ "kind",
3764
+ "component"
3765
+ ]);
1970
3766
  var SidebarFooterCollector = class {
1971
3767
  constructor(collected, allCollected, seenIds) {
1972
3768
  this.collected = collected;
@@ -2028,20 +3824,18 @@ var SidebarFooterCollector = class {
2028
3824
  }
2029
3825
  }
2030
3826
  };
2031
- var NAV_PANEL_REGISTRATION_KEYS = new Set(
2032
- Object.keys({
2033
- id: true,
2034
- title: true,
2035
- icon: true,
2036
- path: true,
2037
- component: true,
2038
- fixedTabs: true,
2039
- experimental_useBadge: true,
2040
- experimental_usePageTitle: true,
2041
- experimental_sidebar: true,
2042
- headerContent: true
2043
- })
2044
- );
3827
+ var NAV_PANEL_REGISTRATION_KEYS = {
3828
+ id: true,
3829
+ title: true,
3830
+ icon: true,
3831
+ path: true,
3832
+ component: true,
3833
+ fixedTabs: true,
3834
+ experimental_useBadge: true,
3835
+ experimental_usePageTitle: true,
3836
+ experimental_sidebar: true,
3837
+ headerContent: true
3838
+ };
2045
3839
  var RENAMED_NAV_PANEL_KEYS = /* @__PURE__ */ new Map([
2046
3840
  ["experimental_fixedTabs", 'was renamed to "fixedTabs" in SDK 0.4.16']
2047
3841
  ]);
@@ -2053,7 +3847,7 @@ var RETIRED_NAV_PANEL_KEYS = /* @__PURE__ */ new Map([
2053
3847
  ]);
2054
3848
  function checkStaleNavPanelKeys(kind, registration, onWarning) {
2055
3849
  for (const key of Object.keys(registration)) {
2056
- if (NAV_PANEL_REGISTRATION_KEYS.has(key)) continue;
3850
+ if (Object.hasOwn(NAV_PANEL_REGISTRATION_KEYS, key)) continue;
2057
3851
  const renamed = RENAMED_NAV_PANEL_KEYS.get(key);
2058
3852
  if (renamed !== void 0) {
2059
3853
  throw new Error(`${kind}: "${key}" ${renamed}`);
@@ -2068,28 +3862,36 @@ function checkStaleNavPanelKeys(kind, registration, onWarning) {
2068
3862
  }
2069
3863
  }
2070
3864
  }
2071
- var commandShortcutSchema = z5.object({
2072
- key: z5.string().min(1).max(32).refine(
2073
- (key) => ![
2074
- "Alt",
2075
- "Control",
2076
- "Meta",
2077
- "OS",
2078
- "Shift",
2079
- "Dead",
2080
- "Unidentified"
2081
- ].includes(key)
2082
- ),
2083
- mod: z5.boolean().default(false),
2084
- meta: z5.boolean().default(false),
2085
- control: z5.boolean().default(false),
2086
- alt: z5.boolean().default(false),
2087
- shift: z5.boolean().default(false)
2088
- }).strict().refine(
2089
- (shortcut) => shortcut.mod || shortcut.meta || shortcut.control || shortcut.alt || /^F(?:[1-9]|1[0-9]|2[0-4])$/u.test(shortcut.key),
2090
- "Use Command, Control, or Alt with a key, or a function key"
2091
- );
2092
- var sidebarFooterItemsByRegistrationSet = /* @__PURE__ */ new WeakMap();
3865
+ function createCommandShortcutSchema() {
3866
+ return z22.object({
3867
+ key: z22.string().min(1).max(32).refine(
3868
+ (key) => ![
3869
+ "Alt",
3870
+ "Control",
3871
+ "Meta",
3872
+ "OS",
3873
+ "Shift",
3874
+ "Dead",
3875
+ "Unidentified"
3876
+ ].includes(key)
3877
+ ),
3878
+ mod: z22.boolean().default(false),
3879
+ meta: z22.boolean().default(false),
3880
+ control: z22.boolean().default(false),
3881
+ alt: z22.boolean().default(false),
3882
+ shift: z22.boolean().default(false)
3883
+ }).strict().refine(
3884
+ (shortcut) => shortcut.mod || shortcut.meta || shortcut.control || shortcut.alt || /^F(?:[1-9]|1[0-9]|2[0-4])$/u.test(shortcut.key),
3885
+ "Use Command, Control, or Alt with a key, or a function key"
3886
+ );
3887
+ }
3888
+ function requireOptionalOrder(kind, order2) {
3889
+ if (order2 === void 0) return {};
3890
+ if (!Number.isFinite(order2)) {
3891
+ throw new Error(`${kind}: "order" must be a finite number`);
3892
+ }
3893
+ return { order: order2 };
3894
+ }
2093
3895
  function collectTitledComponent(kind, seen, registration) {
2094
3896
  const id = requireSlotId(kind, registration?.id);
2095
3897
  requireUniqueId(kind, seen, id);
@@ -2124,13 +3926,19 @@ function collectPanelAction(kind, seen, registration) {
2124
3926
  };
2125
3927
  }
2126
3928
  function collectPluginAppRegistrations(definition, onWarning = (message) => console.warn(message)) {
3929
+ const commandShortcutSchema = createCommandShortcutSchema();
2127
3930
  const sidebarFooterItems = [];
2128
3931
  const collected = {
2129
3932
  homepageSections: [],
2130
3933
  settingsSections: [],
2131
3934
  appOverlays: [],
2132
3935
  navPanels: [],
2133
- threadPanelActions: [],
3936
+ tabs: [],
3937
+ get threadPanelActions() {
3938
+ return this.tabs.filter(
3939
+ (tab) => tab.context.kind === "thread" && tab.availability === "action"
3940
+ );
3941
+ },
2134
3942
  newThreadPanelActions: [],
2135
3943
  composerCustomizations: [],
2136
3944
  pendingInteractions: [],
@@ -2139,11 +3947,14 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
2139
3947
  threadLists: [],
2140
3948
  experimentalSidebarNavigations: [],
2141
3949
  threadHeaderActions: [],
3950
+ threadInfoRows: [],
3951
+ threadInfoSections: [],
2142
3952
  threadActions: [],
2143
3953
  browserToolbarActions: [],
2144
3954
  fileOpeners: [],
2145
3955
  sourceCodeRenderers: [],
2146
3956
  diffRenderers: [],
3957
+ composers: [],
2147
3958
  messageDirectives: [],
2148
3959
  codeFenceRenderers: [],
2149
3960
  messageActions: [],
@@ -2161,7 +3972,7 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
2161
3972
  settingsSection: /* @__PURE__ */ new Set(),
2162
3973
  appOverlay: /* @__PURE__ */ new Set(),
2163
3974
  navPanel: /* @__PURE__ */ new Set(),
2164
- threadPanelAction: /* @__PURE__ */ new Set(),
3975
+ tab: /* @__PURE__ */ new Set(),
2165
3976
  newThreadPanelAction: /* @__PURE__ */ new Set(),
2166
3977
  composerCustomization: /* @__PURE__ */ new Set(),
2167
3978
  composerPopup: /* @__PURE__ */ new Set(),
@@ -2171,11 +3982,14 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
2171
3982
  sidebarNavigation: /* @__PURE__ */ new Set(),
2172
3983
  sidebarHeader: /* @__PURE__ */ new Set(),
2173
3984
  threadHeaderAction: /* @__PURE__ */ new Set(),
3985
+ threadInfoRow: /* @__PURE__ */ new Set(),
3986
+ threadInfoSection: /* @__PURE__ */ new Set(),
2174
3987
  threadAction: /* @__PURE__ */ new Set(),
2175
3988
  browserToolbarAction: /* @__PURE__ */ new Set(),
2176
3989
  fileOpener: /* @__PURE__ */ new Set(),
2177
3990
  sourceCodeRenderer: /* @__PURE__ */ new Set(),
2178
3991
  diffRenderer: /* @__PURE__ */ new Set(),
3992
+ composer: /* @__PURE__ */ new Set(),
2179
3993
  messageDirective: /* @__PURE__ */ new Set(),
2180
3994
  codeFenceRenderer: /* @__PURE__ */ new Set(),
2181
3995
  codeFenceLanguage: /* @__PURE__ */ new Set(),
@@ -2187,6 +4001,54 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
2187
4001
  machineProviderInputs: /* @__PURE__ */ new Set(),
2188
4002
  contentScript: /* @__PURE__ */ new Set()
2189
4003
  };
4004
+ function collectTab(value, legacy = false) {
4005
+ const registration = value;
4006
+ const kind = "slots.experimental_tab";
4007
+ const id = requireSlotId(kind, registration?.id);
4008
+ const context = registration.context;
4009
+ if (context?.kind !== "thread" && context?.kind !== "nav-panel") {
4010
+ throw new Error(`${kind}: context must be thread or nav-panel`);
4011
+ }
4012
+ if (context.kind === "nav-panel") requireSlotId(kind, context.panelId);
4013
+ const availability = registration.availability;
4014
+ if (availability !== "fixed" && availability !== "action") {
4015
+ throw new Error(`${kind}: availability must be fixed or action`);
4016
+ }
4017
+ requireUniqueId(
4018
+ kind,
4019
+ seenIds.tab,
4020
+ `${context.kind}/${context.kind === "nav-panel" ? context.panelId : ""}/${id}`
4021
+ );
4022
+ if (registration.useVisible !== void 0 && typeof registration.useVisible !== "function") {
4023
+ throw new Error(`${kind}: useVisible must be a function`);
4024
+ }
4025
+ if (availability === "fixed" && (registration.run !== void 0 || registration.params !== void 0)) {
4026
+ throw new Error(`${kind}: run and params require action availability`);
4027
+ }
4028
+ const target = registration.experimental_target;
4029
+ if (target !== void 0 && (context.kind !== "nav-panel" || availability !== "fixed" || typeof target?.validate !== "function")) {
4030
+ throw new Error(
4031
+ `${kind}: experimental_target requires a nav-panel fixed tab and a validate function`
4032
+ );
4033
+ }
4034
+ const validated = {
4035
+ ...registration,
4036
+ ...collectPanelAction(kind, /* @__PURE__ */ new Set(), {
4037
+ ...registration,
4038
+ icon: legacy && registration.icon === "" ? void 0 : registration.icon
4039
+ }),
4040
+ icon: legacy && registration.icon === "" ? "" : requireNonEmptyString(kind, "icon", registration.icon),
4041
+ ...registration.tooltip === void 0 ? {} : {
4042
+ tooltip: requireNonEmptyString(
4043
+ kind,
4044
+ "tooltip",
4045
+ registration.tooltip
4046
+ )
4047
+ },
4048
+ ...availability === "action" && registration.params !== void 0 ? { params: z22.json().parse(registration.params) } : {}
4049
+ };
4050
+ collected.tabs.push(validated);
4051
+ }
2190
4052
  function collectCommand(kind, registration) {
2191
4053
  const id = requireSlotId(kind, registration?.id);
2192
4054
  requireUniqueId(kind, seenIds.command, id);
@@ -2221,6 +4083,26 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
2221
4083
  }
2222
4084
  const legacySidebarHeaders = [];
2223
4085
  const legacySlotAliases = {
4086
+ threadPanelAction(registration) {
4087
+ try {
4088
+ const action = collectPanelAction(
4089
+ "slots.threadPanelAction",
4090
+ /* @__PURE__ */ new Set(),
4091
+ registration
4092
+ );
4093
+ collectTab(
4094
+ {
4095
+ ...action,
4096
+ icon: action.icon ?? "",
4097
+ context: { kind: "thread" },
4098
+ availability: "action"
4099
+ },
4100
+ true
4101
+ );
4102
+ } catch (error) {
4103
+ onWarning(`Legacy threadPanelAction ignored: ${String(error)}`);
4104
+ }
4105
+ },
2224
4106
  experimental_sidebarHeader(registration) {
2225
4107
  legacySidebarHeaders.push(
2226
4108
  collectTitledComponent(
@@ -2308,63 +4190,45 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
2308
4190
  `${kind}: "experimental_usePageTitle" must be a React hook function when set`
2309
4191
  );
2310
4192
  }
2311
- const fixedTabs = (() => {
2312
- if (registration.fixedTabs === void 0) return [];
2313
- if (!Array.isArray(registration.fixedTabs)) {
2314
- throw new Error(`${kind}: "fixedTabs" must be an array when set`);
2315
- }
2316
- const seenFixedTabIds = /* @__PURE__ */ new Set();
2317
- return registration.fixedTabs.map((value, index) => {
2318
- const fixedTabKind = `${kind}.fixedTabs[${index}]`;
2319
- const fixedTab = value;
2320
- const id2 = requireSlotId(fixedTabKind, fixedTab?.id);
2321
- requireUniqueId(fixedTabKind, seenFixedTabIds, id2);
2322
- const layout = fixedTab?.layout;
2323
- if (layout !== void 0 && layout !== "padded" && layout !== "flush") {
2324
- throw new Error(
2325
- `${fixedTabKind}: "layout" must be "padded" or "flush" when set`
2326
- );
2327
- }
2328
- const fixedTabPanelId = requireNonEmptyString(
2329
- fixedTabKind,
2330
- "panelId",
2331
- fixedTab?.panelId
2332
- );
2333
- if (fixedTabPanelId !== panelId) {
2334
- throw new Error(
2335
- `${fixedTabKind}: "panelId" must match its containing navPanel id ${JSON.stringify(panelId)}`
2336
- );
2337
- }
2338
- const experimentalTarget = fixedTab?.experimental_target;
2339
- if (experimentalTarget !== void 0 && (typeof experimentalTarget !== "object" || experimentalTarget === null || typeof Reflect.get(experimentalTarget, "validate") !== "function")) {
2340
- throw new Error(
2341
- `${fixedTabKind}: "experimental_target.validate" must be a function when set`
2342
- );
2343
- }
2344
- return {
4193
+ const legacy = registration;
4194
+ const fixedTabs = [];
4195
+ if (legacy.fixedTabs !== void 0 && !Array.isArray(legacy.fixedTabs)) {
4196
+ onWarning("Legacy navPanel.fixedTabs ignored: expected an array");
4197
+ }
4198
+ for (const value of Array.isArray(legacy.fixedTabs) ? legacy.fixedTabs : []) {
4199
+ try {
4200
+ const id2 = requireSlotId(kind, value?.id);
4201
+ const tab = {
2345
4202
  id: id2,
2346
- panelId: fixedTabPanelId,
2347
- title: requireNonEmptyString(
2348
- fixedTabKind,
2349
- "title",
2350
- fixedTab?.title
2351
- ),
2352
- icon: requireNonEmptyString(fixedTabKind, "icon", fixedTab?.icon),
2353
- component: requireComponent(fixedTabKind, fixedTab?.component),
2354
- ...layout === void 0 ? {} : { layout },
2355
- ...experimentalTarget === void 0 ? {} : {
2356
- experimental_target: experimentalTarget
2357
- }
4203
+ panelId,
4204
+ title: requireNonEmptyString(kind, "title", value.title ?? id2),
4205
+ icon: typeof value.icon === "string" ? value.icon : "",
4206
+ component: requireComponent(kind, value.component),
4207
+ ...value.layout === "flush" ? { layout: "flush" } : {},
4208
+ ...typeof value.experimental_target?.validate === "function" ? { experimental_target: value.experimental_target } : {}
2358
4209
  };
2359
- });
2360
- })();
4210
+ collectTab(
4211
+ {
4212
+ ...tab,
4213
+ context: { kind: "nav-panel", panelId },
4214
+ availability: "fixed"
4215
+ },
4216
+ true
4217
+ );
4218
+ fixedTabs.push(tab);
4219
+ } catch (error) {
4220
+ onWarning(
4221
+ `Legacy navPanel.fixedTabs entry ignored: ${String(error)}`
4222
+ );
4223
+ }
4224
+ }
2361
4225
  collected.navPanels.push({
2362
4226
  id,
2363
4227
  title: requireNonEmptyString(kind, "title", registration.title),
2364
4228
  icon: requireNonEmptyString(kind, "icon", registration.icon),
2365
4229
  path,
4230
+ ...fixedTabs.length === 0 ? {} : { fixedTabs },
2366
4231
  component: requireComponent(kind, registration.component),
2367
- ...fixedTabs.length > 0 ? { fixedTabs } : {},
2368
4232
  ...registration.experimental_useBadge !== void 0 ? {
2369
4233
  experimental_useBadge: registration.experimental_useBadge
2370
4234
  } : {},
@@ -2375,14 +4239,8 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
2375
4239
  ...registration.headerContent !== void 0 ? { headerContent: registration.headerContent } : {}
2376
4240
  });
2377
4241
  },
2378
- threadPanelAction(registration) {
2379
- collected.threadPanelActions.push(
2380
- collectPanelAction(
2381
- "slots.threadPanelAction",
2382
- seenIds.threadPanelAction,
2383
- registration
2384
- )
2385
- );
4242
+ experimental_tab(registration) {
4243
+ collectTab(registration);
2386
4244
  },
2387
4245
  experimental_newThreadPanelAction(registration) {
2388
4246
  collected.newThreadPanelActions.push(
@@ -2460,6 +4318,28 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
2460
4318
  component: requireComponent(kind, registration.component)
2461
4319
  });
2462
4320
  },
4321
+ experimental_threadInfoRow(registration) {
4322
+ const kind = "slots.experimental_threadInfoRow";
4323
+ const id = requireSlotId(kind, registration?.id);
4324
+ requireUniqueId(kind, seenIds.threadInfoRow, id);
4325
+ collected.threadInfoRows.push({
4326
+ id,
4327
+ group: requireNonEmptyString(kind, "group", registration.group),
4328
+ ...requireOptionalOrder(kind, registration.order),
4329
+ component: requireComponent(kind, registration.component)
4330
+ });
4331
+ },
4332
+ experimental_threadInfoSection(registration) {
4333
+ const kind = "slots.experimental_threadInfoSection";
4334
+ const id = requireSlotId(kind, registration?.id);
4335
+ requireUniqueId(kind, seenIds.threadInfoSection, id);
4336
+ collected.threadInfoSections.push({
4337
+ id,
4338
+ group: requireNonEmptyString(kind, "group", registration.group),
4339
+ ...requireOptionalOrder(kind, registration.order),
4340
+ component: requireComponent(kind, registration.component)
4341
+ });
4342
+ },
2463
4343
  experimental_threadAction(registration) {
2464
4344
  const kind = "slots.experimental_threadAction";
2465
4345
  const id = requireSlotId(kind, registration?.id);
@@ -2470,15 +4350,12 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
2470
4350
  if (registration.useData !== void 0 && typeof registration.useData !== "function") {
2471
4351
  throw new Error(`${kind}: "useData" must be a function`);
2472
4352
  }
2473
- if (registration.order !== void 0 && !Number.isFinite(registration.order)) {
2474
- throw new Error(`${kind}: "order" must be a finite number`);
2475
- }
2476
4353
  collected.threadActions.push({
2477
4354
  id,
2478
4355
  title: requireNonEmptyString(kind, "title", registration.title),
2479
4356
  icon: requireNonEmptyString(kind, "icon", registration.icon),
2480
4357
  group: requireNonEmptyString(kind, "group", registration.group),
2481
- ...registration.order !== void 0 ? { order: registration.order } : {},
4358
+ ...requireOptionalOrder(kind, registration.order),
2482
4359
  ...registration.useData !== void 0 ? { useData: registration.useData } : {},
2483
4360
  item: registration.item
2484
4361
  });
@@ -2536,6 +4413,15 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
2536
4413
  )
2537
4414
  );
2538
4415
  },
4416
+ experimental_composer(registration) {
4417
+ collected.composers.push(
4418
+ collectTitledComponent(
4419
+ "slots.experimental_composer",
4420
+ seenIds.composer,
4421
+ registration
4422
+ )
4423
+ );
4424
+ },
2539
4425
  messageDirective(registration) {
2540
4426
  const kind = "slots.messageDirective";
2541
4427
  const id = requireMessageDirectiveId(kind, registration?.id);
@@ -2729,7 +4615,7 @@ function attachLegacySidebarHeaders(navigations, headers, onWarning) {
2729
4615
  }
2730
4616
 
2731
4617
  // src/testing/app.tsx
2732
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4618
+ import { Fragment as Fragment2, jsx, jsxs } from "react/jsx-runtime";
2733
4619
  function TestSidebarNavigationIcon({
2734
4620
  icon,
2735
4621
  className
@@ -3357,6 +5243,106 @@ function TestPermissionModePicker({
3357
5243
  }
3358
5244
  );
3359
5245
  }
5246
+ function TestComposerRoot(_props) {
5247
+ return null;
5248
+ }
5249
+ function TestComposerPluginActions() {
5250
+ return null;
5251
+ }
5252
+ function TestComposerPluginPopup({
5253
+ contribution
5254
+ }) {
5255
+ return /* @__PURE__ */ jsx(contribution.popup.component, {});
5256
+ }
5257
+ function TestComposerMenuEntry({
5258
+ contribution
5259
+ }) {
5260
+ return /* @__PURE__ */ jsx("div", { role: "menuitem", children: contribution.item.label });
5261
+ }
5262
+ var IDLE_COMPOSER_MENTION_SEARCH = {
5263
+ status: "idle",
5264
+ refreshing: false,
5265
+ groups: [],
5266
+ search: () => {
5267
+ }
5268
+ };
5269
+ var IDLE_COMPOSER_COMMAND_SEARCH = {
5270
+ status: "idle",
5271
+ refreshing: false,
5272
+ groups: [],
5273
+ search: () => {
5274
+ }
5275
+ };
5276
+ var TEST_COMPOSER_CONTRIBUTIONS = {
5277
+ popups: [],
5278
+ plusMenuItems: [],
5279
+ sendMenuItems: [],
5280
+ Actions: TestComposerPluginActions,
5281
+ Popup: TestComposerPluginPopup,
5282
+ MenuEntry: TestComposerMenuEntry
5283
+ };
5284
+ function TestVoiceInputButton({
5285
+ warning: _warning,
5286
+ variant: _variant,
5287
+ size: _size,
5288
+ ...props
5289
+ }) {
5290
+ return /* @__PURE__ */ jsx("button", { ...props });
5291
+ }
5292
+ function TestVoiceRecordingBar({
5293
+ state,
5294
+ onConfirm,
5295
+ onCancel
5296
+ }) {
5297
+ return /* @__PURE__ */ jsxs("div", { "data-voice-recording-state": state, children: [
5298
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: onConfirm, children: "Finish voice input" }),
5299
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: onCancel, children: "Cancel voice input" })
5300
+ ] });
5301
+ }
5302
+ function TestFailedVoiceRecordings({
5303
+ recordings,
5304
+ className
5305
+ }) {
5306
+ return /* @__PURE__ */ jsx("ul", { className, children: recordings.map((recording) => /* @__PURE__ */ jsx("li", { children: recording.errorMessage }, recording.id)) });
5307
+ }
5308
+ function TestShortcutHint({
5309
+ shortcut,
5310
+ className
5311
+ }) {
5312
+ return shortcut === null ? null : /* @__PURE__ */ jsx("kbd", { className, children: shortcut.label });
5313
+ }
5314
+ function TestImageLightbox({
5315
+ imageSrc,
5316
+ imageAlt,
5317
+ isOpen
5318
+ }) {
5319
+ const visible = isOpen ?? imageSrc !== null;
5320
+ return visible && imageSrc !== null ? /* @__PURE__ */ jsx("img", { alt: imageAlt, src: imageSrc }) : null;
5321
+ }
5322
+ function TestPromptMentionIcon({
5323
+ className
5324
+ }) {
5325
+ return /* @__PURE__ */ jsx("span", { className, "aria-hidden": true });
5326
+ }
5327
+ var TEST_PROMPT_MENTION_ATTRIBUTE = "data-test-prompt-mention";
5328
+ function testPromptMentionClipboardAttributes(mention, text) {
5329
+ return { [TEST_PROMPT_MENTION_ATTRIBUTE]: JSON.stringify({ mention, text }) };
5330
+ }
5331
+ function readTestPromptMentionClipboard(element) {
5332
+ const value = element.getAttribute(TEST_PROMPT_MENTION_ATTRIBUTE);
5333
+ if (value === null) return null;
5334
+ const pill = JSON.parse(value);
5335
+ return pill;
5336
+ }
5337
+ function TestPluginIcon({ className }) {
5338
+ return /* @__PURE__ */ jsx("span", { className, "aria-hidden": true });
5339
+ }
5340
+ function TestThreadTitleText({
5341
+ title,
5342
+ className
5343
+ }) {
5344
+ return /* @__PURE__ */ jsx("span", { className, children: title });
5345
+ }
3360
5346
  function TestVoiceInputTextarea({
3361
5347
  onValueChange,
3362
5348
  onVoiceInputActiveChange: _onVoiceInputActiveChange,
@@ -3412,6 +5398,52 @@ function TestDiff({
3412
5398
  }
3413
5399
  );
3414
5400
  }
5401
+ function TestInfoSection({
5402
+ label,
5403
+ count,
5404
+ accessory,
5405
+ trailing,
5406
+ children
5407
+ }) {
5408
+ return /* @__PURE__ */ jsxs("section", { "aria-label": label, "data-testid": "bb-info-section", children: [
5409
+ /* @__PURE__ */ jsxs("h3", { children: [
5410
+ label,
5411
+ count === void 0 ? null : /* @__PURE__ */ jsx("span", { children: count })
5412
+ ] }),
5413
+ accessory,
5414
+ trailing,
5415
+ children
5416
+ ] });
5417
+ }
5418
+ function TestDetailRow({ label, icon, children }) {
5419
+ return /* @__PURE__ */ jsxs("div", { "data-testid": "bb-detail-row", "data-icon": icon, children: [
5420
+ /* @__PURE__ */ jsx("dt", { children: label }),
5421
+ /* @__PURE__ */ jsx("dd", { children })
5422
+ ] });
5423
+ }
5424
+ function TestInfoList({
5425
+ items,
5426
+ getKey,
5427
+ renderItem,
5428
+ limit
5429
+ }) {
5430
+ return /* @__PURE__ */ jsx("ul", { "data-limit": limit, children: items.map((item) => /* @__PURE__ */ jsx(Fragment, { children: renderItem(item) }, getKey(item))) });
5431
+ }
5432
+ function TestInfoListRow({
5433
+ leading,
5434
+ name,
5435
+ title,
5436
+ context,
5437
+ trailing,
5438
+ onSelect
5439
+ }) {
5440
+ return /* @__PURE__ */ jsxs("li", { children: [
5441
+ leading,
5442
+ onSelect === void 0 ? /* @__PURE__ */ jsx("span", { title, children: name }) : /* @__PURE__ */ jsx("button", { type: "button", title, onClick: onSelect, children: name }),
5443
+ context === void 0 ? null : /* @__PURE__ */ jsx("span", { children: context }),
5444
+ trailing
5445
+ ] });
5446
+ }
3415
5447
  var activeClipboard = null;
3416
5448
  function captureClipboardWrites(result) {
3417
5449
  const writes = [];
@@ -3481,7 +5513,7 @@ var testPluginSdkApp = {
3481
5513
  store.getSnapshot,
3482
5514
  store.getSnapshot
3483
5515
  );
3484
- if (state === null || state.panelId !== tab.panelId || state.tabId !== tab.id || tab.experimental_target === void 0) {
5516
+ if (state === null || state.panelId !== ("context" in tab ? tab.context.panelId : tab.panelId) || state.tabId !== tab.id || tab.experimental_target === void 0) {
3485
5517
  return null;
3486
5518
  }
3487
5519
  try {
@@ -3537,6 +5569,27 @@ var testPluginSdkApp = {
3537
5569
  UrlLink: TestUrlLink,
3538
5570
  experimental_NewThreadComposer: TestNewThreadComposer,
3539
5571
  experimental_VoiceInputTextarea: TestVoiceInputTextarea,
5572
+ experimental_ComposerRoot: TestComposerRoot,
5573
+ experimental_VoiceInputButton: TestVoiceInputButton,
5574
+ experimental_VoiceRecordingBar: TestVoiceRecordingBar,
5575
+ experimental_FailedVoiceRecordings: TestFailedVoiceRecordings,
5576
+ experimental_ShortcutHint: TestShortcutHint,
5577
+ experimental_ImageLightbox: TestImageLightbox,
5578
+ experimental_PromptMentionIcon: TestPromptMentionIcon,
5579
+ experimental_describePromptMention(mention) {
5580
+ return {
5581
+ className: "prompt-mention-pill",
5582
+ title: mention.label,
5583
+ text: `${mention.kind}: ${mention.label}`
5584
+ };
5585
+ },
5586
+ experimental_promptMentionClipboardAttributes: testPromptMentionClipboardAttributes,
5587
+ experimental_readPromptMentionClipboard: readTestPromptMentionClipboard,
5588
+ experimental_PluginIcon: TestPluginIcon,
5589
+ experimental_ThreadTitleText: TestThreadTitleText,
5590
+ experimental_useThreadTitleDisplayText(title) {
5591
+ return title;
5592
+ },
3540
5593
  experimental_ProviderModelPicker: TestProviderModelPicker,
3541
5594
  experimental_PermissionModePicker: TestPermissionModePicker,
3542
5595
  experimental_BranchPicker: TestBranchPicker,
@@ -3548,6 +5601,10 @@ var testPluginSdkApp = {
3548
5601
  },
3549
5602
  experimental_SourceCode: TestSourceCode,
3550
5603
  experimental_Diff: TestDiff,
5604
+ experimental_InfoSection: TestInfoSection,
5605
+ experimental_DetailRow: TestDetailRow,
5606
+ experimental_InfoList: TestInfoList,
5607
+ experimental_InfoListRow: TestInfoListRow,
3551
5608
  experimental_useSidebarThreads() {
3552
5609
  return useSlotEnv("experimental_useSidebarThreads").sidebarThreads;
3553
5610
  },
@@ -3591,14 +5648,14 @@ var testPluginSdkApp = {
3591
5648
  experimental_ThreadActionsContextMenu: TestThreadActionsContextMenu,
3592
5649
  experimental_PluginRpcCallError,
3593
5650
  experimental_THREAD_ACTION_GROUPS,
5651
+ experimental_THREAD_INFO_ROW_GROUPS,
5652
+ experimental_THREAD_INFO_SECTION_GROUPS,
3594
5653
  experimental_useSidebarNavigation() {
3595
5654
  return useSlotEnv("experimental_useSidebarNavigation").sidebarNavigation;
3596
5655
  },
3597
5656
  experimental_useSidebarNavigationSplit(itemId, _options) {
3598
5657
  const env = useSlotEnv("experimental_useSidebarNavigationSplit");
3599
- const kind = env.sidebarNavigation.items.find(
3600
- (item) => item.id === itemId
3601
- )?.action.kind;
5658
+ const kind = env.sidebarNavigation.items.find((item) => item.id === itemId)?.action.kind;
3602
5659
  const isAvailable = kind === "new-thread" || kind === "open-plugin-panel";
3603
5660
  return useMemo3(
3604
5661
  () => ({
@@ -3664,15 +5721,30 @@ var testPluginSdkApp = {
3664
5721
  useSdk() {
3665
5722
  return useSlotEnv("useSdk").sdk;
3666
5723
  },
3667
- experimental_useSidebarThreadPullRequest(threadId) {
3668
- const env = useSlotEnv("experimental_useSidebarThreadPullRequest");
3669
- return useMemo3(
3670
- () => ({
3671
- isLoading: false,
3672
- pullRequest: env.sidebarPullRequests.get(threadId) ?? null
3673
- }),
3674
- [env, threadId]
3675
- );
5724
+ experimental_useComposerRenderer() {
5725
+ const renderer = useSlotEnv(
5726
+ "experimental_useComposerRenderer"
5727
+ ).composerRenderer;
5728
+ if (renderer === null) {
5729
+ throw new Error(
5730
+ "experimental_useComposerRenderer() is only available inside an experimental_composer component; pass composerRenderer to mount it as one."
5731
+ );
5732
+ }
5733
+ return renderer;
5734
+ },
5735
+ experimental_useComposerContributions() {
5736
+ if (useSlotEnv("experimental_useComposerContributions").composerRenderer === null) {
5737
+ throw new Error(
5738
+ "experimental_useComposerContributions() is only available inside an experimental_composer component; pass composerRenderer to mount it as one."
5739
+ );
5740
+ }
5741
+ return TEST_COMPOSER_CONTRIBUTIONS;
5742
+ },
5743
+ experimental_useComposerMentionSearch() {
5744
+ return IDLE_COMPOSER_MENTION_SEARCH;
5745
+ },
5746
+ experimental_useComposerCommandSearch() {
5747
+ return IDLE_COMPOSER_COMMAND_SEARCH;
3676
5748
  },
3677
5749
  useComposerView() {
3678
5750
  const composer = useSlotEnv("useComposerView").composer;
@@ -3864,8 +5936,10 @@ function renderSlot(registration, props, options = {}) {
3864
5936
  });
3865
5937
  return parsed.value;
3866
5938
  };
3867
- const queryClient = new QueryClient();
3868
- const callRpc = async (method, input) => {
5939
+ const queryClient = new QueryClient({
5940
+ defaultOptions: { queries: { retry: false } }
5941
+ });
5942
+ const callRpc2 = async (method, input) => {
3869
5943
  const normalizedInput = input === void 0 ? null : strictJsonRoundTrip(input, `rpc "${method}" input`);
3870
5944
  rpcCalls.push({ method, input: normalizedInput });
3871
5945
  const handler = rpcHandlers[method];
@@ -3884,18 +5958,10 @@ function renderSlot(registration, props, options = {}) {
3884
5958
  throw experimental_PluginRpcCallError.from(error, "handler_error");
3885
5959
  }
3886
5960
  const parsedOutput = declaration ? await parseRpcValue(declaration.output, result2, "invalid_output") : result2;
3887
- const envelope = rpcResponseTags(
3888
- declaration ?? {},
3889
- parsedInput,
3890
- parsedOutput
3891
- );
3892
- return {
3893
- result: strictJsonRoundTrip(parsedOutput, `rpc "${method}" result`),
3894
- ...envelope
3895
- };
5961
+ return strictJsonRoundTrip(parsedOutput, `rpc "${method}" result`);
3896
5962
  };
3897
5963
  const rpcClient = {
3898
- call: async (method, input) => (await callRpc(method, input)).result
5964
+ call: (method, input) => callRpc2(method, input)
3899
5965
  };
3900
5966
  const realtimeHandlers = /* @__PURE__ */ new Map();
3901
5967
  let realtimeConnectionState = options.realtimeConnectionState ?? "connected";
@@ -3914,6 +5980,7 @@ function renderSlot(registration, props, options = {}) {
3914
5980
  };
3915
5981
  const navigateCalls = [];
3916
5982
  const experimental_fixedTabOpenCalls = [];
5983
+ const experimental_tabOpenCalls = [];
3917
5984
  let fixedTabTargetSnapshot = options.experimental_fixedTabTarget === void 0 ? null : {
3918
5985
  panelId: options.experimental_fixedTabTarget.panelId,
3919
5986
  sequence: 1,
@@ -3936,7 +6003,55 @@ function renderSlot(registration, props, options = {}) {
3936
6003
  for (const listener of fixedTabTargetListeners) listener();
3937
6004
  }
3938
6005
  };
6006
+ function captureFixedTabOpen(surface, panelId, tabId, target) {
6007
+ const call = {
6008
+ surface,
6009
+ ...panelId === void 0 ? {} : { panelId },
6010
+ tabId,
6011
+ ...target === void 0 ? {} : { target }
6012
+ };
6013
+ experimental_fixedTabOpenCalls.push(call);
6014
+ const accepted = options.experimental_openFixedTab?.(call) ?? false;
6015
+ if (accepted && target !== void 0 && panelId !== void 0) {
6016
+ fixedTabTargetSnapshot = {
6017
+ panelId,
6018
+ sequence: (fixedTabTargetSnapshot?.sequence ?? 0) + 1,
6019
+ tabId,
6020
+ target
6021
+ };
6022
+ for (const listener of fixedTabTargetListeners) listener();
6023
+ }
6024
+ return accepted;
6025
+ }
3939
6026
  const appPanel = {
6027
+ experimental_openTab(tabOptions) {
6028
+ experimental_tabOpenCalls.push(tabOptions);
6029
+ if (options.experimental_openTab !== void 0)
6030
+ return options.experimental_openTab(tabOptions);
6031
+ if (tabOptions.tab.availability === "action") {
6032
+ try {
6033
+ const params = tabOptions.params === void 0 ? void 0 : strictJsonRoundTrip(tabOptions.params, "tab params");
6034
+ return navigate.openThreadPanel({
6035
+ actionId: tabOptions.tab.id,
6036
+ ...tabOptions.title === void 0 ? {} : { title: tabOptions.title },
6037
+ ...params === void 0 ? {} : { params }
6038
+ });
6039
+ } catch {
6040
+ return false;
6041
+ }
6042
+ }
6043
+ try {
6044
+ const target = tabOptions.target === void 0 ? void 0 : strictJsonRoundTrip(tabOptions.target, "tab target");
6045
+ return captureFixedTabOpen(
6046
+ tabOptions.surface,
6047
+ tabOptions.tab.context.kind === "nav-panel" ? tabOptions.tab.context.panelId : void 0,
6048
+ tabOptions.tab.id,
6049
+ target
6050
+ );
6051
+ } catch {
6052
+ return false;
6053
+ }
6054
+ },
3940
6055
  openFixedTab(panelOptions) {
3941
6056
  let target;
3942
6057
  if (panelOptions.target !== void 0) {
@@ -3957,24 +6072,26 @@ function renderSlot(registration, props, options = {}) {
3957
6072
  return false;
3958
6073
  }
3959
6074
  }
3960
- const call = {
6075
+ if (panelOptions.tab.panelId === void 0) {
6076
+ if (target !== void 0) return false;
6077
+ return appPanel.experimental_openTab({
6078
+ surface: panelOptions.surface,
6079
+ tab: {
6080
+ id: panelOptions.tab.id,
6081
+ context: { kind: "thread" },
6082
+ availability: "fixed"
6083
+ }
6084
+ });
6085
+ }
6086
+ return appPanel.experimental_openTab({
3961
6087
  surface: panelOptions.surface,
3962
- panelId: panelOptions.tab.panelId,
3963
- tabId: panelOptions.tab.id,
6088
+ tab: {
6089
+ id: panelOptions.tab.id,
6090
+ context: { kind: "nav-panel", panelId: panelOptions.tab.panelId },
6091
+ availability: "fixed"
6092
+ },
3964
6093
  ...target === void 0 ? {} : { target }
3965
- };
3966
- experimental_fixedTabOpenCalls.push(call);
3967
- const accepted = options.experimental_openFixedTab?.(call) ?? false;
3968
- if (accepted && target !== void 0) {
3969
- fixedTabTargetSnapshot = {
3970
- panelId: panelOptions.tab.panelId,
3971
- sequence: (fixedTabTargetSnapshot?.sequence ?? 0) + 1,
3972
- tabId: panelOptions.tab.id,
3973
- target
3974
- };
3975
- for (const listener of fixedTabTargetListeners) listener();
3976
- }
3977
- return accepted;
6094
+ });
3978
6095
  }
3979
6096
  };
3980
6097
  const sidebarActionCalls = [];
@@ -4023,9 +6140,6 @@ function renderSlot(registration, props, options = {}) {
4023
6140
  }
4024
6141
  };
4025
6142
  const environmentArchiveCalls = [];
4026
- const sidebarPullRequests = new Map(
4027
- Object.entries(options.sidebarPullRequests ?? {})
4028
- );
4029
6143
  const sidebarDraftThreadIds = new Set(
4030
6144
  options.sidebarDraftThreadIds ?? []
4031
6145
  );
@@ -4286,6 +6400,17 @@ ${block}
4286
6400
  },
4287
6401
  subscribeEditorState: () => () => {
4288
6402
  },
6403
+ async editorSubmit({ mode, sendAt, pluginSubmission }) {
6404
+ const reason = composerBlockedReason();
6405
+ if (reason !== null) throw new Error(reason);
6406
+ composerLog.submits.push({
6407
+ ...mode === "enter" ? {} : { experimental_mode: mode },
6408
+ ...sendAt === void 0 ? {} : { sendAt },
6409
+ ...pluginSubmission === void 0 ? {} : { experimental_data: pluginSubmission.data }
6410
+ });
6411
+ commitComposerDraft("", []);
6412
+ for (const listener of submissionListeners) listener();
6413
+ },
4289
6414
  insertAtCursor(value, block) {
4290
6415
  composerTarget.setDraft(
4291
6416
  appendComposerDraft(composerDraft(), value, block)
@@ -4296,11 +6421,6 @@ ${block}
4296
6421
  focus() {
4297
6422
  composerLog.focusCount += 1;
4298
6423
  },
4299
- async submit(submitOptions) {
4300
- composerLog.submits.push(submitOptions);
4301
- commitComposerDraft("", []);
4302
- for (const listener of submissionListeners) listener();
4303
- },
4304
6424
  async setSelection(selection) {
4305
6425
  if (composerScope.kind === "queued-message") {
4306
6426
  throw new Error("This composer has no pickers to set.");
@@ -4389,7 +6509,7 @@ ${block}
4389
6509
  queryClient,
4390
6510
  subscribe: () => () => {
4391
6511
  },
4392
- call: (_pluginId, method, input) => callRpc(method, input)
6512
+ call: (_pluginId, method, input) => callRpc2(method, input)
4393
6513
  };
4394
6514
  const env = {
4395
6515
  rpcQueryHost,
@@ -4409,6 +6529,7 @@ ${block}
4409
6529
  navigateCalls,
4410
6530
  appPanel,
4411
6531
  experimental_fixedTabOpenCalls,
6532
+ experimental_tabOpenCalls,
4412
6533
  fixedTabTarget,
4413
6534
  composer,
4414
6535
  composerLog,
@@ -4420,11 +6541,11 @@ ${block}
4420
6541
  environmentArchiveCalls,
4421
6542
  threadActions: options.threadActions ?? NO_THREAD_ACTIONS,
4422
6543
  threadActionRegistrations: options.threadActionRegistrations ?? NO_THREAD_ACTION_REGISTRATIONS,
4423
- sidebarPullRequests,
4424
6544
  sidebarDraftThreadIds,
4425
6545
  sidebarRowStatuses,
4426
6546
  sidebarShortcuts,
4427
6547
  sidebarSplitLayout: options.sidebarSplitLayout ?? null,
6548
+ composerRenderer: options.composerRenderer ?? null,
4428
6549
  environmentProviders,
4429
6550
  sdk,
4430
6551
  sdkCalls,
@@ -4462,7 +6583,7 @@ ${block}
4462
6583
  pageTitle = null;
4463
6584
  };
4464
6585
  }, [value]);
4465
- return /* @__PURE__ */ jsx(Fragment, { children });
6586
+ return /* @__PURE__ */ jsx(Fragment2, { children });
4466
6587
  }
4467
6588
  const renderSlotTree = (ui) => /* @__PURE__ */ jsx(SlotEnvContext.Provider, { value: env, children: /* @__PURE__ */ jsx(SlotLifecycleGuard, { onUnmount: releaseComposerOwnership, children: /* @__PURE__ */ jsx(SlotPageTitle, { children: ui }) }) });
4468
6589
  const Component = registration.component;
@@ -4481,7 +6602,15 @@ ${block}
4481
6602
  });
4482
6603
  };
4483
6604
  const setRealtimeConnectionState = async (state) => {
4484
- await act(async () => realtimeConnection.setState(state));
6605
+ await act(async () => {
6606
+ realtimeConnection.setState(state);
6607
+ if (state === "connected")
6608
+ await invalidateTags(
6609
+ queryClient,
6610
+ pluginTagScope(options.pluginId ?? "test-plugin"),
6611
+ null
6612
+ );
6613
+ });
4485
6614
  };
4486
6615
  const setComposerText2 = async (text) => {
4487
6616
  await act(async () => commitComposerText(text));
@@ -4492,13 +6621,9 @@ ${block}
4492
6621
  notifyComposerListeners();
4493
6622
  });
4494
6623
  };
4495
- const experimental_invalidateRpc = async (tags) => {
6624
+ const experimental_invalidateRpc = async (tags, pluginId = options.pluginId ?? "test-plugin") => {
4496
6625
  await act(async () => {
4497
- await invalidateTags(
4498
- queryClient,
4499
- pluginTagScope(rpcQueryHost.pluginId),
4500
- tags
4501
- );
6626
+ await invalidateTags(queryClient, pluginTagScope(pluginId), tags);
4502
6627
  });
4503
6628
  };
4504
6629
  const unmountSlot = () => {
@@ -4517,6 +6642,7 @@ ${block}
4517
6642
  setComposerScope,
4518
6643
  navigateCalls,
4519
6644
  experimental_fixedTabOpenCalls,
6645
+ experimental_tabOpenCalls,
4520
6646
  sidebarActionCalls,
4521
6647
  sidebarNavigationCalls,
4522
6648
  experimental_environmentArchiveCalls: environmentArchiveCalls,
@@ -4537,6 +6663,7 @@ ${block}
4537
6663
  rpcCalls,
4538
6664
  navigateCalls,
4539
6665
  experimental_fixedTabOpenCalls,
6666
+ experimental_tabOpenCalls,
4540
6667
  sidebarActionCalls,
4541
6668
  sidebarNavigationCalls,
4542
6669
  experimental_environmentArchiveCalls: environmentArchiveCalls,