@xmoon76/dsh-pi-tui 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.en.md +64 -26
  2. package/README.md +64 -26
  3. package/cordis.patch.yml +13 -0
  4. package/dist/acp-stdio.mjs +151 -0
  5. package/dist/{bootstrap-C9nl6e13.mjs → bootstrap-CVyHGQDX.mjs} +22330 -6888
  6. package/dist/browser-CDUSHIIr.mjs +76 -0
  7. package/dist/builtins.mjs +2 -2
  8. package/dist/{client-bootstrap-CGezi85O.mjs → client-bootstrap-4UoeVIHE.mjs} +2407 -1830
  9. package/dist/client-runtime-BHBlVUf5.mjs +1376 -0
  10. package/dist/{daemon-launcher-H_1r5Cqs.mjs → daemon-launcher-DxIgjBHW.mjs} +1551 -57
  11. package/dist/daemon-launcher.d.mts +85 -14
  12. package/dist/daemon-launcher.mjs +2 -2
  13. package/dist/diagnostics-Db5iVcuJ.mjs +123 -0
  14. package/dist/{entry-control-jBfKn1qO.mjs → entry-control-BDLZgg4m.mjs} +1 -1
  15. package/dist/{extensions-6a5vvJUT.mjs → extensions-Dx7ncPNA.mjs} +1 -4
  16. package/dist/extensions.mjs +1 -1
  17. package/dist/handoff-BjoEy3f8.mjs +106 -0
  18. package/dist/history-search-limits-Cx2UvRC2.mjs +16 -0
  19. package/dist/history-search-remote-BHuoellG.mjs +113 -0
  20. package/dist/history-search-remote-BzXdvrxk.mjs +26 -0
  21. package/dist/history-search-seat-BcHJTpeB.mjs +639 -0
  22. package/dist/history-search-seat-rZcq0XV6.mjs +639 -0
  23. package/dist/{host-bootstrap-MVxks641.mjs → host-bootstrap-BfnufpnW.mjs} +37 -72
  24. package/dist/{host-foundation-probe-DK7n5jDu.mjs → host-foundation-probe-DlD8-N_Q.mjs} +2 -2
  25. package/dist/host-runtime.mjs +5611 -290
  26. package/dist/index.d.mts +13 -6
  27. package/dist/index.mjs +22766 -6893
  28. package/dist/installed-dsh-BjUiJSwR.mjs +142 -0
  29. package/dist/interaction-port-D1Yv9zgu.mjs +45 -0
  30. package/dist/local-acp-control-CC5z4Xbq.mjs +304 -0
  31. package/dist/local-acp-endpoint-D1jYdJdv.mjs +41 -0
  32. package/dist/local-acp-listener-Cmgb5M0H.mjs +9493 -0
  33. package/dist/local-acp-status-B_25Q6kU.mjs +101 -0
  34. package/dist/local-client.mjs +719 -93
  35. package/dist/local-daemon-control-BFJAC8Kg.mjs +2199 -0
  36. package/dist/local-daemon-control-Bm3imctD.mjs +2101 -0
  37. package/dist/{local-discovery-BPZw1wEd.mjs → local-discovery-BMhaGIiJ.mjs} +254 -544
  38. package/dist/{local-discovery-BMoNXZjJ.mjs → local-discovery-Ba7_-NNC.mjs} +1 -1
  39. package/dist/{local-discovery-Bq3jLAn1.mjs → local-discovery-QSbFpjK2.mjs} +301 -544
  40. package/dist/local-host.mjs +970 -501
  41. package/dist/local-profile-daemon-admin-otpm69R6.mjs +469 -0
  42. package/dist/{local-scope-DEuGAy8l.mjs → local-scope-5DEKA_lW.mjs} +1075 -31
  43. package/dist/{local-transport-X4ZCe2uE.mjs → local-transport-DeWmdZ5E.mjs} +14 -3
  44. package/dist/{local-web-control-DKWtXIkr.mjs → local-web-control-Dny93N-r.mjs} +10 -7
  45. package/dist/{local-workspace-object-D06GL0UO.mjs → local-workspace-object-D0RVQt8U.mjs} +33 -9
  46. package/dist/model-selection-CYlqg2DV.mjs +83 -0
  47. package/dist/native-client-domains-Dg4srzYt.mjs +2 -0
  48. package/dist/native-client.d.mts +735 -0
  49. package/dist/native-client.mjs +3534 -0
  50. package/dist/{open-CmOBxSjN.mjs → open-QQva8-ar.mjs} +24 -20
  51. package/dist/{pi-tui-remote-contribution-Do8ECrUy.mjs → pi-tui-remote-contribution-565wiLWp.mjs} +741 -150
  52. package/dist/preferences.mjs +1 -1
  53. package/dist/{profile-preferences-migration-CThz4rHH.mjs → profile-preferences-migration-CNOWIdnr.mjs} +1 -1
  54. package/dist/{profile-preferences-migration-BfUGdPZx.mjs → profile-preferences-migration-IrnXcJWK.mjs} +10 -8
  55. package/dist/{prompt-sections-DXmjB58H.mjs → prompt-sections-Bi-9_Gr_.mjs} +28 -10
  56. package/dist/{prompt-sections-DUKmWb8g.mjs → prompt-sections-DFS1dqsY.mjs} +342 -56
  57. package/dist/{dist-BFgC-5tL.mjs → recall-scope-9Nuoto_i.mjs} +353 -1
  58. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  59. package/dist/schema-CCLvDa7Q.mjs +177 -0
  60. package/dist/{schema-qE_P09zJ.mjs → schema-t97l3aK8.mjs} +56 -3
  61. package/dist/{session-DC0XQr5O.mjs → session-Cs8iLCEx.mjs} +784 -342
  62. package/dist/{session-Cihe8PPS.mjs → session-EBRZF6Ow.mjs} +783 -341
  63. package/dist/session-create-facts-CkfG5DpQ.mjs +20 -0
  64. package/dist/{startup-CarQxWwi.d.mts → startup-Dti3Udne.d.mts} +30 -3
  65. package/dist/{startup-CARqn3kV.mjs → startup-UtFQSDe_.mjs} +90 -15
  66. package/dist/startup.d.mts +2 -2
  67. package/dist/startup.mjs +1 -1
  68. package/dist/task-read-remote-DRtkXDrZ.mjs +1083 -0
  69. package/dist/{terminal-progress-source-D4DHyXDo.mjs → terminal-progress-source-VsczdXA-.mjs} +610 -335
  70. package/dist/{transcript-view-a7cROAaI.mjs → transcript-view-B6vCnukn.mjs} +2284 -1166
  71. package/dist/{transcript-view-hvNVkPtv.mjs → transcript-view-DSSdE2vK.mjs} +2191 -765
  72. package/dist/write-failure-xNKczXH7.mjs +189 -0
  73. package/package.json +25 -8
  74. package/dist/local-acp-listener-CNkguN5-.mjs +0 -2566
  75. package/dist/local-daemon-control-Bg9s2aYi.mjs +0 -1424
  76. package/dist/local-daemon-control-Cu_4FIdd.mjs +0 -1585
  77. package/dist/local-profile-daemon-admin-AXgVH-6y.mjs +0 -91
  78. package/dist/preset-BcWqOtY7.mjs +0 -46
@@ -0,0 +1,639 @@
1
+ import { i as runDetached } from "./tasks-D_z5Yjjr.mjs";
2
+ import { i as RemoteHistorySearchSupersededError, n as RemoteHistorySearchFailedError, t as RemoteHistorySearchDeniedError } from "./history-search-remote-BHuoellG.mjs";
3
+ import { t as HISTORY_SEARCH_READ_TEXT_LIMIT_MAX } from "./history-search-limits-Cx2UvRC2.mjs";
4
+ import { createHash } from "node:crypto";
5
+ //#region src/runtime/history-search-seat.ts
6
+ /**
7
+ * The neutral Remote accepted-history seat contract shared by the application
8
+ * owner and both renderers.
9
+ *
10
+ * The concrete seat lives in the Remote composition layer; terminal
11
+ * presentation consumes only these types, so it never imports the experimental
12
+ * Remote composition or a Host transport.
13
+ *
14
+ * @module @xmoon76/dsh-pi-tui/runtime/history-search-seat
15
+ */
16
+ const DEFAULT_DEBOUNCE_MS = 75;
17
+ const INCOMPLETE_LABEL = {
18
+ "source-uncertain": "source uncertain",
19
+ "reconciling": "reconciling",
20
+ "resource-limit": "resource limit",
21
+ "source-read-failed": "source read failed"
22
+ };
23
+ function rowOf(item) {
24
+ return {
25
+ id: `${item.sessionId}\u0000${item.messageId}`,
26
+ sessionId: item.sessionId,
27
+ messageId: item.messageId,
28
+ firstEventSeq: item.firstEventSeq,
29
+ acceptedAt: item.acceptedAt,
30
+ effectiveCwd: item.effectiveCwd,
31
+ preview: item.preview,
32
+ contentLength: item.contentLength,
33
+ contentSha256: item.contentSha256,
34
+ hasNonText: item.hasNonText
35
+ };
36
+ }
37
+ /** The complete visible row identity used to keep a selection across a refresh. */
38
+ function sameRowIdentity(left, right) {
39
+ return left.id === right.id && left.firstEventSeq === right.firstEventSeq && left.acceptedAt === right.acceptedAt && left.effectiveCwd === right.effectiveCwd && left.contentLength === right.contentLength && left.contentSha256 === right.contentSha256 && left.hasNonText === right.hasNonText && left.preview === right.preview;
40
+ }
41
+ function isAbort(error) {
42
+ return typeof error === "object" && error !== null && error.name === "AbortError";
43
+ }
44
+ /** The closed, safe body-failure reasons (never a raw Host error message). */
45
+ const BODY_FAILURE_LABEL = {
46
+ "body-loading": "the Host is still indexing",
47
+ "body-incomplete": "the Host source is incomplete",
48
+ "body-unavailable": "the Host body is unavailable",
49
+ "body-length-mismatch": "the Host content length changed",
50
+ "body-offset-mismatch": "the Host text offsets are not contiguous",
51
+ "body-truncated": "the Host text did not terminate",
52
+ "body-hash-mismatch": "the content hash does not match"
53
+ };
54
+ function createRemoteHistorySeat(options) {
55
+ const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
56
+ const refreshMs = options.refreshMs ?? 1e3;
57
+ const listeners = /* @__PURE__ */ new Set();
58
+ let serial = 0;
59
+ let queryRevision = 0;
60
+ let scope = "all";
61
+ let query = "";
62
+ let status = "idle";
63
+ let message = "";
64
+ let rows = [];
65
+ let selectedId;
66
+ let nextCursor = null;
67
+ let generation;
68
+ let moreLoading = false;
69
+ let progress;
70
+ let pageRevision = 0;
71
+ let body = { kind: "none" };
72
+ let directory = options.scope.directory();
73
+ let searchAbort;
74
+ let bodyAbort;
75
+ let timer;
76
+ let staleAutoUsed = false;
77
+ let userChanged = false;
78
+ let closed = false;
79
+ let scopeSub;
80
+ const publish = () => {
81
+ if (closed) return;
82
+ for (const listener of [...listeners]) listener();
83
+ };
84
+ const cancelSearch = () => {
85
+ searchAbort?.abort();
86
+ searchAbort = void 0;
87
+ if (timer !== void 0) {
88
+ clearTimeout(timer);
89
+ timer = void 0;
90
+ }
91
+ };
92
+ const cancelBody = () => {
93
+ bodyAbort?.abort();
94
+ bodyAbort = void 0;
95
+ };
96
+ const retire = () => {
97
+ if (closed) return;
98
+ closed = true;
99
+ cancelSearch();
100
+ cancelBody();
101
+ scopeSub?.();
102
+ scopeSub = void 0;
103
+ options.scope.dispose();
104
+ listeners.clear();
105
+ options.onRetire();
106
+ };
107
+ const onScopeChanged = () => {
108
+ if (closed) return;
109
+ if (!options.scope.isCurrent()) {
110
+ retire();
111
+ return;
112
+ }
113
+ directory = options.scope.directory();
114
+ const blank = options.scope.blankDirectory?.();
115
+ if (!userChanged && serial > 0 && scope === "session" && options.scope.initialScope === "session" && blank !== void 0 && blank.sessionId === options.sessionId && directory.available && directory.cwd === blank.cwd) {
116
+ scope = "current";
117
+ startFresh();
118
+ return;
119
+ }
120
+ if (!userChanged && serial > 0 && scope === "all" && options.scope.initialScope === "all" && directory.available && directory.cwd !== void 0) {
121
+ scope = "current";
122
+ userChanged = false;
123
+ startFresh();
124
+ return;
125
+ }
126
+ if (scope === "current" && !directory.available) {
127
+ cancelSearch();
128
+ queryRevision += 1;
129
+ status = "unavailable";
130
+ message = "That Host directory is no longer available";
131
+ rows = [];
132
+ selectedId = void 0;
133
+ nextCursor = null;
134
+ generation = void 0;
135
+ progress = void 0;
136
+ cancelBody();
137
+ body = { kind: "none" };
138
+ } else if (scope === "current" && directory.available && status === "unavailable") {
139
+ startFresh();
140
+ return;
141
+ }
142
+ publish();
143
+ };
144
+ scopeSub = options.scope.subscribe(onScopeChanged);
145
+ const requestOf = (cursor) => {
146
+ if (scope === "session") {
147
+ if (options.sessionId === void 0) return void 0;
148
+ return {
149
+ scope: "session",
150
+ sessionId: options.sessionId,
151
+ query,
152
+ limit: 25,
153
+ ...cursor === void 0 ? {} : { cursor }
154
+ };
155
+ }
156
+ if (scope === "current") {
157
+ if (!directory.available || directory.cwd === void 0) return void 0;
158
+ return {
159
+ scope: "directory",
160
+ cwd: directory.cwd,
161
+ query,
162
+ limit: 25,
163
+ ...cursor === void 0 ? {} : { cursor }
164
+ };
165
+ }
166
+ return {
167
+ scope: "all",
168
+ query,
169
+ limit: 25,
170
+ ...cursor === void 0 ? {} : { cursor }
171
+ };
172
+ };
173
+ const finishWithStatus = (next, text) => {
174
+ status = next;
175
+ message = text;
176
+ rows = [];
177
+ selectedId = void 0;
178
+ nextCursor = null;
179
+ generation = void 0;
180
+ progress = void 0;
181
+ moreLoading = false;
182
+ cancelBody();
183
+ body = { kind: "none" };
184
+ publish();
185
+ };
186
+ const selectForPage = (previousRows, incoming, preserveSelection) => {
187
+ const previous = preserveSelection && selectedId !== void 0 ? previousRows.find((row) => row.id === selectedId) : void 0;
188
+ return (previous === void 0 ? void 0 : incoming.find((row) => sameRowIdentity(row, previous))) ?? incoming[0];
189
+ };
190
+ /**
191
+ * Keep the exact body/read state only for the SAME complete row identity.
192
+ * A progress-only publish therefore never re-reads the body or drops a ready
193
+ * text; a changed hash/rank/missing row starts exactly one new body read.
194
+ */
195
+ const keepOrStartBody = (next, preserveSelection) => {
196
+ const existing = body;
197
+ if (preserveSelection && existing.kind !== "none" && sameRowIdentity(existing.row, next)) {
198
+ if (existing.kind === "ready" || existing.kind === "loading" || existing.kind === "failed") {
199
+ body = {
200
+ ...existing,
201
+ row: next
202
+ };
203
+ return;
204
+ }
205
+ }
206
+ startBody(next, serial, queryRevision);
207
+ };
208
+ const sameRowList = (left, right) => {
209
+ if (left.length !== right.length) return false;
210
+ return left.every((row, index) => {
211
+ const other = right[index];
212
+ return other !== void 0 && sameRowIdentity(row, other);
213
+ });
214
+ };
215
+ const commitPage = (page, round, preserveSelection) => {
216
+ if (closed || round.serial !== serial || round.revision !== queryRevision) return;
217
+ if (!options.scope.isCurrent()) {
218
+ retire();
219
+ return;
220
+ }
221
+ const previousRows = rows;
222
+ if (!sameRowList(previousRows, page.rows)) pageRevision += 1;
223
+ rows = [...page.rows];
224
+ status = page.status;
225
+ message = page.message;
226
+ nextCursor = page.nextCursor;
227
+ generation = page.generation;
228
+ progress = page.progress;
229
+ moreLoading = false;
230
+ const selected = selectForPage(previousRows, rows, preserveSelection);
231
+ if (selected === void 0) {
232
+ selectedId = void 0;
233
+ cancelBody();
234
+ body = { kind: "none" };
235
+ } else {
236
+ selectedId = selected.id;
237
+ keepOrStartBody(selected, preserveSelection);
238
+ }
239
+ publish();
240
+ if (page.refresh) scheduleRefresh(round);
241
+ };
242
+ const commitFirstPage = (response, round, refresh) => {
243
+ const incoming = response.items.map(rowOf);
244
+ commitPage({
245
+ rows: incoming,
246
+ status: "ready",
247
+ message: incoming.length === 0 ? "No matches" : `Results · ${String(incoming.length)} shown`,
248
+ nextCursor: response.nextCursor,
249
+ generation: response.generation,
250
+ progress: void 0,
251
+ refresh: false
252
+ }, round, refresh);
253
+ };
254
+ const commitPartial = (response, round, refresh) => {
255
+ const incoming = response.items.map(rowOf);
256
+ const { settled, total } = response.progress;
257
+ const percent = Math.floor(settled * 100 / total);
258
+ commitPage({
259
+ rows: incoming,
260
+ status: "partial",
261
+ message: incoming.length === 0 ? "No matches yet — indexing…" : `Results · ${String(incoming.length)} shown · Indexing ${String(settled)}/${String(total)} (${String(percent)}%)`,
262
+ nextCursor: null,
263
+ generation: void 0,
264
+ progress: {
265
+ settled,
266
+ total
267
+ },
268
+ refresh: true
269
+ }, round, refresh);
270
+ };
271
+ const runSearch = (round, cursor, append, refresh = false) => {
272
+ if (closed || round.serial !== serial || round.revision !== queryRevision) return;
273
+ const request = requestOf(cursor);
274
+ if (request === void 0) {
275
+ finishWithStatus("unavailable", scope === "current" ? "Directory is not available for this open" : "Session history is not available for this open");
276
+ return;
277
+ }
278
+ const controller = new AbortController();
279
+ searchAbort = controller;
280
+ runDetached("Remote History search", async () => {
281
+ try {
282
+ const response = await options.read.search(request, controller.signal);
283
+ if (closed || round.serial !== serial || round.revision !== queryRevision || controller.signal.aborted) return;
284
+ if (!options.scope.isCurrent()) {
285
+ retire();
286
+ return;
287
+ }
288
+ await commitResponse(response, round, append, cursor, refresh);
289
+ } catch (error) {
290
+ if (closed || round.serial !== serial || round.revision !== queryRevision || isAbort(error)) return;
291
+ if (error instanceof RemoteHistorySearchSupersededError) {
292
+ retire();
293
+ return;
294
+ }
295
+ if (error instanceof RemoteHistorySearchDeniedError) {
296
+ finishWithStatus("denied", "History search is not permitted");
297
+ return;
298
+ }
299
+ if (error instanceof RemoteHistorySearchFailedError) {
300
+ finishWithStatus("failed", `History request failed${error.code === void 0 ? "" : ` (${error.code})`}`);
301
+ return;
302
+ }
303
+ finishWithStatus("failed", "History request failed");
304
+ } finally {
305
+ if (searchAbort === controller) searchAbort = void 0;
306
+ }
307
+ }, { diag: options.diag });
308
+ };
309
+ /**
310
+ * One settled→next first-page refresh. The timer is the seat's existing owner
311
+ * (the debounce slot), never a second interval: any new user query/scope,
312
+ * Retry, close or teardown clears it through cancelSearch().
313
+ */
314
+ const scheduleRefresh = (round) => {
315
+ if (closed || timer !== void 0) return;
316
+ if (status !== "partial" && status !== "loading-host") return;
317
+ if (round.serial !== serial || round.revision !== queryRevision) return;
318
+ timer = setTimeout(() => {
319
+ timer = void 0;
320
+ if (closed || round.serial !== serial || round.revision !== queryRevision) return;
321
+ if (status !== "partial" && status !== "loading-host") return;
322
+ if (searchAbort !== void 0) return;
323
+ runSearch({
324
+ serial,
325
+ revision: queryRevision
326
+ }, void 0, false, true);
327
+ }, refreshMs);
328
+ timer.unref?.();
329
+ };
330
+ const commitResponse = async (response, round, append, cursor, refresh) => {
331
+ if (response.kind === "ready") {
332
+ if (append) {
333
+ if (cursor === void 0 || response.generation !== generation) {
334
+ await recoverStaleMore(round);
335
+ return;
336
+ }
337
+ rows = [...rows, ...response.items.map(rowOf)];
338
+ nextCursor = response.nextCursor;
339
+ moreLoading = false;
340
+ if (selectedId === void 0 && rows.length > 0) {
341
+ selectedId = rows[0]?.id;
342
+ const selected = rows[0];
343
+ if (selected !== void 0) startBody(selected, round.serial, round.revision);
344
+ }
345
+ body = body.kind === "none" && selectedId !== void 0 ? {
346
+ kind: "preview",
347
+ row: rows.find((row) => row.id === selectedId)
348
+ } : body;
349
+ status = "ready";
350
+ message = `Results · ${String(rows.length)} shown`;
351
+ publish();
352
+ return;
353
+ }
354
+ commitFirstPage(response, round, refresh);
355
+ return;
356
+ }
357
+ if (append) {
358
+ moreLoading = false;
359
+ if (response.kind === "stale" || response.kind === "partial") {
360
+ await recoverStaleMore(round);
361
+ return;
362
+ }
363
+ rows = [];
364
+ selectedId = void 0;
365
+ nextCursor = null;
366
+ generation = void 0;
367
+ status = response.kind === "loading" ? "loading-host" : response.kind === "incomplete" ? "incomplete" : "unavailable";
368
+ message = response.kind === "loading" ? "History is loading on Host" : response.kind === "incomplete" ? `History incomplete — ${INCOMPLETE_LABEL[response.reason]}` : response.reason === "service-missing" ? "History search is not available on this Host" : "History index is unavailable";
369
+ cancelBody();
370
+ body = { kind: "none" };
371
+ publish();
372
+ return;
373
+ }
374
+ if (response.kind === "partial") {
375
+ commitPartial(response, round, refresh);
376
+ return;
377
+ }
378
+ if (response.kind === "loading") {
379
+ finishWithStatus("loading-host", "Loading history…");
380
+ scheduleRefresh(round);
381
+ return;
382
+ }
383
+ if (response.kind === "incomplete") {
384
+ finishWithStatus("incomplete", `History incomplete — ${INCOMPLETE_LABEL[response.reason]}`);
385
+ return;
386
+ }
387
+ if (response.kind === "unavailable") {
388
+ finishWithStatus("unavailable", response.reason === "service-missing" ? "History search is not available on this Host" : "History index is unavailable");
389
+ return;
390
+ }
391
+ finishWithStatus("stale", "History changed — Retry");
392
+ };
393
+ const recoverStaleMore = async (round) => {
394
+ cancelBody();
395
+ rows = [];
396
+ selectedId = void 0;
397
+ nextCursor = null;
398
+ generation = void 0;
399
+ body = { kind: "none" };
400
+ if (!staleAutoUsed) {
401
+ staleAutoUsed = true;
402
+ moreLoading = false;
403
+ queryRevision += 1;
404
+ status = "searching";
405
+ message = "Refreshing history…";
406
+ publish();
407
+ runSearch({
408
+ serial: round.serial,
409
+ revision: queryRevision
410
+ }, void 0, false);
411
+ return;
412
+ }
413
+ moreLoading = false;
414
+ finishWithStatus("stale", "History changed — Retry");
415
+ };
416
+ const resetChain = () => {
417
+ cancelSearch();
418
+ cancelBody();
419
+ queryRevision += 1;
420
+ moreLoading = false;
421
+ staleAutoUsed = false;
422
+ rows = [];
423
+ selectedId = void 0;
424
+ nextCursor = null;
425
+ generation = void 0;
426
+ progress = void 0;
427
+ body = { kind: "none" };
428
+ };
429
+ const startFresh = () => {
430
+ resetChain();
431
+ if (closed) return;
432
+ if (query.length > 256) {
433
+ status = "too-long";
434
+ message = `Query is too long (max ${String(256)})`;
435
+ publish();
436
+ return;
437
+ }
438
+ if (scope === "session" && options.sessionId === void 0) {
439
+ status = "unavailable";
440
+ message = "Session history is not available for this open";
441
+ publish();
442
+ return;
443
+ }
444
+ if (scope === "current" && !directory.available) {
445
+ status = "unavailable";
446
+ message = "Directory is not available for this open";
447
+ publish();
448
+ return;
449
+ }
450
+ const round = {
451
+ serial,
452
+ revision: queryRevision
453
+ };
454
+ status = "searching";
455
+ message = "Searching…";
456
+ publish();
457
+ runSearch(round, void 0, false);
458
+ };
459
+ const scheduleFresh = () => {
460
+ resetChain();
461
+ if (closed) return;
462
+ if (query.length > 256) {
463
+ status = "too-long";
464
+ message = `Query is too long (max ${String(256)})`;
465
+ publish();
466
+ return;
467
+ }
468
+ status = "searching";
469
+ message = "Searching…";
470
+ publish();
471
+ timer = setTimeout(() => {
472
+ timer = void 0;
473
+ runSearch({
474
+ serial,
475
+ revision: queryRevision
476
+ }, void 0, false);
477
+ }, debounceMs);
478
+ };
479
+ const startBody = (row, expectedSerial, expectedRevision) => {
480
+ if (closed) return;
481
+ cancelBody();
482
+ const controller = new AbortController();
483
+ bodyAbort = controller;
484
+ body = {
485
+ kind: "loading",
486
+ row,
487
+ preview: row.preview
488
+ };
489
+ publish();
490
+ runDetached("Remote History body", async () => {
491
+ try {
492
+ const text = await readBody(row, expectedSerial, expectedRevision, controller.signal);
493
+ if (closed || controller.signal.aborted || expectedSerial !== serial || expectedRevision !== queryRevision || selectedId !== row.id) return;
494
+ if (!options.scope.isCurrent()) {
495
+ retire();
496
+ return;
497
+ }
498
+ body = {
499
+ kind: "ready",
500
+ row,
501
+ text,
502
+ hasNonText: row.hasNonText
503
+ };
504
+ publish();
505
+ } catch (error) {
506
+ if (closed || controller.signal.aborted || isAbort(error) || expectedSerial !== serial || expectedRevision !== queryRevision || selectedId !== row.id) return;
507
+ if (error instanceof RemoteHistorySearchSupersededError) {
508
+ retire();
509
+ return;
510
+ }
511
+ const message = error instanceof RemoteHistorySearchDeniedError ? "History text is not permitted" : error instanceof RemoteHistorySearchFailedError ? `History text failed${BODY_FAILURE_LABEL[error.code ?? ""] === void 0 ? "" : ` — ${BODY_FAILURE_LABEL[error.code ?? ""]}`}` : "History text is unavailable";
512
+ body = {
513
+ kind: "failed",
514
+ row,
515
+ preview: row.preview,
516
+ message
517
+ };
518
+ publish();
519
+ } finally {
520
+ if (bodyAbort === controller) bodyAbort = void 0;
521
+ }
522
+ }, { diag: options.diag });
523
+ };
524
+ const readBody = async (row, expectedSerial, expectedRevision, signal) => {
525
+ let text = "";
526
+ let offset = 0;
527
+ const maxChunks = Math.ceil(row.contentLength / HISTORY_SEARCH_READ_TEXT_LIMIT_MAX) + 2;
528
+ for (let chunkIndex = 0; chunkIndex < maxChunks; chunkIndex += 1) {
529
+ if (closed || signal.aborted || expectedSerial !== serial || expectedRevision !== queryRevision) throw new DOMException("aborted", "AbortError");
530
+ const request = {
531
+ sessionId: row.sessionId,
532
+ messageId: row.messageId,
533
+ contentSha256: row.contentSha256,
534
+ offset,
535
+ limit: HISTORY_SEARCH_READ_TEXT_LIMIT_MAX
536
+ };
537
+ const response = await options.read.readText(request, signal);
538
+ if (signal.aborted || expectedSerial !== serial || expectedRevision !== queryRevision) throw new DOMException("aborted", "AbortError");
539
+ if (response.kind !== "ready") throw new RemoteHistorySearchFailedError(response.kind === "unavailable" ? "body-unavailable" : response.kind === "incomplete" ? "body-incomplete" : "body-loading", "the Host did not answer a body chunk");
540
+ if (response.contentLength !== row.contentLength) throw new RemoteHistorySearchFailedError("body-length-mismatch", "the Host content length changed");
541
+ text += response.chunk;
542
+ if (response.nextOffset === null) {
543
+ if (text.length !== row.contentLength) throw new RemoteHistorySearchFailedError("body-length-mismatch", "the Host text ended at the wrong offset");
544
+ break;
545
+ }
546
+ if (response.nextOffset !== text.length || response.nextOffset <= offset) throw new RemoteHistorySearchFailedError("body-offset-mismatch", "the Host text offset is not contiguous");
547
+ offset = response.nextOffset;
548
+ if (chunkIndex === maxChunks - 1) throw new RemoteHistorySearchFailedError("body-truncated", "the Host text did not terminate");
549
+ }
550
+ if (createHash("sha256").update(text, "utf8").digest("hex") !== row.contentSha256) throw new RemoteHistorySearchFailedError("body-hash-mismatch", "the Host text does not match its content hash");
551
+ return text;
552
+ };
553
+ return {
554
+ open(nextScope, nextQuery) {
555
+ if (closed) return;
556
+ serial += 1;
557
+ userChanged = false;
558
+ query = nextQuery;
559
+ directory = options.scope.directory();
560
+ const blank = options.scope.blankDirectory?.();
561
+ scope = nextScope === "session" && blank !== void 0 && blank.sessionId === options.sessionId && directory.available && directory.cwd === blank.cwd ? "current" : nextScope;
562
+ startFresh();
563
+ },
564
+ setQuery(nextQuery) {
565
+ if (closed) return;
566
+ userChanged = true;
567
+ query = nextQuery;
568
+ scheduleFresh();
569
+ },
570
+ setScope(nextScope) {
571
+ if (closed) return;
572
+ userChanged = true;
573
+ if (nextScope === scope) return;
574
+ scope = nextScope;
575
+ startFresh();
576
+ },
577
+ select(id) {
578
+ if (closed || status !== "ready" && status !== "partial" || moreLoading) return;
579
+ const row = rows.find((candidate) => candidate.id === id);
580
+ if (row === void 0) return;
581
+ userChanged = true;
582
+ if (id === selectedId && body.kind !== "failed") return;
583
+ selectedId = id;
584
+ startBody(row, serial, queryRevision);
585
+ },
586
+ more() {
587
+ if (closed || status !== "ready" || moreLoading || nextCursor === null) return;
588
+ moreLoading = true;
589
+ message = "Loading more…";
590
+ publish();
591
+ runSearch({
592
+ serial,
593
+ revision: queryRevision
594
+ }, nextCursor, true);
595
+ },
596
+ retry() {
597
+ if (closed || moreLoading) return;
598
+ userChanged = true;
599
+ staleAutoUsed = false;
600
+ startFresh();
601
+ },
602
+ close(closeOptions) {
603
+ if (closed) return;
604
+ closed = true;
605
+ cancelSearch();
606
+ cancelBody();
607
+ scopeSub?.();
608
+ scopeSub = void 0;
609
+ if (closeOptions?.preserveScope !== true) options.scope.dispose();
610
+ listeners.clear();
611
+ },
612
+ view() {
613
+ return {
614
+ serial,
615
+ queryRevision,
616
+ pageRevision,
617
+ scope,
618
+ query,
619
+ status,
620
+ message,
621
+ progress,
622
+ rows: [...rows],
623
+ selectedId,
624
+ hasMore: nextCursor !== null,
625
+ moreLoading,
626
+ directory,
627
+ body
628
+ };
629
+ },
630
+ subscribe(listener) {
631
+ listeners.add(listener);
632
+ return () => {
633
+ listeners.delete(listener);
634
+ };
635
+ }
636
+ };
637
+ }
638
+ //#endregion
639
+ export { createRemoteHistorySeat };