@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,1083 @@
1
+ import { t as cancellationError } from "./tasks-D_z5Yjjr.mjs";
2
+ import { a as remoteFailureMessage, c as settledWriteMessage, i as remoteFailureCode, l as GATEWAY_PRE_INVOCATION_CODES, n as copyFailureDetails, o as remoteNotDispatched, s as remoteRejected } from "./write-failure-xNKczXH7.mjs";
3
+ import { a as SupersededReadError, n as normalizeModelSelection } from "./model-selection-CYlqg2DV.mjs";
4
+ //#region src/runtime/remote/file-upload-remote.ts
5
+ var RemoteFileUploadError = class extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.name = "RemoteFileUploadError";
10
+ this.code = code;
11
+ }
12
+ };
13
+ /**
14
+ * Start the Client source BEFORE the carrier request: the streamer's open-time
15
+ * fingerprint/fstat checks run on this first pull, so a source that is already
16
+ * deleted/replaced/changed fails locally with its actionable error and the
17
+ * Host never receives a partial upload. At most ONE bounded source chunk is
18
+ * held here; everything after it streams directly.
19
+ */
20
+ async function prepareSource(file, signal) {
21
+ if (file.source.kind !== "client-stream") throw new RemoteFileUploadError("session/prompt-file-unsupported", "recalled files cannot be re-uploaded by this Client");
22
+ const iterator = file.source.open(signal)[Symbol.asyncIterator]();
23
+ const first = await iterator.next();
24
+ /**
25
+ * The ONE release of this source. Every caller (the upload's failure path
26
+ * and a concurrent carrier cancel) shares the SAME promise, so none of them
27
+ * reports completion before the iterator's `finally` has actually run; a
28
+ * rejection is observed identically by all of them.
29
+ */
30
+ let closePromise;
31
+ const close = () => {
32
+ closePromise ??= (async () => {
33
+ await iterator.return?.();
34
+ })();
35
+ return closePromise;
36
+ };
37
+ return {
38
+ body: new ReadableStream({
39
+ start(controller) {
40
+ if (first.done === true) controller.close();
41
+ else controller.enqueue(first.value);
42
+ },
43
+ async pull(controller) {
44
+ if (closePromise !== void 0) {
45
+ controller.close();
46
+ return;
47
+ }
48
+ signal.throwIfAborted();
49
+ const next = await iterator.next();
50
+ if (closePromise !== void 0) return;
51
+ signal.throwIfAborted();
52
+ if (next.done) controller.close();
53
+ else controller.enqueue(next.value);
54
+ },
55
+ async cancel() {
56
+ await close();
57
+ }
58
+ }),
59
+ close
60
+ };
61
+ }
62
+ function objectOf(value) {
63
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new RemoteFileUploadError("session/prompt-upload-invalid-response", "file upload returned an invalid response");
64
+ return value;
65
+ }
66
+ function createRemoteFileReceiptUploader(fetch) {
67
+ return { async upload(sessionId, prepared, signal) {
68
+ signal.throwIfAborted();
69
+ const source = await prepareSource(prepared, signal);
70
+ let primary;
71
+ try {
72
+ signal.throwIfAborted();
73
+ const response = await fetch(`/api/session/uploadFileBinary?${new URLSearchParams({
74
+ sessionId,
75
+ name: prepared.name
76
+ })}`, {
77
+ method: "POST",
78
+ headers: { "content-type": "application/octet-stream" },
79
+ body: source.body,
80
+ duplex: "half",
81
+ signal
82
+ });
83
+ signal.throwIfAborted();
84
+ if (!response.ok) throw new RemoteFileUploadError("session/prompt-upload-http-failed", `file upload failed with HTTP ${response.status}`);
85
+ let payload;
86
+ try {
87
+ payload = objectOf(await response.json());
88
+ } catch (error) {
89
+ if (error instanceof RemoteFileUploadError) throw error;
90
+ throw new RemoteFileUploadError("session/prompt-upload-invalid-response", "file upload returned invalid JSON");
91
+ }
92
+ signal.throwIfAborted();
93
+ if (payload.ok !== true) {
94
+ const failure = objectOf(payload.error);
95
+ if (typeof failure.code !== "string" || failure.code === "" || typeof failure.message !== "string" || failure.message === "") throw new RemoteFileUploadError("session/prompt-upload-invalid-response", "file upload returned an invalid business error");
96
+ throw new RemoteFileUploadError(failure.code, failure.message);
97
+ }
98
+ const value = objectOf(payload.value);
99
+ const file = objectOf(value.file);
100
+ if (typeof value.receiptId !== "string" || value.receiptId === "" || typeof file.attachmentId !== "string" || file.attachmentId === "" || typeof file.name !== "string" || file.name === "" || typeof file.bytes !== "number" || !Number.isSafeInteger(file.bytes) || file.bytes < 0) throw new RemoteFileUploadError("session/prompt-upload-invalid-response", "file upload returned invalid receipt metadata");
101
+ return {
102
+ receiptId: value.receiptId,
103
+ file: {
104
+ attachmentId: file.attachmentId,
105
+ name: file.name,
106
+ bytes: file.bytes
107
+ }
108
+ };
109
+ } catch (error) {
110
+ primary = error;
111
+ throw error;
112
+ } finally {
113
+ try {
114
+ await source.close();
115
+ } catch (closeError) {
116
+ if (primary !== void 0) throw new AggregateError([primary, closeError], "file upload failed and the Client file source could not be closed");
117
+ throw closeError;
118
+ }
119
+ }
120
+ } };
121
+ }
122
+ //#endregion
123
+ //#region src/runtime/remote/generation-cache.ts
124
+ /**
125
+ * `GenerationCache` — the minimal shared cache for an official one-shot Host
126
+ * snapshot (D2.3 v2 §0.4).
127
+ *
128
+ * The plan's warning against "an increasingly complicated cache" means: do not
129
+ * preserve old synchronous Direct-shaped APIs by inventing a private business
130
+ * model. It does NOT prohibit holding the official one-shot snapshot that a
131
+ * synchronous projection needs. This primitive exists only because the model
132
+ * directory and the preset roster genuinely share the same contract:
133
+ *
134
+ * ```text
135
+ * generation-tagged
136
+ * monotonic read epoch (latest read wins publication)
137
+ * invalidate on reconnect / successful mutation
138
+ * values detached on write AND on read (caller mutation can never reach cache)
139
+ * a failed read never destroys a last-good same-generation value
140
+ * a superseded read is never returned as if it were current
141
+ * ```
142
+ *
143
+ * @module @xmoon76/dsh-pi-tui/generation-cache
144
+ */
145
+ /** A generation-tagged snapshot cache with a latest-only read epoch. */
146
+ var GenerationCache = class {
147
+ value;
148
+ tag;
149
+ epoch = 0;
150
+ detach;
151
+ /** @param detach - deep-clone/freeze a value for storage or for a caller. */
152
+ constructor(detach) {
153
+ this.detach = detach;
154
+ }
155
+ /** Drop the cached value and bump the epoch, so any in-flight read can
156
+ * neither publish its result nor be served the invalidated value. */
157
+ invalidate() {
158
+ this.epoch += 1;
159
+ this.value = void 0;
160
+ this.tag = void 0;
161
+ }
162
+ /** Begin a read; the returned epoch identifies this read's publication
163
+ * ownership (a newer read or an invalidation supersedes it). */
164
+ beginRead() {
165
+ return ++this.epoch;
166
+ }
167
+ /** Publish a successfully read value. Returns false when this read was
168
+ * superseded while it was in flight (the cache is left untouched). */
169
+ publish(epoch, tag, value) {
170
+ if (epoch !== this.epoch) return false;
171
+ this.value = this.detach(value);
172
+ this.tag = tag;
173
+ return true;
174
+ }
175
+ /** A detached copy of the last-good value for `tag`, or undefined when the
176
+ * cache is empty or belongs to another generation. */
177
+ snapshot(tag) {
178
+ if (this.value === void 0 || !Object.is(this.tag, tag)) return void 0;
179
+ return this.detach(this.value);
180
+ }
181
+ /** Read one narrow projection of the current cached value without cloning
182
+ * the whole snapshot. The callback MUST return a detached scalar/object and
183
+ * must never expose or mutate the cached value itself. */
184
+ project(tag, project) {
185
+ if (this.value === void 0 || !Object.is(this.tag, tag)) return void 0;
186
+ return project(this.value);
187
+ }
188
+ };
189
+ //#endregion
190
+ //#region src/runtime/remote/model-remote.ts
191
+ /** The TUI add-provider wizard's settings family (the Direct adapter probes
192
+ * the same namespace; the wizard's provider profiles live under it). */
193
+ const WIZARD_SETTINGS_NS = "llm-pi-ai";
194
+ function generationChanged$1(generation, captured) {
195
+ return !Object.is(captured, generation.getSnapshot());
196
+ }
197
+ /** Detach an official selection into the semantic DTO (never the Host object). */
198
+ function copySelection(value) {
199
+ if (typeof value !== "object" || value === null) return void 0;
200
+ const record = value;
201
+ if (typeof record.provider !== "string" || record.provider === "") return void 0;
202
+ if (typeof record.model !== "string" || record.model === "") return void 0;
203
+ if (record.reasoningEffort !== void 0 && (typeof record.reasoningEffort !== "string" || record.reasoningEffort === "")) return void 0;
204
+ return {
205
+ provider: record.provider,
206
+ model: record.model,
207
+ ...typeof record.reasoningEffort === "string" ? { reasoningEffort: record.reasoningEffort } : {}
208
+ };
209
+ }
210
+ /** Detach an official catalog value into the semantic directory DTO. */
211
+ function copyDirectory(value) {
212
+ return {
213
+ default: copySelection(value.default) ?? {
214
+ provider: "",
215
+ model: ""
216
+ },
217
+ routableProviders: [...value.routableProviders],
218
+ groups: value.groups.map((group) => ({
219
+ id: group.id,
220
+ name: group.name,
221
+ models: group.models.map((model) => ({
222
+ id: model.id,
223
+ name: model.name,
224
+ ...model.description === void 0 ? {} : { description: model.description },
225
+ ...model.reasoning === void 0 ? {} : { reasoning: {
226
+ efforts: model.reasoning.efforts.map((effort) => ({
227
+ id: effort.id,
228
+ name: effort.name,
229
+ ...effort.description === void 0 ? {} : { description: effort.description }
230
+ })),
231
+ ...model.reasoning.defaultEffort === void 0 ? {} : { defaultEffort: model.reasoning.defaultEffort }
232
+ } }
233
+ }))
234
+ })),
235
+ failures: value.failures.map((failure) => ({
236
+ id: failure.id,
237
+ name: failure.name,
238
+ message: failure.message
239
+ }))
240
+ };
241
+ }
242
+ /**
243
+ * Operation-specific settlement for `session.selectModel`. Only an EXACT
244
+ * refusal code that PROVES the selection never committed is `rejected`;
245
+ * anything else stays `indeterminate`. The D2.2 broad refusal helper is
246
+ * deliberately NOT used, and no namespace prefix is treated as proof: a
247
+ * future post-commit `session/model-*` code must not be silently downgraded
248
+ * to a rejection.
249
+ *
250
+ * This classifier is only ever invoked AFTER `session.selectModel` was
251
+ * dispatched, so a cancellation code (`gateway/cancelled`, an AbortError) is
252
+ * NOT a proven pre-commit cancellation — §0.2.4/§0.7.1 require
253
+ * `indeterminate`. Pre-dispatch cancellation is `remoteNotDispatched()`.
254
+ */
255
+ function classifyRemoteModelFailure(error) {
256
+ const code = remoteFailureCode(error);
257
+ const details = copyFailureDetails(error);
258
+ if (code !== void 0 && (code === "gateway/bad-request" || code === "session/not-found" || code === "session/agent-busy" || code === "session/writer-held" || code === "session/model-unavailable" || GATEWAY_PRE_INVOCATION_CODES.has(code))) return {
259
+ kind: "rejected",
260
+ error: {
261
+ code,
262
+ message: settledWriteMessage(code, error),
263
+ ...details === void 0 ? {} : { details }
264
+ }
265
+ };
266
+ return {
267
+ kind: "indeterminate",
268
+ error: {
269
+ code: code ?? "session/model-indeterminate",
270
+ message: remoteFailureMessage(error),
271
+ ...details === void 0 ? {} : { details }
272
+ }
273
+ };
274
+ }
275
+ /** User-facing message for one Host default-model refusal reason (the reason
276
+ * code stays machine-readable on the semantic error). */
277
+ const DEFAULT_MODEL_REFUSAL_MESSAGES = {
278
+ "owner-required": "only the authenticated Owner peer may change the Host default model",
279
+ "default-model-service-unavailable": "the Host default-model service is not available",
280
+ "profile-persistence-unavailable": "this Host has no persisted profile to store the default model",
281
+ "profile-entry-unavailable": "the Host profile has no active agent-default-model entry to save into"
282
+ };
283
+ /**
284
+ * Settlement for ONE dispatched `piTuiDefaultModel/saveSelection` failure.
285
+ *
286
+ * Only a PROVEN Gateway pre-invocation code (the Gateway refused BEFORE the Host
287
+ * method ran) is a rejection. Every other dispatched failure — `gateway/internal`,
288
+ * `gateway/cancelled`, `gateway/result-invalid`, a code-less HTTP drop — leaves
289
+ * the commit state unproven and stays `indeterminate`. The generic D2.2
290
+ * `isRemoteBusinessRefusalCode` is deliberately NOT used: no domain code on this
291
+ * endpoint proves the official save did not run.
292
+ */
293
+ function classifyRemoteDefaultModelFailure(error) {
294
+ const code = remoteFailureCode(error);
295
+ const details = copyFailureDetails(error);
296
+ if (code !== void 0 && (code === "gateway/bad-request" || GATEWAY_PRE_INVOCATION_CODES.has(code))) return {
297
+ kind: "rejected",
298
+ error: {
299
+ code,
300
+ message: settledWriteMessage(code, error),
301
+ ...details === void 0 ? {} : { details }
302
+ }
303
+ };
304
+ return {
305
+ kind: "indeterminate",
306
+ error: {
307
+ code: code ?? "piTuiDefaultModel/indeterminate",
308
+ message: remoteFailureMessage(error),
309
+ ...details === void 0 ? {} : { details }
310
+ }
311
+ };
312
+ }
313
+ /**
314
+ * Classify an official `modelSelection` face value at the trust boundary.
315
+ * The legally unconfigured Session is `{next:null,lastUsed:null}`; an absent
316
+ * face or a malformed record is unknown, never an authorization to substitute
317
+ * the global default. `next` already includes `lastUsed` in normal rc.5
318
+ * producers; the `lastUsed` branch preserves older valid records.
319
+ */
320
+ function projectedSelection(value) {
321
+ if (typeof value !== "object" || value === null) return { kind: "unknown" };
322
+ const record = value;
323
+ if (!("next" in record) || !("lastUsed" in record)) return { kind: "unknown" };
324
+ if (record.next === null) {
325
+ if (record.lastUsed === null) return { kind: "empty" };
326
+ const lastUsed = copySelection(record.lastUsed);
327
+ return lastUsed === void 0 ? { kind: "unknown" } : {
328
+ kind: "selected",
329
+ selection: lastUsed
330
+ };
331
+ }
332
+ const next = copySelection(record.next);
333
+ return next === void 0 ? { kind: "unknown" } : {
334
+ kind: "selected",
335
+ selection: next
336
+ };
337
+ }
338
+ /** The five directory-invalidation events are deliberately one owner. */
339
+ const MODEL_DIRECTORY_EVENTS = [
340
+ "llm/adapters-updated",
341
+ "llm/models-updated",
342
+ "settings/document-updated",
343
+ "credentials/record-updated",
344
+ "credentials/reference-updated"
345
+ ];
346
+ /** The experimental Remote model catalog. */
347
+ var RemoteModelCatalog = class {
348
+ session;
349
+ llm;
350
+ piTuiDefaultModel;
351
+ sessions;
352
+ generation;
353
+ events;
354
+ /** The single Host-generation directory cache. Read publication, event
355
+ * invalidation and reconnect revocation all go through this owner. */
356
+ directoryCache = new GenerationCache(copyDirectory);
357
+ /** Whether the cached directory is a current authoritative value (not a
358
+ * last-known chooser snapshot or an unreadable/unknown default). */
359
+ directoryCurrent = false;
360
+ /** ONE in-flight physical modelCatalog read per Host generation. Explicit
361
+ * callers and the mounted observer share the current generation's read. */
362
+ directoryFlights = /* @__PURE__ */ new Map();
363
+ /** Invalidating a read (event, local write or reconnect) ends its
364
+ * publication right; a burst during a read schedules ONE trailing read. */
365
+ directoryEpoch = 0;
366
+ refreshScheduled;
367
+ directoryListeners = /* @__PURE__ */ new Set();
368
+ directoryScheduler;
369
+ disposeDirectoryEvents;
370
+ disposeGenerationSubscription;
371
+ projectionGeneration;
372
+ disposed = false;
373
+ /** Exact mounted-display proof. Ordinary retained-Session readers do not
374
+ * depend on this UI-runner-owned hydration/refold acknowledgement. */
375
+ displayProof;
376
+ /** Owner token for overlapping same-generation selections (v2 §0.2.5).
377
+ * adapter-global is accepted ONLY under the current single-live-session TUI
378
+ * invariant; if one adapter later serves independently writable concurrent
379
+ * Session surfaces, key the ownership epoch by semantic subject/sessionId. */
380
+ writeEpoch = 0;
381
+ constructor(session, sessions, generation, llm, piTuiDefaultModel, events) {
382
+ this.session = session;
383
+ this.sessions = sessions;
384
+ this.generation = generation;
385
+ this.llm = llm;
386
+ this.piTuiDefaultModel = piTuiDefaultModel;
387
+ this.events = events;
388
+ this.projectionGeneration = generation.getSnapshot();
389
+ this.disposeGenerationSubscription = generation.subscribe(() => {
390
+ const current = generation.getSnapshot();
391
+ if (Object.is(this.projectionGeneration, current)) return;
392
+ this.projectionGeneration = current;
393
+ this.displayProof = void 0;
394
+ if (this.directoryListeners.size > 0) this.invalidateDirectory();
395
+ });
396
+ }
397
+ available() {
398
+ return true;
399
+ }
400
+ async loadDirectory(signal) {
401
+ const captured = this.generation.getSnapshot();
402
+ if (captured === void 0) throw new Error("remote connection is not connected");
403
+ signal?.throwIfAborted();
404
+ const read = this.startDirectoryRead(captured);
405
+ if (signal === void 0) return read;
406
+ let onAbort;
407
+ const aborted = new Promise((_resolve, reject) => {
408
+ onAbort = () => reject(cancellationError("model catalog read aborted"));
409
+ signal.addEventListener("abort", onAbort, { once: true });
410
+ if (signal.aborted) onAbort();
411
+ });
412
+ try {
413
+ return await Promise.race([read, aborted]);
414
+ } finally {
415
+ if (onAbort !== void 0) signal.removeEventListener("abort", onAbort);
416
+ }
417
+ }
418
+ /** Start or join the ONE physical directory read for this generation. */
419
+ startDirectoryRead(captured) {
420
+ const existing = this.directoryFlights.get(captured);
421
+ if (existing !== void 0 && existing.epoch === this.directoryEpoch) return existing.promise;
422
+ const epoch = ++this.directoryEpoch;
423
+ const cacheEpoch = this.directoryCache.beginRead();
424
+ let flight;
425
+ const promise = (async () => {
426
+ try {
427
+ const result = await this.session.modelCatalog();
428
+ if (generationChanged$1(this.generation, captured) || this.disposed) throw new SupersededReadError("remote connection changed while loading the model catalog");
429
+ const stale = () => this.disposed || this.directoryFlights.get(captured) !== flight || flight.epoch !== this.directoryEpoch;
430
+ if (stale()) {
431
+ const newer = this.directoryFlights.get(captured);
432
+ if (newer !== void 0 && newer !== flight) return newer.promise;
433
+ const settled = this.directoryCache.snapshot(this.generation.getSnapshot());
434
+ if (settled !== void 0 && this.directoryCurrent) return settled;
435
+ throw new SupersededReadError("the model catalog read was superseded by a newer request");
436
+ }
437
+ if (!result.ok) {
438
+ this.directoryCurrent = false;
439
+ throw new Error(`session.modelCatalog failed: ${remoteFailureMessage(result.error)}`);
440
+ }
441
+ if (!this.directoryCache.publish(cacheEpoch, captured, result.value)) {
442
+ const newer = this.directoryFlights.get(captured);
443
+ if (newer !== void 0 && newer !== flight) return newer.promise;
444
+ const settled = this.directoryCache.snapshot(this.generation.getSnapshot());
445
+ if (settled !== void 0 && this.directoryCurrent) return settled;
446
+ throw new SupersededReadError("the model catalog read was superseded by a newer request");
447
+ }
448
+ this.directoryCurrent = true;
449
+ const directory = this.directoryCache.snapshot(captured);
450
+ this.notifyDirectoryChanged();
451
+ if (this.directoryFlights.get(captured) === flight && this.directoryCurrent && !this.disposed) return directory;
452
+ const newer = this.directoryFlights.get(captured);
453
+ if (newer !== void 0 && newer !== flight) return newer.promise;
454
+ throw new SupersededReadError("the model catalog read was superseded after publication");
455
+ } finally {
456
+ const ownsCurrentFlight = this.directoryFlights.get(captured) === flight;
457
+ if (ownsCurrentFlight) this.directoryFlights.delete(captured);
458
+ if (ownsCurrentFlight && !this.disposed && Object.is(this.generation.getSnapshot(), captured) && flight.epoch !== this.directoryEpoch && this.directoryFlights.get(captured) === void 0) this.requestDirectoryRefresh();
459
+ }
460
+ })();
461
+ flight = {
462
+ generation: captured,
463
+ epoch,
464
+ promise
465
+ };
466
+ this.directoryFlights.set(captured, flight);
467
+ this.directoryCurrent = false;
468
+ this.notifyDirectoryChanged();
469
+ return promise;
470
+ }
471
+ /** The official Session domain clears every projection store before this
472
+ * adapter's generation callback, so an admitted generation may read the
473
+ * current retained binding without a second observation ledger. */
474
+ projectionCurrent() {
475
+ const current = this.generation.getSnapshot();
476
+ return current !== void 0 && Object.is(current, this.projectionGeneration);
477
+ }
478
+ /** Exact mounted-display proof from the existing fenced hydrate/refold
479
+ * settlement. It never restricts ordinary retained-Session port reads. */
480
+ markSessionCurrent(sessionId) {
481
+ const current = this.generation.getSnapshot();
482
+ if (current === void 0) return;
483
+ const binding = this.sessions.binding(sessionId);
484
+ if (binding === void 0) return;
485
+ this.displayProof = {
486
+ sessionId,
487
+ generation: current,
488
+ binding
489
+ };
490
+ }
491
+ displaySessionSelection(sessionId) {
492
+ const proof = this.displayProof;
493
+ if (proof === void 0 || proof.sessionId !== sessionId || !Object.is(proof.generation, this.generation.getSnapshot()) || !Object.is(proof.binding, this.sessions.binding(sessionId))) return void 0;
494
+ return this.sessionSelection(sessionId);
495
+ }
496
+ /** Narrow synchronous reads never clone the whole model directory. */
497
+ defaultSelection() {
498
+ const current = this.generation.getSnapshot();
499
+ if (current === void 0 || !this.directoryCurrent) return void 0;
500
+ return this.directoryCache.project(current, (directory) => copySelection(directory.default));
501
+ }
502
+ displayEffort(selection) {
503
+ if (selection.reasoningEffort !== void 0) return selection.reasoningEffort;
504
+ const current = this.generation.getSnapshot();
505
+ if (current === void 0 || !this.directoryCurrent) return void 0;
506
+ return this.directoryCache.project(current, (directory) => {
507
+ const effort = directory.groups.find((group) => group.id === selection.provider)?.models.find((model) => model.id === selection.model)?.reasoning?.defaultEffort;
508
+ return typeof effort === "string" && effort !== "" ? effort : void 0;
509
+ });
510
+ }
511
+ /**
512
+ * Persist the sessionless default through the ONE private, Owner-only
513
+ * `piTuiDefaultModel/saveSelection` service (which delegates to the official
514
+ * `agentDefaultModel.saveSelection`). Exactly one dispatch; the Client only
515
+ * maps the settlement, it never retains a second authority.
516
+ */
517
+ async saveDefaultSelection(selection) {
518
+ const next = normalizeModelSelection(selection);
519
+ if (next === void 0) return {
520
+ kind: "rejected",
521
+ error: {
522
+ code: "session/model-invalid",
523
+ message: "invalid model selection"
524
+ }
525
+ };
526
+ const captured = this.generation.getSnapshot();
527
+ if (captured === void 0) return remoteNotDispatched();
528
+ const remotes = this.piTuiDefaultModel;
529
+ if (remotes === void 0) return {
530
+ kind: "rejected",
531
+ error: {
532
+ code: "piTuiDefaultModel/unsupported",
533
+ message: "the Host sessionless default-model service is not mounted"
534
+ }
535
+ };
536
+ const wire = {
537
+ provider: next.provider,
538
+ model: next.model,
539
+ ...next.reasoningEffort === void 0 ? {} : { reasoningEffort: next.reasoningEffort }
540
+ };
541
+ const result = await remotes.saveSelection(wire).catch((error) => ({
542
+ ok: false,
543
+ error
544
+ }));
545
+ let outcome;
546
+ if (!result.ok) outcome = classifyRemoteDefaultModelFailure(result.error);
547
+ else {
548
+ const value = result.value;
549
+ if (value !== void 0 && value.kind === "saved") outcome = {
550
+ kind: "committed",
551
+ value: void 0
552
+ };
553
+ else if (value !== void 0 && value.kind === "refused") outcome = {
554
+ kind: "rejected",
555
+ error: {
556
+ code: `piTuiDefaultModel/${value.reason}`,
557
+ message: DEFAULT_MODEL_REFUSAL_MESSAGES[value.reason]
558
+ }
559
+ };
560
+ else outcome = {
561
+ kind: "indeterminate",
562
+ error: {
563
+ code: "piTuiDefaultModel/result-invalid",
564
+ message: "the Host returned an unusable default-model save result"
565
+ }
566
+ };
567
+ }
568
+ if (!generationChanged$1(this.generation, captured) && (outcome.kind === "committed" || outcome.kind === "indeterminate")) this.invalidateDirectory();
569
+ return outcome;
570
+ }
571
+ sessionSelection(sessionId) {
572
+ if (this.disposed) return void 0;
573
+ const binding = this.sessions.binding(sessionId);
574
+ if (binding === void 0 || !this.projectionCurrent()) return void 0;
575
+ const projected = projectedSelection(binding.session.projections.faceOf("modelSelection").getSnapshot());
576
+ if (projected.kind === "selected") return projected.selection;
577
+ return projected.kind === "empty" ? this.defaultSelection() : void 0;
578
+ }
579
+ async selectSessionModel(sessionId, selection, signal) {
580
+ if (signal?.aborted === true) return {
581
+ ownership: "current",
582
+ outcome: { kind: "cancelled" }
583
+ };
584
+ const captured = this.generation.getSnapshot();
585
+ if (captured === void 0) return {
586
+ ownership: "current",
587
+ outcome: remoteNotDispatched()
588
+ };
589
+ const binding = this.sessions.binding(sessionId);
590
+ if (binding === void 0) return {
591
+ ownership: "current",
592
+ outcome: remoteRejected("session/not-found", `session "${sessionId}" is not available`)
593
+ };
594
+ if (generationChanged$1(this.generation, captured)) return {
595
+ ownership: "current",
596
+ outcome: remoteNotDispatched()
597
+ };
598
+ const epoch = ++this.writeEpoch;
599
+ const result = await this.session.selectModel({
600
+ sessionId,
601
+ provider: selection.provider,
602
+ model: selection.model,
603
+ ...selection.reasoningEffort === void 0 ? {} : { reasoningEffort: selection.reasoningEffort }
604
+ }).catch((error) => ({
605
+ ok: false,
606
+ error
607
+ }));
608
+ const normalized = !result.ok ? void 0 : copySelection(result.value.selected);
609
+ const outcome = !result.ok ? classifyRemoteModelFailure(result.error) : normalized !== void 0 ? {
610
+ kind: "committed",
611
+ value: normalized
612
+ } : {
613
+ kind: "indeterminate",
614
+ error: {
615
+ code: "session/model-result-invalid",
616
+ message: "the Host returned an unusable normalized selection"
617
+ }
618
+ };
619
+ const superseded = generationChanged$1(this.generation, captured) || epoch !== this.writeEpoch || !Object.is(binding, this.sessions.binding(sessionId)) || Boolean(signal?.aborted);
620
+ if (!generationChanged$1(this.generation, captured) && (outcome.kind === "committed" || outcome.kind === "indeterminate")) this.invalidateDirectory();
621
+ return {
622
+ ownership: superseded ? "superseded" : "current",
623
+ outcome
624
+ };
625
+ }
626
+ /** Notify only after the cache/currentness state is committed. */
627
+ notifyDirectoryChanged() {
628
+ for (const listener of [...this.directoryListeners]) listener();
629
+ }
630
+ /** Schedule at most one background read for the CURRENT generation. Events
631
+ * during a physical read mark ONE trailing read; physical settlement owns
632
+ * convergence regardless of who started that read. */
633
+ requestDirectoryRefresh() {
634
+ const captured = this.generation.getSnapshot();
635
+ if (this.disposed || captured === void 0 || this.directoryListeners.size === 0) return;
636
+ if (this.directoryFlights.get(captured) !== void 0) return;
637
+ if (this.refreshScheduled?.generation === captured) return;
638
+ const schedule = this.directoryScheduler;
639
+ if (schedule === void 0) return;
640
+ this.refreshScheduled = { generation: captured };
641
+ schedule("remote model directory refresh", async () => {
642
+ await Promise.resolve();
643
+ if (this.refreshScheduled?.generation !== captured) return;
644
+ this.refreshScheduled = void 0;
645
+ if (this.disposed || !Object.is(this.generation.getSnapshot(), captured) || this.directoryListeners.size === 0) return;
646
+ await this.loadDirectory();
647
+ });
648
+ }
649
+ /** Drop the cached Host-generation directory and every in-flight read's
650
+ * publication right. Local writes and all five Host events share this entry. */
651
+ invalidateDirectory() {
652
+ if (this.disposed) return;
653
+ this.directoryEpoch += 1;
654
+ this.directoryCurrent = false;
655
+ this.directoryCache.invalidate();
656
+ this.notifyDirectoryChanged();
657
+ this.requestDirectoryRefresh();
658
+ }
659
+ /** Activate one mounted-surface observation. Subscriptions are installed
660
+ * BEFORE the initial read, so a synchronous Host notification cannot fall
661
+ * into the subscribe/read gap. */
662
+ subscribeDirectoryChanges(listener, schedule) {
663
+ if (this.disposed) return () => {};
664
+ const first = this.directoryListeners.size === 0;
665
+ this.directoryListeners.add(listener);
666
+ this.directoryScheduler ??= schedule;
667
+ if (first) {
668
+ const invalidate = () => {
669
+ this.invalidateDirectory();
670
+ };
671
+ const disposers = MODEL_DIRECTORY_EVENTS.map((event) => this.events?.$on(event, invalidate));
672
+ this.disposeDirectoryEvents = () => {
673
+ for (const dispose of disposers) dispose?.();
674
+ };
675
+ this.requestDirectoryRefresh();
676
+ }
677
+ return () => {
678
+ this.directoryListeners.delete(listener);
679
+ if (this.directoryListeners.size > 0) return;
680
+ this.disposeDirectoryEvents?.();
681
+ this.disposeDirectoryEvents = void 0;
682
+ this.directoryScheduler = void 0;
683
+ this.refreshScheduled = void 0;
684
+ };
685
+ }
686
+ /** Assembly disposal seam: release every observer and revoke cache/in-flight
687
+ * publication before the Client Context disposal. */
688
+ disposeCache() {
689
+ if (this.disposed) return;
690
+ this.disposed = true;
691
+ this.disposeGenerationSubscription();
692
+ this.disposeDirectoryEvents?.();
693
+ this.disposeDirectoryEvents = void 0;
694
+ this.directoryListeners.clear();
695
+ this.directoryScheduler = void 0;
696
+ this.refreshScheduled = void 0;
697
+ this.directoryEpoch += 1;
698
+ this.directoryCurrent = false;
699
+ this.directoryCache.invalidate();
700
+ this.directoryFlights.clear();
701
+ this.displayProof = void 0;
702
+ }
703
+ async discoverModels(request) {
704
+ if (this.llm === void 0) throw new Error("remote llm namespace is not available");
705
+ const { signal, ...probe } = request;
706
+ signal?.throwIfAborted();
707
+ const captured = this.generation.getSnapshot();
708
+ if (captured === void 0) throw new Error("remote connection is not connected");
709
+ const result = await this.llm.discoverModels(WIZARD_SETTINGS_NS, probe, signal).catch((error) => ({
710
+ ok: false,
711
+ error
712
+ }));
713
+ signal?.throwIfAborted();
714
+ if (generationChanged$1(this.generation, captured)) throw new SupersededReadError("remote connection changed while discovering models");
715
+ if (!result.ok) throw new Error(`llm.discoverModels failed: ${remoteFailureMessage(result.error)}`);
716
+ return result.value.map((model) => ({
717
+ id: model.id,
718
+ ...model.name === void 0 ? {} : { name: model.name }
719
+ }));
720
+ }
721
+ listConfigurableProviders() {}
722
+ };
723
+ //#endregion
724
+ //#region src/runtime/remote/preset-remote.ts
725
+ function generationChanged(generation, captured) {
726
+ return !Object.is(captured, generation.getSnapshot());
727
+ }
728
+ function copyRosterEntry(row) {
729
+ return {
730
+ id: row.id,
731
+ ...row.name === void 0 ? {} : { name: row.name },
732
+ ...row.description === void 0 ? {} : { description: row.description },
733
+ ...row.broken === void 0 ? {} : { broken: row.broken }
734
+ };
735
+ }
736
+ /** Detach a roster DTO for cache storage or for a caller. */
737
+ function copyRoster(roster) {
738
+ return {
739
+ presets: roster.presets.map(copyRosterEntry),
740
+ ...roster.defaultId === void 0 ? {} : { defaultId: roster.defaultId }
741
+ };
742
+ }
743
+ /**
744
+ * Operation-specific settlement for `agentPresets.select`. Only an EXACT
745
+ * proven pre-commit refusal (`agent-preset/locked`, `agent-preset/not-found`,
746
+ * `agent-preset/invalid`, `session/not-found`, `session/agent-busy`,
747
+ * `session/writer-held`, `gateway/bad-request`, a pre-invocation Gateway code)
748
+ * is `rejected`; anything else is `indeterminate`. The D2.2 broad refusal
749
+ * helper is deliberately NOT used and no namespace prefix is treated as proof.
750
+ *
751
+ * `session/not-found`/`session/agent-busy`/`session/writer-held` are proven
752
+ * because the pinned Host resolves the Agent via `resolveAgent()` BEFORE
753
+ * `agentPresets.select` enters its mutation (§0.7.2). `gateway/internal` stays
754
+ * indeterminate: it is too broad to prove no preset mutation happened.
755
+ *
756
+ * This classifier only ever runs AFTER dispatch, so a cancellation code is
757
+ * likewise `indeterminate` (§0.2.4); pre-dispatch cancellation is
758
+ * `remoteNotDispatched()`.
759
+ */
760
+ function classifyRemotePresetFailure(error) {
761
+ const code = remoteFailureCode(error);
762
+ const details = copyFailureDetails(error);
763
+ if (code !== void 0 && (code === "gateway/bad-request" || code === "session/not-found" || code === "session/agent-busy" || code === "session/writer-held" || REMOTE_PRESET_REFUSAL_CODES.has(code) || GATEWAY_PRE_INVOCATION_CODES.has(code))) return {
764
+ kind: "rejected",
765
+ error: {
766
+ code,
767
+ message: settledWriteMessage(code, error),
768
+ ...details === void 0 ? {} : { details }
769
+ }
770
+ };
771
+ return {
772
+ kind: "indeterminate",
773
+ error: {
774
+ code: code ?? "agent-preset/select-indeterminate",
775
+ message: remoteFailureMessage(error),
776
+ ...details === void 0 ? {} : { details }
777
+ }
778
+ };
779
+ }
780
+ /** The exact official preset-switch refusal codes (`agentPresets.select`). */
781
+ const REMOTE_PRESET_REFUSAL_CODES = /* @__PURE__ */ new Set([
782
+ "agent-preset/locked",
783
+ "agent-preset/not-found",
784
+ "agent-preset/invalid"
785
+ ]);
786
+ /** The experimental Remote preset catalog. */
787
+ var RemotePresetCatalog = class {
788
+ presets;
789
+ generation;
790
+ /** The last loaded Host roster (default + rows), generation-tagged,
791
+ * latest-read-wins, detached on read AND write. */
792
+ rosterCache = new GenerationCache(copyRoster);
793
+ /** Assembly disposal seam: drop the cached roster (and any in-flight
794
+ * read's publication right) before the Client Context disposal. */
795
+ disposeCache() {
796
+ this.rosterCache.invalidate();
797
+ }
798
+ /** Owner token for overlapping same-generation preset selections (v2 §0.2.5).
799
+ * adapter-global is accepted ONLY under the current single-live-session TUI
800
+ * invariant; if one adapter later serves independently writable concurrent
801
+ * Session surfaces, key the ownership epoch by semantic subject/sessionId. */
802
+ writeEpoch = 0;
803
+ constructor(presets, generation) {
804
+ this.presets = presets;
805
+ this.generation = generation;
806
+ }
807
+ available() {
808
+ return true;
809
+ }
810
+ async roster(signal) {
811
+ const captured = this.generation.getSnapshot();
812
+ if (captured === void 0) throw new Error("remote connection is not connected");
813
+ signal?.throwIfAborted();
814
+ const epoch = this.rosterCache.beginRead();
815
+ const result = await this.presets.list();
816
+ if (generationChanged(this.generation, captured)) throw new SupersededReadError("remote connection changed while loading the preset roster");
817
+ signal?.throwIfAborted();
818
+ if (!result.ok) throw new Error(`agentPresets.list failed: ${remoteFailureMessage(result.error)}`);
819
+ const defaultId = result.value.presets.find((preset) => preset.isDefault === true)?.id;
820
+ const dto = {
821
+ presets: result.value.presets.map(copyRosterEntry),
822
+ ...defaultId === void 0 ? {} : { defaultId }
823
+ };
824
+ if (!this.rosterCache.publish(epoch, captured, dto)) {
825
+ const newer = this.rosterCache.snapshot(this.generation.getSnapshot());
826
+ if (newer !== void 0) return newer;
827
+ throw new SupersededReadError("the preset roster read was superseded by a newer request");
828
+ }
829
+ return this.rosterCache.snapshot(captured);
830
+ }
831
+ async resolve(id, signal) {
832
+ const roster = await this.roster(signal);
833
+ const wanted = id ?? roster.defaultId;
834
+ if (wanted === void 0) return {};
835
+ const found = roster.presets.find((preset) => preset.id === wanted);
836
+ if (found === void 0) throw new Error(`preset "${wanted}" not found (available: ${roster.presets.map((preset) => preset.id).join(", ") || "none"})`);
837
+ return { id: found.id };
838
+ }
839
+ defaultId() {
840
+ return this.rosterCache.snapshot(this.generation.getSnapshot())?.defaultId;
841
+ }
842
+ async selectSessionPreset(sessionId, presetId, signal) {
843
+ if (signal?.aborted === true) return {
844
+ ownership: "current",
845
+ outcome: { kind: "cancelled" }
846
+ };
847
+ const captured = this.generation.getSnapshot();
848
+ if (captured === void 0) return {
849
+ ownership: "current",
850
+ outcome: remoteNotDispatched()
851
+ };
852
+ if (generationChanged(this.generation, captured)) return {
853
+ ownership: "current",
854
+ outcome: remoteNotDispatched()
855
+ };
856
+ const epoch = ++this.writeEpoch;
857
+ const result = await this.presets.select(sessionId, presetId).catch((error) => ({
858
+ ok: false,
859
+ error
860
+ }));
861
+ const outcome = result.ok ? typeof result.value === "string" && result.value !== "" ? {
862
+ kind: "committed",
863
+ value: { preset: result.value }
864
+ } : {
865
+ kind: "indeterminate",
866
+ error: {
867
+ code: "agent-preset/select-result-invalid",
868
+ message: "the Host returned an unusable preset id"
869
+ }
870
+ } : classifyRemotePresetFailure(result.error);
871
+ return {
872
+ ownership: generationChanged(this.generation, captured) || epoch !== this.writeEpoch || Boolean(signal?.aborted) ? "superseded" : "current",
873
+ outcome
874
+ };
875
+ }
876
+ };
877
+ //#endregion
878
+ //#region src/runtime/remote/task-read-remote.ts
879
+ function generationMatches(generation, captured) {
880
+ return Object.is(captured, generation.getSnapshot());
881
+ }
882
+ function detachDiagnostic(id, reason, parentId, depth) {
883
+ return Object.freeze({
884
+ kind: "diagnostic",
885
+ id,
886
+ reason,
887
+ parentId,
888
+ depth
889
+ });
890
+ }
891
+ function detachJob(job) {
892
+ return Object.freeze({
893
+ id: job.id,
894
+ kind: job.kind,
895
+ label: job.label,
896
+ status: job.status,
897
+ ...job.detail === void 0 ? {} : { detail: job.detail },
898
+ startedAt: job.startedAt,
899
+ ...job.finishedAt === void 0 ? {} : { finishedAt: job.finishedAt }
900
+ });
901
+ }
902
+ /**
903
+ * The official `joinAgentPath` semantics (dsh-subagent/names): the root's path
904
+ * is `''`, a child of the root is its own name, a deeper child is
905
+ * `${parentPath}/${name}`, and ANY undefined link (unnamed child or unnamed
906
+ * ancestor) makes the whole path undefined. Never fabricated.
907
+ */
908
+ function joinAgentPath(parentPath, name) {
909
+ if (parentPath === void 0 || name === void 0) return void 0;
910
+ return parentPath === "" ? name : `${parentPath}/${name}`;
911
+ }
912
+ /**
913
+ * Read the full descendant catalog, the parent availability fact, and the
914
+ * status-only job roster of one session. The roster watch is retained across
915
+ * reads for the SAME parent and switches atomically when the read targets
916
+ * another session.
917
+ */
918
+ var RemoteTaskReader = class {
919
+ sessions;
920
+ jobs;
921
+ generation;
922
+ releaseWatch;
923
+ watchedSession;
924
+ /** Reader-local operation epoch (§6.9 stale-fencing): bumped by every
925
+ * read start and by dispose, so a read superseded by a newer read (any
926
+ * parent), a session switch, or reader disposal can never return its
927
+ * snapshot — the connection generation fence alone cannot see those. */
928
+ operationEpoch = 0;
929
+ constructor(sessions, jobs, generation) {
930
+ this.sessions = sessions;
931
+ this.jobs = jobs;
932
+ this.generation = generation;
933
+ }
934
+ /** Release the retained roster watch and invalidate every in-flight
935
+ * read; safe to call more than once. The reader itself stays usable — a
936
+ * later read re-opens a watch under a fresh epoch. */
937
+ dispose() {
938
+ this.operationEpoch += 1;
939
+ this.releaseWatch?.();
940
+ this.releaseWatch = void 0;
941
+ this.watchedSession = void 0;
942
+ }
943
+ ensureWatch(parentSessionId) {
944
+ if (this.watchedSession === parentSessionId && this.releaseWatch !== void 0) return;
945
+ const previous = this.releaseWatch;
946
+ const successor = this.jobs.watchRows(parentSessionId);
947
+ this.releaseWatch = successor;
948
+ this.watchedSession = parentSessionId;
949
+ previous?.();
950
+ }
951
+ /** §6.9 fencing: this read is current only while no newer read/dispose
952
+ * bumped the epoch AND the Connection generation it captured is live. */
953
+ isCurrent(capturedGeneration, epoch) {
954
+ return this.operationEpoch === epoch && generationMatches(this.generation, capturedGeneration);
955
+ }
956
+ /**
957
+ * Read one session's settled durable catalog. A missing, idle, or loading
958
+ * projection is NEVER an authoritative empty membership, so the read
959
+ * re-enters the official single-flight `refreshProjections` until the
960
+ * projection settles. Two settled failure shapes are handled explicitly:
961
+ *
962
+ * - `state === 'error'`: the official `refreshProjections` is the released
963
+ * RETRY face (it short-circuits only on a settled `ready`), so this read
964
+ * re-enters it ONCE before giving up — otherwise one transient failure would
965
+ * turn every later read (including the Task Center's own retry) into a
966
+ * permanent failure;
967
+ * - `state === 'migration-required'` (0.2.1-rc.1): the Session needs an official
968
+ * migration before its projections can be read. Settled and NOT an
969
+ * authoritative catalog, so this read fails closed with a named error
970
+ * rather than reporting an empty membership (the fuller migration UX
971
+ * belongs to the Session-migration stage);
972
+ * - `state === 'ready'` WITHOUT `subagentCatalog`: the official Client clears
973
+ * the projection store and still settles `ready` when `session.projections`
974
+ * answers a null/missing Session, so this is a REAL read failure — exactly
975
+ * the one upstream `listChildren` reports as
976
+ * `SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE`. It must never read as an
977
+ * authoritative empty catalog (root) or as a normal inactive child (branch).
978
+ *
979
+ * Returns `undefined` when this read was superseded or the Connection
980
+ * generation changed.
981
+ */
982
+ async readCatalog(sessionId, capturedGeneration, epoch, signal) {
983
+ let retriedOnError = false;
984
+ for (;;) {
985
+ signal?.throwIfAborted();
986
+ if (!this.isCurrent(capturedGeneration, epoch)) return void 0;
987
+ const projection = this.sessions.list.getSnapshot().projectionsBySession[sessionId];
988
+ const state = projection === void 0 ? "loading" : projection.state === "idle" ? projection.values.subagentCatalog === void 0 ? "loading" : "ready" : projection.state;
989
+ if (state === "error") {
990
+ if (retriedOnError) throw projection?.error;
991
+ retriedOnError = true;
992
+ try {
993
+ await this.sessions.refreshProjections(sessionId);
994
+ } catch (error) {
995
+ signal?.throwIfAborted();
996
+ if (!this.isCurrent(capturedGeneration, epoch)) return void 0;
997
+ throw error;
998
+ }
999
+ continue;
1000
+ }
1001
+ if (state === "loading") {
1002
+ try {
1003
+ await this.sessions.refreshProjections(sessionId);
1004
+ } catch (error) {
1005
+ signal?.throwIfAborted();
1006
+ if (!this.isCurrent(capturedGeneration, epoch)) return void 0;
1007
+ throw error;
1008
+ }
1009
+ continue;
1010
+ }
1011
+ if (state === "migration-required") throw new Error(`the subagentCatalog projection requires an official migration for Session ${sessionId}`);
1012
+ const entries = projection.values.subagentCatalog;
1013
+ if (entries === void 0) throw new Error(`the subagentCatalog projection is unavailable for Session ${sessionId}`);
1014
+ return entries;
1015
+ }
1016
+ }
1017
+ async readDescendants(parentSessionId, signal) {
1018
+ signal?.throwIfAborted();
1019
+ const epoch = ++this.operationEpoch;
1020
+ const capturedGeneration = this.generation.getSnapshot();
1021
+ if (capturedGeneration === void 0) return void 0;
1022
+ this.ensureWatch(parentSessionId);
1023
+ const rootEntries = await this.readCatalog(parentSessionId, capturedGeneration, epoch, signal);
1024
+ if (rootEntries === void 0) return void 0;
1025
+ const stack = rootEntries.map((entry) => ({
1026
+ entry,
1027
+ parentId: parentSessionId,
1028
+ depth: 1,
1029
+ parentPath: ""
1030
+ })).reverse();
1031
+ const visited = /* @__PURE__ */ new Set([parentSessionId]);
1032
+ const descendants = [];
1033
+ for (let position = stack.pop(); position !== void 0; position = stack.pop()) {
1034
+ signal?.throwIfAborted();
1035
+ if (!this.isCurrent(capturedGeneration, epoch)) return void 0;
1036
+ const { entry, parentId, depth, parentPath } = position;
1037
+ if (visited.has(entry.id)) continue;
1038
+ visited.add(entry.id);
1039
+ const path = joinAgentPath(parentPath, entry.name);
1040
+ let children;
1041
+ try {
1042
+ children = await this.readCatalog(entry.id, capturedGeneration, epoch, signal);
1043
+ } catch (error) {
1044
+ signal?.throwIfAborted();
1045
+ if (!this.isCurrent(capturedGeneration, epoch)) return void 0;
1046
+ const code = error instanceof Error && "code" in error ? error.code : void 0;
1047
+ descendants.push(detachDiagnostic(entry.id, code === "SESSION_QUERY_CORRUPT_SESSION" || code === "SESSION_QUERY_SOURCE_CONFLICT" ? "corrupt" : "unavailable", parentId, depth));
1048
+ continue;
1049
+ }
1050
+ if (children === void 0) return void 0;
1051
+ if (entry.mode === "unknown") descendants.push(detachDiagnostic(entry.id, "unsupported", parentId, depth));
1052
+ else descendants.push(Object.freeze({
1053
+ kind: "child",
1054
+ id: entry.id,
1055
+ ...entry.label === void 0 ? {} : { label: entry.label },
1056
+ mode: entry.mode,
1057
+ activity: this.sessions.list.getSnapshot().byId[entry.id]?.running === true ? "running" : "inactive",
1058
+ hasChildren: children.length > 0,
1059
+ parentId,
1060
+ depth,
1061
+ ...path === void 0 ? {} : { path }
1062
+ }));
1063
+ for (const child of [...children].reverse()) stack.push({
1064
+ entry: child,
1065
+ parentId: entry.id,
1066
+ depth: depth + 1,
1067
+ parentPath: path
1068
+ });
1069
+ }
1070
+ if (!this.isCurrent(capturedGeneration, epoch)) return void 0;
1071
+ const parentAvailable = this.sessions.list.getSnapshot().byId[parentSessionId] !== void 0;
1072
+ const jobs = Object.freeze((this.jobs.state.getSnapshot().rows[parentSessionId] ?? []).map(detachJob));
1073
+ if (!this.isCurrent(capturedGeneration, epoch)) return void 0;
1074
+ return Object.freeze({
1075
+ parentSessionId,
1076
+ parentAvailable,
1077
+ descendants: Object.freeze(descendants),
1078
+ jobs
1079
+ });
1080
+ }
1081
+ };
1082
+ //#endregion
1083
+ export { classifyRemoteModelFailure as a, RemoteModelCatalog as i, RemotePresetCatalog as n, RemoteFileUploadError as o, classifyRemotePresetFailure as r, createRemoteFileReceiptUploader as s, RemoteTaskReader as t };