@xmoon76/dsh-pi-tui 0.5.8 → 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 (77) hide show
  1. package/README.en.md +61 -25
  2. package/README.md +61 -25
  3. package/cordis.patch.yml +13 -0
  4. package/dist/acp-stdio.mjs +151 -0
  5. package/dist/{bootstrap-CMIjGyuk.mjs → bootstrap-CVyHGQDX.mjs} +21901 -6575
  6. package/dist/browser-CDUSHIIr.mjs +76 -0
  7. package/dist/builtins.mjs +2 -2
  8. package/dist/{client-bootstrap-BjGPc-DM.mjs → client-bootstrap-4UoeVIHE.mjs} +2488 -2734
  9. package/dist/client-runtime-BHBlVUf5.mjs +1376 -0
  10. package/dist/{daemon-launcher-Dult7Jxv.mjs → daemon-launcher-DxIgjBHW.mjs} +1549 -172
  11. package/dist/daemon-launcher.d.mts +85 -14
  12. package/dist/daemon-launcher.mjs +2 -2
  13. package/dist/{local-profile-daemon-admin-BmQSdzT0.mjs → diagnostics-Db5iVcuJ.mjs} +3 -90
  14. package/dist/{entry-control-DjNsE3I0.mjs → entry-control-BDLZgg4m.mjs} +1 -1
  15. package/dist/{extensions-B4uLpSTv.mjs → extensions-Dx7ncPNA.mjs} +1 -1
  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-DMNTmNrH.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 +22334 -6695
  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 +292 -63
  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-uOBfFq5j.mjs → local-discovery-BMhaGIiJ.mjs} +254 -544
  38. package/dist/{local-discovery-egN4_gsQ.mjs → local-discovery-Ba7_-NNC.mjs} +1 -1
  39. package/dist/{local-discovery-DOSsCh9q.mjs → local-discovery-QSbFpjK2.mjs} +301 -544
  40. package/dist/local-host.mjs +952 -501
  41. package/dist/local-profile-daemon-admin-otpm69R6.mjs +469 -0
  42. package/dist/{local-scope-DamiMqPd.mjs → local-scope-5DEKA_lW.mjs} +1023 -96
  43. package/dist/{local-transport-Iwo0mtu3.mjs → local-transport-DeWmdZ5E.mjs} +14 -3
  44. package/dist/{local-web-control-DMrjwCkl.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-C6tSs86s.mjs → session-Cs8iLCEx.mjs} +784 -342
  62. package/dist/{session-CstInGIA.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-EG5UqIcd.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-CpfpQO_h.mjs → terminal-progress-source-VsczdXA-.mjs} +610 -332
  70. package/dist/{transcript-view-CuJYWkhp.mjs → transcript-view-B6vCnukn.mjs} +2096 -977
  71. package/dist/{transcript-view-C1YtJ49Y.mjs → transcript-view-DSSdE2vK.mjs} +2078 -651
  72. package/dist/write-failure-xNKczXH7.mjs +189 -0
  73. package/package.json +20 -3
  74. package/dist/local-acp-listener-B65J0Bx4.mjs +0 -3115
  75. package/dist/local-daemon-control-C14q9KnD.mjs +0 -1588
  76. package/dist/local-daemon-control-TCnERL7n.mjs +0 -1424
  77. package/dist/preset-BcWqOtY7.mjs +0 -46
@@ -0,0 +1,3534 @@
1
+ import { d as installedPackageRootFromEntry, p as readInstalledDshVersion, u as inspectInstalledProfileScope } from "./local-scope-5DEKA_lW.mjs";
2
+ import { t as publishedSessionIdOfCreateError } from "./session-create-facts-CkfG5DpQ.mjs";
3
+ import { a as runOwned, i as runDetached, o as safeErrorMessage, r as observeSettled } from "./tasks-D_z5Yjjr.mjs";
4
+ import { i as authenticateLocalHost, l as inspectHostProcess, p as readLocalRecord, r as assertRecordedHostKernelIdentityCurrent, t as assertClientHostCompatible } from "./local-discovery-QSbFpjK2.mjs";
5
+ import { t as mergeCause } from "./dispose-cause-CNFuUnjR.mjs";
6
+ import { t as createDiag } from "./diagnostics-Db5iVcuJ.mjs";
7
+ import { a as classifyRemoteModelFailure, r as classifyRemotePresetFailure, s as createRemoteFileReceiptUploader, t as RemoteTaskReader } from "./task-read-remote-DRtkXDrZ.mjs";
8
+ import { a as remoteFailureMessage, i as remoteFailureCode, l as GATEWAY_PRE_INVOCATION_CODES, t as classifyRemoteWriteFailure, u as isRemoteBusinessRefusalCode } from "./write-failure-xNKczXH7.mjs";
9
+ import { createRequire } from "node:module";
10
+ import { randomUUID } from "node:crypto";
11
+ import { readFileSync, realpathSync } from "node:fs";
12
+ import { isAbsolute, join } from "node:path";
13
+ import { pathToFileURL } from "node:url";
14
+ //#region src/app/remote-process/native-client-continued.ts
15
+ /**
16
+ * One exact-binding/native-callId owner. Both official question and inbox
17
+ * faces are live inputs; revocation always precedes any new offer.
18
+ */
19
+ function createNativeContinuedQuestionReceiver(options) {
20
+ let disposed = false;
21
+ const watched = /* @__PURE__ */ new Map();
22
+ const deliveries = /* @__PURE__ */ new Map();
23
+ const keyOf = (sessionId, callId) => `${sessionId}\u0000${callId}`;
24
+ const currentBindingHandle = (sessionId, binding) => [...options.handlesBySession.get(sessionId) ?? []].find((handle) => !handle.isClosed && handle.bindingIdentity() === binding && handle.isCurrentBinding());
25
+ const revokeInvalid = () => {
26
+ for (const [key, reservation] of deliveries) {
27
+ const handle = currentBindingHandle(reservation.sessionId, reservation.binding);
28
+ if (!options.isClosed() && !disposed && handle !== void 0 && Object.is(reservation.generation, options.generation.getSnapshot()) && handle.continuedEligible(reservation.callId)) continue;
29
+ deliveries.delete(key);
30
+ reservation.controller.abort(/* @__PURE__ */ new Error("native-client: continued Question ownership revoked"));
31
+ }
32
+ };
33
+ const offerContinued = (handle, callId, questions) => {
34
+ if (disposed || options.isClosed()) return;
35
+ const binding = handle.bindingIdentity();
36
+ const key = keyOf(handle.sessionId, callId);
37
+ if (deliveries.has(key)) return;
38
+ const generation = options.generation.getSnapshot();
39
+ if (generation === void 0 || !handle.continuedEligible(callId)) return;
40
+ const reservation = {
41
+ sessionId: handle.sessionId,
42
+ binding,
43
+ callId,
44
+ generation,
45
+ controller: new AbortController()
46
+ };
47
+ deliveries.set(key, reservation);
48
+ if (!options.onOffer(reservation, callId, questions) || disposed) {
49
+ if (deliveries.get(key) === reservation) deliveries.delete(key);
50
+ reservation.controller.abort(/* @__PURE__ */ new Error("native-client: continued Question delivery was not started"));
51
+ }
52
+ };
53
+ const reconcileHandle = (handle) => {
54
+ if (disposed || options.isClosed() || handle.isClosed) return;
55
+ revokeInvalid();
56
+ let calls;
57
+ try {
58
+ calls = handle.continuedCalls();
59
+ } catch (error) {
60
+ options.onInvalidProjection(error);
61
+ return;
62
+ }
63
+ for (const call of calls) if (call.state === "continued") offerContinued(handle, call.callId, call.questions);
64
+ };
65
+ const reconcileAll = () => {
66
+ revokeInvalid();
67
+ for (const handle of options.handles) reconcileHandle(handle);
68
+ };
69
+ const watchHandle = (handle) => {
70
+ if (watched.has(handle)) return;
71
+ watched.set(handle, () => {});
72
+ watched.set(handle, handle.observeOfficialQuestionFacts(() => {
73
+ reconcileHandle(handle);
74
+ }));
75
+ };
76
+ const syncHandles = () => {
77
+ for (const [handle, off] of watched) {
78
+ if (!handle.isClosed) continue;
79
+ off();
80
+ watched.delete(handle);
81
+ }
82
+ for (const handle of options.handles) watchHandle(handle);
83
+ reconcileAll();
84
+ };
85
+ const offGeneration = options.generation.subscribe(() => {
86
+ revokeInvalid();
87
+ });
88
+ options.handleListeners.add(syncHandles);
89
+ syncHandles();
90
+ return {
91
+ reconcile() {
92
+ if (!disposed) reconcileAll();
93
+ },
94
+ dispose() {
95
+ if (disposed) return;
96
+ disposed = true;
97
+ offGeneration();
98
+ options.handleListeners.delete(syncHandles);
99
+ for (const off of watched.values()) off();
100
+ watched.clear();
101
+ for (const reservation of deliveries.values()) reservation.controller.abort(/* @__PURE__ */ new Error("native-client: interaction receivers disposed"));
102
+ deliveries.clear();
103
+ }
104
+ };
105
+ }
106
+ //#endregion
107
+ //#region src/app/remote-process/native-client-operations.ts
108
+ /** Await one owned operation under a caller lifetime without orphaning it. */
109
+ function abortable(operation, signal) {
110
+ if (signal.aborted) {
111
+ observeSettled(operation, () => {});
112
+ return Promise.reject(signal.reason);
113
+ }
114
+ return new Promise((resolve, reject) => {
115
+ const abort = () => {
116
+ cleanup();
117
+ reject(signal.reason);
118
+ };
119
+ const cleanup = () => signal.removeEventListener("abort", abort);
120
+ signal.addEventListener("abort", abort, { once: true });
121
+ operation.then((value) => {
122
+ cleanup();
123
+ resolve(value);
124
+ }, (error) => {
125
+ cleanup();
126
+ reject(error);
127
+ });
128
+ });
129
+ }
130
+ //#endregion
131
+ //#region src/app/remote-process/native-client-prompt.ts
132
+ function record(value, label) {
133
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${label}: expected an object`);
134
+ return value;
135
+ }
136
+ function message(value) {
137
+ const entry = record(value, "prompt message");
138
+ if (typeof entry.id !== "string" || entry.id === "") throw new TypeError("prompt message: invalid id");
139
+ return {
140
+ id: entry.id,
141
+ source: entry.source
142
+ };
143
+ }
144
+ function eventMessages(event) {
145
+ if (event.type === "user/message") return [message(event.data)];
146
+ if (event.type !== "agent/inbox/spliced") return [];
147
+ const inserted = record(event.data, "inbox splice").inserted;
148
+ if (!Array.isArray(inserted)) throw new TypeError("inbox splice: invalid inserted array");
149
+ return inserted.map(message);
150
+ }
151
+ function requestIdOfMessage(message) {
152
+ if (typeof message.source !== "object" || message.source === null || Array.isArray(message.source)) return void 0;
153
+ const source = message.source;
154
+ if (source.kind !== "user" && source.kind !== "retry") return void 0;
155
+ return typeof source.rpcId === "string" && source.rpcId !== "" ? source.rpcId : void 0;
156
+ }
157
+ function inboxTarget(event) {
158
+ const target = record(event.data, "inbox splice").target;
159
+ if (target !== "next-turn" && target !== "next-step") throw new TypeError("inbox splice: invalid target");
160
+ return target;
161
+ }
162
+ function turnStep(events, userSeq) {
163
+ let turn;
164
+ let step;
165
+ for (const event of events) {
166
+ if (event.seq >= userSeq) break;
167
+ if (event.type === "turn/start") {
168
+ const value = record(event.data, "turn start").turn;
169
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError("turn start: invalid turn");
170
+ turn = value;
171
+ step = void 0;
172
+ } else if (event.type === "step/start" && turn !== void 0) {
173
+ const data = record(event.data, "step start");
174
+ if (data.turn !== turn) continue;
175
+ if (typeof data.step !== "number" || !Number.isSafeInteger(data.step)) throw new TypeError("step start: invalid step");
176
+ step = data.step;
177
+ }
178
+ }
179
+ return {
180
+ ...turn === void 0 ? {} : { turn },
181
+ ...step === void 0 ? {} : { step }
182
+ };
183
+ }
184
+ /** Fold one complete, chronological fixed-cut sample into official prompt evidence. */
185
+ function promptResolutionOf(events, requestId) {
186
+ let inheritedCut = -1;
187
+ for (const event of events) {
188
+ if (event.type !== "session/end-seed") continue;
189
+ if (record(event.data, "session end-seed").inherited === true) inheritedCut = event.seq;
190
+ }
191
+ const inheritedMessages = /* @__PURE__ */ new Set();
192
+ for (const event of events) {
193
+ if (event.seq > inheritedCut) continue;
194
+ for (const entry of eventMessages(event)) inheritedMessages.add(entry.id);
195
+ }
196
+ const occurrences = /* @__PURE__ */ new Map();
197
+ for (const event of events) {
198
+ if (event.seq <= inheritedCut) continue;
199
+ if (event.type === "user/message" && event.surfaceOp !== void 0 && event.surfaceOp !== "append" && event.surfaceOp.op === "replace") continue;
200
+ const messages = eventMessages(event);
201
+ if (messages.length === 0) continue;
202
+ for (const entry of messages) {
203
+ if (inheritedMessages.has(entry.id) || requestIdOfMessage(entry) !== requestId) continue;
204
+ const value = event.type === "user/message" ? {
205
+ source: "user-message",
206
+ requestId,
207
+ messageId: entry.id,
208
+ seq: event.seq,
209
+ ...turnStep(events, event.seq)
210
+ } : {
211
+ source: "inbox-insertion",
212
+ requestId,
213
+ messageId: entry.id,
214
+ target: inboxTarget(event),
215
+ seq: event.seq
216
+ };
217
+ const current = occurrences.get(entry.id);
218
+ if (current === void 0 || current.value.source === "inbox-insertion" && value.source === "user-message") occurrences.set(entry.id, {
219
+ seq: event.seq,
220
+ value
221
+ });
222
+ }
223
+ }
224
+ let selected;
225
+ for (const occurrence of occurrences.values()) if (selected === void 0 || occurrence.seq < selected.seq) selected = occurrence;
226
+ return selected?.value;
227
+ }
228
+ //#endregion
229
+ //#region src/app/remote-process/native-client-realm.ts
230
+ /**
231
+ * One Native Client composition per Node realm.
232
+ *
233
+ * The reservation is process-local and is created before any installed-runtime
234
+ * import, discovery read, authentication or Context construction. It is not a
235
+ * Host lock and says nothing about another process; it only prevents two public
236
+ * headless compositions from racing in the same realm.
237
+ */
238
+ const REALM_STATE_KEY = Symbol.for("@xmoon76/dsh-pi-tui/native-client-realm");
239
+ const realm = globalThis;
240
+ const realmState = realm[REALM_STATE_KEY] ??= {};
241
+ function reserveNativeClientRealm() {
242
+ if (realmState.activeReservation !== void 0) throw Object.assign(/* @__PURE__ */ new Error("native-client: another attach is active in this Node realm"), { code: "NATIVE_CLIENT_REALM_BUSY" });
243
+ const token = Symbol("native-client-realm");
244
+ realmState.activeReservation = token;
245
+ let released = false;
246
+ return () => {
247
+ if (released) return;
248
+ released = true;
249
+ if (realmState.activeReservation === token) realmState.activeReservation = void 0;
250
+ };
251
+ }
252
+ /** Release the realm only after the caller's Client-owned cleanup has settled successfully. */
253
+ async function completeNativeClientRealm(release, cleanup) {
254
+ await cleanup();
255
+ release();
256
+ }
257
+ //#endregion
258
+ //#region src/app/remote-process/native-client-workspace.ts
259
+ function closedResult$1() {
260
+ return {
261
+ kind: "closed",
262
+ code: "NATIVE_CLIENT_CLOSED",
263
+ message: "The Native Client is closed."
264
+ };
265
+ }
266
+ function staleResult$1() {
267
+ return {
268
+ kind: "stale",
269
+ code: "NATIVE_GENERATION_STALE",
270
+ message: "The result belongs to a replaced Connection generation."
271
+ };
272
+ }
273
+ function workspaceSummaryOf(value) {
274
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("workspace row: expected an object");
275
+ const row = value;
276
+ if (typeof row.workspaceId !== "string" || row.workspaceId === "" || typeof row.path !== "string" || row.path === "" || typeof row.title !== "string" || !Array.isArray(row.sessionIds) || row.sessionIds.some((sessionId) => typeof sessionId !== "string" || sessionId === "")) throw new TypeError("workspace row: incomplete official baseline");
277
+ return {
278
+ workspaceId: row.workspaceId,
279
+ path: row.path,
280
+ title: row.title,
281
+ sessionIds: [...row.sessionIds]
282
+ };
283
+ }
284
+ /** Read exactly one official baseline, including actual iterator teardown. */
285
+ async function readNativeWorkspaceBaseline(source, classifyReadFailure) {
286
+ if (source.isClosed()) return closedResult$1();
287
+ const captured = source.generation.getSnapshot();
288
+ if (captured === void 0) return {
289
+ kind: "unavailable",
290
+ code: "NATIVE_DISCONNECTED",
291
+ message: "No authenticated Host generation is current."
292
+ };
293
+ const controller = new AbortController();
294
+ const signal = AbortSignal.any([source.lifetime, controller.signal]);
295
+ let invalidated = false;
296
+ const unsubscribe = source.generation.subscribe(() => {
297
+ if (Object.is(captured, source.generation.getSnapshot())) return;
298
+ invalidated = true;
299
+ controller.abort(/* @__PURE__ */ new Error("native-client: Workspace read generation changed"));
300
+ });
301
+ let candidate = { kind: "unavailable" };
302
+ try {
303
+ if (source.isClosed()) candidate = { kind: "closed" };
304
+ else if (!Object.is(captured, source.generation.getSnapshot())) candidate = { kind: "stale" };
305
+ else {
306
+ let stream;
307
+ try {
308
+ stream = source.follow(signal);
309
+ } catch (error) {
310
+ candidate = {
311
+ kind: "error",
312
+ error
313
+ };
314
+ }
315
+ if (stream !== void 0) try {
316
+ for await (const frame of stream) {
317
+ if (source.isClosed()) {
318
+ candidate = { kind: "closed" };
319
+ break;
320
+ }
321
+ if (invalidated || !Object.is(captured, source.generation.getSnapshot())) {
322
+ candidate = { kind: "stale" };
323
+ break;
324
+ }
325
+ const baseline = frame?.value;
326
+ if (typeof frame !== "object" || frame === null || frame.type !== "baseline" || typeof baseline !== "object" || baseline === null || !Array.isArray(baseline.items)) {
327
+ candidate = { kind: "invalid" };
328
+ break;
329
+ }
330
+ try {
331
+ candidate = {
332
+ kind: "ok",
333
+ value: baseline.items.map(workspaceSummaryOf)
334
+ };
335
+ } catch {
336
+ candidate = { kind: "invalid" };
337
+ }
338
+ break;
339
+ }
340
+ } catch (error) {
341
+ candidate = {
342
+ kind: "error",
343
+ error
344
+ };
345
+ } finally {
346
+ stream.dispose();
347
+ }
348
+ }
349
+ } finally {
350
+ unsubscribe();
351
+ }
352
+ if (source.isClosed()) return closedResult$1();
353
+ if (invalidated || !Object.is(captured, source.generation.getSnapshot())) return staleResult$1();
354
+ if (candidate.kind === "closed") return closedResult$1();
355
+ if (candidate.kind === "stale") return staleResult$1();
356
+ if (candidate.kind === "error") return classifyReadFailure(candidate.error);
357
+ if (candidate.kind === "invalid") return {
358
+ kind: "unavailable",
359
+ code: "NATIVE_INVALID_RESPONSE",
360
+ message: "The official Workspace baseline is unusable."
361
+ };
362
+ if (candidate.kind === "unavailable") return {
363
+ kind: "unavailable",
364
+ code: "NATIVE_WORKSPACES_UNAVAILABLE",
365
+ message: "The official Workspace stream ended before its baseline."
366
+ };
367
+ return candidate;
368
+ }
369
+ //#endregion
370
+ //#region src/app/remote-process/native-client-write-result.ts
371
+ function unknownFailure(code, message) {
372
+ return {
373
+ kind: "unknown",
374
+ code,
375
+ message
376
+ };
377
+ }
378
+ /**
379
+ * Native's public result taxonomy deliberately does not reuse the shared TUI
380
+ * classifier's `cancelled => not-dispatched` shortcut. Native operations fence
381
+ * genuinely pre-dispatch cancellation themselves; a cancellation reported by
382
+ * the official service has already entered the call path.
383
+ */
384
+ function nativeWriteFailure(failure) {
385
+ if (failure.kind === "rejected") return {
386
+ kind: "rejected",
387
+ code: failure.error.code,
388
+ message: failure.error.message
389
+ };
390
+ if (failure.kind === "cancelled") return unknownFailure("NATIVE_OPERATION_CANCELLED_AFTER_DISPATCH", "The official call was cancelled after it entered the dispatch path.");
391
+ return unknownFailure(failure.error.code, failure.error.message);
392
+ }
393
+ function nativePromptWriteFailure(failure, requestId) {
394
+ if (failure.kind === "rejected") return {
395
+ kind: "rejected",
396
+ code: failure.error.code,
397
+ message: failure.error.message
398
+ };
399
+ if (failure.kind === "cancelled") return {
400
+ kind: "unknown",
401
+ code: "NATIVE_OPERATION_CANCELLED_AFTER_DISPATCH",
402
+ message: "The official prompt call was cancelled after it entered the dispatch path.",
403
+ requestId
404
+ };
405
+ return {
406
+ kind: "unknown",
407
+ code: failure.error.code,
408
+ message: failure.error.message,
409
+ requestId
410
+ };
411
+ }
412
+ //#endregion
413
+ //#region src/app/remote-process/native-client-window.ts
414
+ function sessionEventOf(entry) {
415
+ if (entry.type === "transient") return {
416
+ type: "transient",
417
+ event: {
418
+ type: "assistant/live-chunk",
419
+ seq: entry.event.seq,
420
+ time: entry.event.time,
421
+ data: {
422
+ attemptId: entry.event.data.attemptId,
423
+ turn: entry.event.data.turn,
424
+ step: entry.event.data.step,
425
+ chunk: nativeJsonValueOf(entry.event.data.chunk, "assistant chunk")
426
+ }
427
+ }
428
+ };
429
+ const event = entry.event;
430
+ const type = event.type;
431
+ const seq = event.seq;
432
+ const time = event.time;
433
+ if (typeof type !== "string" || typeof seq !== "number" || typeof time !== "number") throw new TypeError("session event: invalid envelope");
434
+ const rawSurfaceOp = "surfaceOp" in event ? event.surfaceOp : void 0;
435
+ const rawSourceEventSeqs = "sourceEventSeqs" in event ? event.sourceEventSeqs : void 0;
436
+ const surfaceOp = rawSurfaceOp === void 0 || rawSurfaceOp === "append" ? rawSurfaceOp : typeof rawSurfaceOp === "object" && rawSurfaceOp !== null && !Array.isArray(rawSurfaceOp) && rawSurfaceOp.op === "replace" && typeof rawSurfaceOp.startSeq === "number" && typeof rawSurfaceOp.endSeq === "number" ? {
437
+ op: "replace",
438
+ startSeq: rawSurfaceOp.startSeq,
439
+ endSeq: rawSurfaceOp.endSeq
440
+ } : void 0;
441
+ if (rawSurfaceOp !== void 0 && surfaceOp === void 0) throw new TypeError("session event: invalid surfaceOp");
442
+ if (rawSourceEventSeqs !== void 0 && (!Array.isArray(rawSourceEventSeqs) || !rawSourceEventSeqs.every((value) => typeof value === "number"))) throw new TypeError("session event: invalid sourceEventSeqs");
443
+ const sourceEventSeqs = rawSourceEventSeqs;
444
+ return {
445
+ type: "event",
446
+ event: {
447
+ type,
448
+ seq,
449
+ time,
450
+ data: nativeJsonValueOf(event.data, `session event ${type}`),
451
+ ...event.ignorable === true ? { ignorable: true } : {},
452
+ ...surfaceOp === void 0 ? {} : { surfaceOp },
453
+ ...sourceEventSeqs === void 0 ? {} : { sourceEventSeqs }
454
+ }
455
+ };
456
+ }
457
+ function nativeJsonValueOf(value, label = "value") {
458
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
459
+ if (typeof value === "number" && Number.isFinite(value)) return value;
460
+ if (Array.isArray(value)) return value.map((item) => nativeJsonValueOf(item, label));
461
+ if (typeof value === "object") {
462
+ const output = {};
463
+ for (const [key, item] of Object.entries(value)) output[key] = nativeJsonValueOf(item, `${label}.${key}`);
464
+ return output;
465
+ }
466
+ throw new TypeError(`${label}: expected JSON data`);
467
+ }
468
+ function sessionChangeOf(change) {
469
+ if (change.kind === "settle-assistant") return {
470
+ kind: "settle-assistant",
471
+ attemptId: change.attemptId,
472
+ ...change.entry === void 0 ? {} : { entry: sessionEventOf(change.entry) }
473
+ };
474
+ return {
475
+ kind: change.kind,
476
+ entries: change.entries.map(sessionEventOf)
477
+ };
478
+ }
479
+ /** Project one immutable official cut without rematerializing an unchanged full window. */
480
+ function projectNativeSessionWindow(source, previous, sameGeneration) {
481
+ if (sameGeneration && previous !== void 0 && Object.is(source, previous.source)) {
482
+ const readEntries = previous.readEntries;
483
+ return {
484
+ source,
485
+ readEntries,
486
+ reconcileRequired: false,
487
+ window: {
488
+ get entries() {
489
+ return readEntries();
490
+ },
491
+ hasMore: previous.window.hasMore,
492
+ revision: previous.window.revision,
493
+ change: {
494
+ kind: "append",
495
+ entries: []
496
+ }
497
+ }
498
+ };
499
+ }
500
+ if (sameGeneration && previous !== void 0 && source.revision === previous.source.revision + 1 && (source.change.kind === "append" || source.change.kind === "settle-assistant")) {
501
+ const change = sessionChangeOf(source.change);
502
+ let entries;
503
+ const readEntries = () => entries ??= source.entries.map(sessionEventOf);
504
+ return {
505
+ source,
506
+ readEntries,
507
+ reconcileRequired: false,
508
+ window: {
509
+ get entries() {
510
+ return readEntries();
511
+ },
512
+ hasMore: source.hasMore,
513
+ revision: source.revision,
514
+ change
515
+ }
516
+ };
517
+ }
518
+ const entries = source.entries.map(sessionEventOf);
519
+ const readEntries = () => entries;
520
+ return {
521
+ source,
522
+ readEntries,
523
+ reconcileRequired: true,
524
+ window: {
525
+ entries,
526
+ hasMore: source.hasMore,
527
+ revision: source.revision,
528
+ change: {
529
+ kind: "replace",
530
+ entries
531
+ }
532
+ }
533
+ };
534
+ }
535
+ //#endregion
536
+ //#region src/app/remote-process/native-client-subagents.ts
537
+ function unavailableDiagnostic(entry) {
538
+ return {
539
+ kind: "diagnostic",
540
+ id: entry.id,
541
+ reason: "unavailable",
542
+ parentId: entry.parentId,
543
+ depth: entry.depth
544
+ };
545
+ }
546
+ /** Prepare one detached sample without owning subscriptions, retry or cache. */
547
+ async function prepareNativeSubagentActivity(snapshot, deps, signal) {
548
+ if (signal.aborted || !deps.isCurrent()) return void 0;
549
+ const roster = deps.roster();
550
+ const actualIds = new Set(roster.ids);
551
+ const descendants = [];
552
+ const actualWitnesses = [];
553
+ for (const entry of snapshot.descendants) {
554
+ if (entry.kind !== "child") {
555
+ descendants.push(entry);
556
+ continue;
557
+ }
558
+ if (entry.mode === "external") {
559
+ descendants.push({
560
+ kind: "diagnostic",
561
+ id: entry.id,
562
+ reason: "unsupported",
563
+ parentId: entry.parentId,
564
+ depth: entry.depth
565
+ });
566
+ continue;
567
+ }
568
+ if (entry.mode !== "one-shot" && entry.mode !== "continuable") {
569
+ descendants.push(unavailableDiagnostic(entry));
570
+ continue;
571
+ }
572
+ const row = actualIds.has(entry.id) ? roster.byId[entry.id] : void 0;
573
+ if (row !== void 0 && typeof row.running === "boolean") {
574
+ actualWitnesses.push({
575
+ id: entry.id,
576
+ running: row.running
577
+ });
578
+ descendants.push({
579
+ ...entry,
580
+ activity: row.running ? "running" : "inactive"
581
+ });
582
+ continue;
583
+ }
584
+ if (signal.aborted || !deps.isCurrent()) return void 0;
585
+ actualWitnesses.push({
586
+ id: entry.id,
587
+ running: void 0
588
+ });
589
+ let result;
590
+ try {
591
+ result = await deps.state(entry.id, signal);
592
+ } catch {
593
+ if (signal.aborted || !deps.isCurrent()) return void 0;
594
+ descendants.push(unavailableDiagnostic(entry));
595
+ continue;
596
+ }
597
+ if (signal.aborted || !deps.isCurrent()) return void 0;
598
+ if (!result.ok || typeof result.value.running !== "boolean") {
599
+ descendants.push(unavailableDiagnostic(entry));
600
+ continue;
601
+ }
602
+ descendants.push({
603
+ ...entry,
604
+ activity: result.value.running ? "running" : "inactive"
605
+ });
606
+ }
607
+ if (signal.aborted || !deps.isCurrent()) return void 0;
608
+ return {
609
+ parentSessionId: snapshot.parentSessionId,
610
+ descendants,
611
+ actualWitnesses
612
+ };
613
+ }
614
+ /**
615
+ * Finalize a prepared sample synchronously at the public publication boundary.
616
+ * No await may separate this authority check from the Native listener call.
617
+ */
618
+ function settleNativeSubagentActivity(prepared, deps, signal) {
619
+ if (signal.aborted || !deps.isCurrent()) return { kind: "abandoned" };
620
+ const currentRoster = deps.roster();
621
+ const currentIds = new Set(currentRoster.ids);
622
+ for (const witness of prepared.actualWitnesses) {
623
+ const row = currentIds.has(witness.id) ? currentRoster.byId[witness.id] : void 0;
624
+ if ((typeof row?.running === "boolean" ? row.running : void 0) !== witness.running) return { kind: "abandoned" };
625
+ }
626
+ const parentAvailable = currentRoster.byId[prepared.parentSessionId] !== void 0 || deps.parentEvidence();
627
+ if (signal.aborted || !deps.isCurrent()) return { kind: "abandoned" };
628
+ return {
629
+ kind: "ok",
630
+ value: {
631
+ parentSessionId: prepared.parentSessionId,
632
+ parentAvailable,
633
+ descendants: prepared.descendants
634
+ }
635
+ };
636
+ }
637
+ //#endregion
638
+ //#region src/app/remote-process/native-client.ts
639
+ const NATIVE_CLIENT_API_VERSION = 1;
640
+ const NATIVE_DSH_VERSION = "0.2.2-rc.5";
641
+ const NATIVE_PROJECTION_KEYS = [
642
+ "title",
643
+ "plan",
644
+ "tokenUsage",
645
+ "contextPressure",
646
+ "userQuestions",
647
+ "inbox"
648
+ ];
649
+ function nativeError(code, message) {
650
+ return Object.assign(/* @__PURE__ */ new Error(`native-client: ${message}`), { code });
651
+ }
652
+ function requireNonEmpty(value, label) {
653
+ if (typeof value !== "string" || value.trim() === "") throw nativeError("NATIVE_CLIENT_INVALID_INPUT", `${label} is required`);
654
+ return value;
655
+ }
656
+ function validateProfileName(profile) {
657
+ if (profile === "" || profile.includes("/") || profile.includes("\\") || profile === "." || profile === ".." || profile === "node_modules") throw nativeError("NATIVE_CLIENT_INVALID_PROFILE", "profile is not a valid official profile name");
658
+ }
659
+ function validateNodeAndPlatform() {
660
+ if (process.platform !== "linux" && process.platform !== "darwin") throw nativeError("NATIVE_CLIENT_UNSUPPORTED_PLATFORM", "Native Client supports Linux and macOS only");
661
+ const match = /^(\d+)\.(\d+)\.(\d+)$/u.exec(process.versions.node);
662
+ if (match === null || Number(match[1]) !== 24 || Number(match[2]) < 9) throw nativeError("NATIVE_CLIENT_UNSUPPORTED_NODE", "Native Client requires Node 24.9 or later within Node 24");
663
+ }
664
+ function validateDshAnchor(value) {
665
+ requireNonEmpty(value, "dshAnchor");
666
+ if (!isAbsolute(value)) throw nativeError("NATIVE_CLIENT_INVALID_DSH_ANCHOR", "dshAnchor must be an absolute package.json path");
667
+ const anchor = realpathSync(value);
668
+ let manifest;
669
+ try {
670
+ manifest = JSON.parse(readFileSync(anchor, "utf8"));
671
+ } catch (error) {
672
+ throw nativeError("NATIVE_CLIENT_INVALID_DSH_ANCHOR", "dshAnchor is not a readable DSH package manifest");
673
+ }
674
+ const record = recordOf(manifest, "dshAnchor manifest");
675
+ if (record.name !== "@deepseek-ai/dsh" || record.version !== NATIVE_DSH_VERSION) throw nativeError("NATIVE_CLIENT_UNSUPPORTED_DSH", `Native Client requires @deepseek-ai/dsh ${NATIVE_DSH_VERSION}`);
676
+ return anchor;
677
+ }
678
+ async function loadOfficialClientHost(anchor) {
679
+ const requireFromDsh = createRequire(anchor);
680
+ const importResolved = async (specifier) => import(pathToFileURL(requireFromDsh.resolve(specifier)).href);
681
+ const appBoot = await importResolved("@deepseek-ai/dsh-app-boot");
682
+ const cordis = await importResolved("@deepseek-ai/cordis");
683
+ const loaderModule = await importResolved("@deepseek-ai/cordis-plugin-loader");
684
+ const homePaths = await importResolved("@deepseek-ai/dsh-home-paths");
685
+ return {
686
+ Context: cordis.Context,
687
+ PluginPackages: appBoot.PluginPackages,
688
+ Loader: loaderModule.default,
689
+ loadProfileDirectory: appBoot.loadProfileDirectory,
690
+ readProfileManifest: appBoot.readProfileManifest,
691
+ createRuntimeResolution: appBoot.createRuntimeResolution,
692
+ resolveDshHome: homePaths.resolveDshHome,
693
+ resolveProfileDir: appBoot.resolveProfileDir
694
+ };
695
+ }
696
+ function createStartupGate() {
697
+ let resolveBarrier;
698
+ let rejectBarrier;
699
+ let state = "pending";
700
+ const barrier = new Promise((resolve, reject) => {
701
+ resolveBarrier = resolve;
702
+ rejectBarrier = reject;
703
+ });
704
+ barrier.catch(() => {});
705
+ return {
706
+ plugin: async () => {
707
+ await barrier;
708
+ },
709
+ get pending() {
710
+ return state === "pending";
711
+ },
712
+ release() {
713
+ if (state !== "pending") return;
714
+ state = "released";
715
+ resolveBarrier?.();
716
+ },
717
+ cancel(reason) {
718
+ if (state !== "pending") return;
719
+ state = "cancelled";
720
+ rejectBarrier?.(reason);
721
+ }
722
+ };
723
+ }
724
+ function projectIdentity(identity) {
725
+ const shared = {
726
+ scopeId: identity.scopeId,
727
+ instanceId: identity.instanceId,
728
+ hostPid: identity.hostPid,
729
+ protocol: identity.protocol,
730
+ dshVersion: identity.dshVersion,
731
+ bundleVersion: identity.bundleVersion,
732
+ buildId: identity.buildId
733
+ };
734
+ if (identity.schema === 1) return Object.freeze({
735
+ ...shared,
736
+ kernel: Object.freeze({
737
+ platform: "linux",
738
+ hostStarttime: identity.hostStarttime
739
+ })
740
+ });
741
+ if (identity.schema === 2) return Object.freeze({
742
+ ...shared,
743
+ kernel: Object.freeze({
744
+ ...identity.hostKernelIdentity,
745
+ platform: "darwin"
746
+ })
747
+ });
748
+ throw nativeError("NATIVE_CLIENT_UNSUPPORTED_PLATFORM", "the authenticated Host uses an unsupported kernel identity schema");
749
+ }
750
+ function recordOf(value, label) {
751
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${label}: expected an object`);
752
+ return value;
753
+ }
754
+ function optionalString(record, key) {
755
+ const value = record[key];
756
+ return typeof value === "string" ? value : void 0;
757
+ }
758
+ function failureOf(error, fallbackCode, fallbackMessage, officialMessage) {
759
+ const code = remoteFailureCode(error);
760
+ return {
761
+ code: code !== void 0 && (isRemoteBusinessRefusalCode(code) || code.startsWith("gateway/")) ? code : fallbackCode,
762
+ message: officialMessage ? remoteFailureMessage(error) : fallbackMessage
763
+ };
764
+ }
765
+ /**
766
+ * The official `SessionCreateError` wraps the real Host/transport failure as
767
+ * `rpcError`; only that wrapped fact is a trustworthy create classification,
768
+ * never a code attached by an arbitrary local throw.
769
+ */
770
+ function sessionCreateRpcErrorOf(error) {
771
+ if (typeof error !== "object" || error === null) return void 0;
772
+ const rpcError = error.rpcError;
773
+ return typeof rpcError === "object" && rpcError !== null ? rpcError : void 0;
774
+ }
775
+ function closedResult() {
776
+ return {
777
+ kind: "closed",
778
+ code: "NATIVE_CLIENT_CLOSED",
779
+ message: "The Native Client is closed."
780
+ };
781
+ }
782
+ function closedSessionResult() {
783
+ return {
784
+ kind: "closed",
785
+ code: "NATIVE_SESSION_CLOSED",
786
+ message: "The Native Session handle is closed."
787
+ };
788
+ }
789
+ function staleResult() {
790
+ return {
791
+ kind: "stale",
792
+ code: "NATIVE_GENERATION_STALE",
793
+ message: "The result belongs to a replaced Connection generation."
794
+ };
795
+ }
796
+ function unavailableResult(code, message) {
797
+ return {
798
+ kind: "unavailable",
799
+ code,
800
+ message
801
+ };
802
+ }
803
+ function notDispatchedResult(code = "NATIVE_OPERATION_NOT_DISPATCHED", message = "The operation was not dispatched.") {
804
+ return {
805
+ kind: "not-dispatched",
806
+ code,
807
+ message
808
+ };
809
+ }
810
+ function unsupportedResult(code, message) {
811
+ return {
812
+ kind: "unsupported",
813
+ code,
814
+ message
815
+ };
816
+ }
817
+ function rejectedResult(failure) {
818
+ return {
819
+ kind: "rejected",
820
+ ...failure
821
+ };
822
+ }
823
+ function unknownResult(failure, extra) {
824
+ return {
825
+ kind: "unknown",
826
+ ...failure,
827
+ ...extra
828
+ };
829
+ }
830
+ function asPromptFailure(result) {
831
+ return result;
832
+ }
833
+ function asPromptResolutionFailure(result, requestId) {
834
+ return result.kind === "unknown" ? {
835
+ ...result,
836
+ requestId
837
+ } : result;
838
+ }
839
+ function readFailure(error, officialMessage) {
840
+ const failure = failureOf(error, "NATIVE_READ_UNAVAILABLE", "The authoritative read is unavailable.", officialMessage);
841
+ return isRemoteBusinessRefusalCode(remoteFailureCode(error)) ? rejectedResult(failure) : unavailableResult(failure.code, failure.message);
842
+ }
843
+ function currentGeneration(state) {
844
+ return state.transport.connection.generation.getSnapshot();
845
+ }
846
+ function isInitialGenerationCurrent(state) {
847
+ return state.initialGeneration !== void 0 && Object.is(currentGeneration(state), state.initialGeneration);
848
+ }
849
+ function trackClientOperation(state, operation) {
850
+ state.operations.add(operation);
851
+ observeSettled(operation, () => {
852
+ state.operations.delete(operation);
853
+ });
854
+ return operation;
855
+ }
856
+ async function settleRead(call, captured, generation, map) {
857
+ let result;
858
+ try {
859
+ result = await call();
860
+ } catch (error) {
861
+ if (!Object.is(captured, generation.getSnapshot())) return staleResult();
862
+ return readFailure(error, false);
863
+ }
864
+ if (!Object.is(captured, generation.getSnapshot())) return staleResult();
865
+ if (!result.ok) return readFailure(result.error, true);
866
+ try {
867
+ return {
868
+ kind: "ok",
869
+ value: map(result.value)
870
+ };
871
+ } catch {
872
+ return unavailableResult("NATIVE_INVALID_RESPONSE", "The official service returned an unusable response.");
873
+ }
874
+ }
875
+ /**
876
+ * Admit one passive root read. A pre-aborted caller never dispatches, while a
877
+ * closed root and a replaced/absent generation keep their existing outcome.
878
+ */
879
+ function admitRootRead(state, signal) {
880
+ if (state.closed) return closedResult();
881
+ if (signal?.aborted === true) return notDispatchedResult("NATIVE_READ_NOT_DISPATCHED", "The read was cancelled before dispatch.");
882
+ const generation = currentGeneration(state);
883
+ if (generation === void 0) return unavailableResult("NATIVE_DISCONNECTED", "No authenticated Host generation is current.");
884
+ const invalidation = new AbortController();
885
+ const unsubscribe = state.generation.subscribe(() => {
886
+ if (Object.is(generation, state.generation.getSnapshot())) return;
887
+ invalidation.abort(/* @__PURE__ */ new Error("native-client: read generation changed"));
888
+ });
889
+ const lifetime = state.lifetime.signal;
890
+ return {
891
+ generation,
892
+ signal: signal === void 0 ? AbortSignal.any([lifetime, invalidation.signal]) : AbortSignal.any([
893
+ lifetime,
894
+ signal,
895
+ invalidation.signal
896
+ ]),
897
+ callerAborted: () => signal?.aborted === true,
898
+ release: unsubscribe
899
+ };
900
+ }
901
+ /**
902
+ * Closed > replaced generation > caller cancellation > the actual read result.
903
+ * The caller cancellation is only ever published after the read stops, never
904
+ * as a fabricated wait timeout or a not-dispatched claim.
905
+ */
906
+ function rootReadInterruption(state, admission) {
907
+ if (state.closed) return closedResult();
908
+ if (!Object.is(admission.generation, currentGeneration(state))) return staleResult();
909
+ if (admission.callerAborted()) return unavailableResult("NATIVE_READ_CANCELLED", "The read was cancelled by the caller.");
910
+ }
911
+ /** Await one official unary read without publishing it. */
912
+ async function awaitRootRead(admission, call) {
913
+ try {
914
+ return await call();
915
+ } catch (error) {
916
+ return readFailure(error, false);
917
+ }
918
+ }
919
+ function mapRootValue(result, map) {
920
+ if (result.kind !== "ok") return result;
921
+ try {
922
+ return {
923
+ kind: "ok",
924
+ value: map(result.value)
925
+ };
926
+ } catch {
927
+ return unavailableResult("NATIVE_INVALID_RESPONSE", "The official service returned an unusable response.");
928
+ }
929
+ }
930
+ /** Convert one already-awaited official unary result, including its mapping. */
931
+ function rootReadCandidate(outcome, map) {
932
+ if (!("ok" in outcome)) return outcome;
933
+ if (!outcome.ok) return readFailure(outcome.error, true);
934
+ return mapRootValue({
935
+ kind: "ok",
936
+ value: outcome.value
937
+ }, map);
938
+ }
939
+ /**
940
+ * The owning read's final publication boundary. This MUST stay the last
941
+ * synchronous step before the owning read returns: conversion happened first,
942
+ * and no await may follow the check.
943
+ */
944
+ function finalizeRootRead(state, admission, candidate) {
945
+ return rootReadInterruption(state, admission) ?? candidate;
946
+ }
947
+ async function settleWrite(call, success, map, classify = classifyRemoteWriteFailure) {
948
+ let result;
949
+ try {
950
+ result = await call();
951
+ } catch (error) {
952
+ return unknownResult(failureOf(error, "NATIVE_OPERATION_OUTCOME_UNKNOWN", "The operation outcome could not be determined.", false));
953
+ }
954
+ if (!result.ok) return nativeWriteFailure(classify(result.error));
955
+ try {
956
+ const value = map(result.value);
957
+ return success === "accepted" ? {
958
+ kind: "accepted",
959
+ value
960
+ } : {
961
+ kind: "committed",
962
+ value
963
+ };
964
+ } catch {
965
+ return unknownResult({
966
+ code: "NATIVE_INVALID_RESPONSE",
967
+ message: "The official service returned an unusable response."
968
+ });
969
+ }
970
+ }
971
+ /**
972
+ * A create's success proves the official receipt. Only the pinned Gateway
973
+ * pre-invocation refusal set proves that the addressed create never ran; every
974
+ * business/domain code stays unknown because a create can publish before a
975
+ * later step fails.
976
+ */
977
+ function classifyCreateWriteFailure(error) {
978
+ const failure = classifyRemoteWriteFailure(error);
979
+ if (failure.kind !== "rejected") return failure;
980
+ return GATEWAY_PRE_INVOCATION_CODES.has(failure.error.code) ? failure : {
981
+ kind: "indeterminate",
982
+ error: failure.error
983
+ };
984
+ }
985
+ function classifyConfigurationCommandFailure(error) {
986
+ const failure = classifyRemoteWriteFailure(error);
987
+ if (failure.kind !== "rejected") return failure;
988
+ return failure.error.code === "gateway/bad-request" || GATEWAY_PRE_INVOCATION_CODES.has(failure.error.code) ? failure : {
989
+ kind: "indeterminate",
990
+ error: failure.error
991
+ };
992
+ }
993
+ function modelSelectionOf(value) {
994
+ const record = recordOf(value, "model selection");
995
+ const provider = optionalString(record, "provider");
996
+ const model = optionalString(record, "model");
997
+ if (provider === void 0 || provider === "" || model === void 0 || model === "") throw new TypeError("model selection: provider and model are required");
998
+ const reasoningEffort = optionalString(record, "reasoningEffort");
999
+ if (record.reasoningEffort !== void 0 && (reasoningEffort === void 0 || reasoningEffort === "")) throw new TypeError("model selection: invalid reasoning effort");
1000
+ return {
1001
+ provider,
1002
+ model,
1003
+ ...reasoningEffort === void 0 ? {} : { reasoningEffort }
1004
+ };
1005
+ }
1006
+ function nullableModelSelectionOf(value) {
1007
+ return value === null ? null : modelSelectionOf(value);
1008
+ }
1009
+ function nullableStringOf(value, label) {
1010
+ if (value === null) return null;
1011
+ if (typeof value !== "string" || value === "") throw new TypeError(`${label}: invalid value`);
1012
+ return value;
1013
+ }
1014
+ function localizedTextOf(value) {
1015
+ if (typeof value === "string") return value;
1016
+ const record = recordOf(value, "localized text");
1017
+ if (typeof record.en !== "string") throw new TypeError("localized text: English entry is required");
1018
+ const output = { en: record.en };
1019
+ for (const [locale, text] of Object.entries(record)) {
1020
+ if (typeof text !== "string") throw new TypeError("localized text: every entry must be a string");
1021
+ if (locale !== "en") output[locale] = text;
1022
+ }
1023
+ return output;
1024
+ }
1025
+ function modelCatalogOf(value) {
1026
+ const record = recordOf(value, "model catalog");
1027
+ if (!Array.isArray(record.routableProviders) || !Array.isArray(record.groups) || !Array.isArray(record.failures)) throw new TypeError("model catalog: invalid arrays");
1028
+ return {
1029
+ default: modelSelectionOf(record.default),
1030
+ routableProviders: record.routableProviders.map((provider) => {
1031
+ if (typeof provider !== "string") throw new TypeError("model catalog: invalid provider");
1032
+ return provider;
1033
+ }),
1034
+ groups: record.groups.map((groupValue) => {
1035
+ const group = recordOf(groupValue, "model group");
1036
+ if (typeof group.id !== "string" || typeof group.name !== "string" || !Array.isArray(group.models)) throw new TypeError("model group: invalid fields");
1037
+ return {
1038
+ id: group.id,
1039
+ name: group.name,
1040
+ models: group.models.map((modelValue) => {
1041
+ const model = recordOf(modelValue, "catalog model");
1042
+ if (typeof model.id !== "string" || typeof model.name !== "string") throw new TypeError("catalog model: invalid identity");
1043
+ const description = optionalString(model, "description");
1044
+ const reasoning = model.reasoning === void 0 ? void 0 : (() => {
1045
+ const value = recordOf(model.reasoning, "model reasoning");
1046
+ if (!Array.isArray(value.efforts)) throw new TypeError("model reasoning: invalid efforts");
1047
+ const defaultEffort = optionalString(value, "defaultEffort");
1048
+ return {
1049
+ efforts: value.efforts.map((effortValue) => {
1050
+ const effort = recordOf(effortValue, "reasoning effort");
1051
+ if (typeof effort.id !== "string" || typeof effort.name !== "string") throw new TypeError("reasoning effort: invalid identity");
1052
+ const effortDescription = optionalString(effort, "description");
1053
+ return {
1054
+ id: effort.id,
1055
+ name: effort.name,
1056
+ ...effortDescription === void 0 ? {} : { description: effortDescription }
1057
+ };
1058
+ }),
1059
+ ...defaultEffort === void 0 ? {} : { defaultEffort }
1060
+ };
1061
+ })();
1062
+ const badge = model.badge === void 0 ? void 0 : (() => {
1063
+ const value = recordOf(model.badge, "model badge");
1064
+ const tone = value.tone;
1065
+ if (tone !== "neutral" && tone !== "info" && tone !== "success" && tone !== "warning") throw new TypeError("model badge: invalid tone");
1066
+ return {
1067
+ text: localizedTextOf(value.text),
1068
+ tone
1069
+ };
1070
+ })();
1071
+ return {
1072
+ id: model.id,
1073
+ name: model.name,
1074
+ ...description === void 0 ? {} : { description },
1075
+ ...reasoning === void 0 ? {} : { reasoning },
1076
+ ...badge === void 0 ? {} : { badge }
1077
+ };
1078
+ })
1079
+ };
1080
+ }),
1081
+ failures: record.failures.map((failureValue) => {
1082
+ const failure = recordOf(failureValue, "model catalog failure");
1083
+ if (typeof failure.id !== "string" || typeof failure.name !== "string" || typeof failure.message !== "string") throw new TypeError("model catalog failure: invalid fields");
1084
+ return {
1085
+ id: failure.id,
1086
+ name: failure.name,
1087
+ message: failure.message
1088
+ };
1089
+ })
1090
+ };
1091
+ }
1092
+ function presetRosterOf(value) {
1093
+ const record = recordOf(value, "preset roster");
1094
+ if (!Array.isArray(record.presets)) throw new TypeError("preset roster: invalid presets");
1095
+ return { presets: record.presets.map((value) => {
1096
+ const preset = recordOf(value, "preset row");
1097
+ if (typeof preset.id !== "string") throw new TypeError("preset row: invalid id");
1098
+ const name = optionalString(preset, "name");
1099
+ const description = optionalString(preset, "description");
1100
+ const broken = optionalString(preset, "broken");
1101
+ return {
1102
+ id: preset.id,
1103
+ ...typeof preset.isDefault === "boolean" ? { isDefault: preset.isDefault } : {},
1104
+ ...name === void 0 ? {} : { name },
1105
+ ...description === void 0 ? {} : { description },
1106
+ ...broken === void 0 ? {} : { broken }
1107
+ };
1108
+ }) };
1109
+ }
1110
+ function permissionOptionOf(value) {
1111
+ const option = recordOf(value, "permission option");
1112
+ if (typeof option.value !== "string" || typeof option.name !== "string") throw new TypeError("permission option: invalid identity");
1113
+ const description = optionalString(option, "description");
1114
+ return {
1115
+ value: option.value,
1116
+ name: option.name,
1117
+ ...description === void 0 ? {} : { description }
1118
+ };
1119
+ }
1120
+ function permissionCatalogOf(value) {
1121
+ const record = recordOf(value, "permission catalog");
1122
+ if (!Array.isArray(record.options) || !Array.isArray(record.defaultOptions) || typeof record.defaultPreset !== "string") throw new TypeError("permission catalog: invalid fields");
1123
+ return {
1124
+ options: record.options.map(permissionOptionOf),
1125
+ defaultOptions: record.defaultOptions.map(permissionOptionOf),
1126
+ defaultPreset: record.defaultPreset
1127
+ };
1128
+ }
1129
+ function questionIntentOf(value) {
1130
+ const intent = recordOf(value, "question intent");
1131
+ if (intent.kind === "plan-review") {
1132
+ if (typeof intent.approve !== "string") throw new TypeError("plan-review intent: approve is required");
1133
+ const callId = optionalString(intent, "callId");
1134
+ return {
1135
+ kind: "plan-review",
1136
+ approve: intent.approve,
1137
+ ...callId === void 0 ? {} : { callId }
1138
+ };
1139
+ }
1140
+ if (intent.kind === "approval") {
1141
+ if (typeof intent.approve !== "string" || typeof intent.reject !== "string") throw new TypeError("approval intent: approve and reject are required");
1142
+ const always = optionalString(intent, "always");
1143
+ const subject = intent.subject === void 0 ? void 0 : (() => {
1144
+ const value = recordOf(intent.subject, "approval subject");
1145
+ if (typeof value.name !== "string") throw new TypeError("approval subject: name is required");
1146
+ const icon = optionalString(value, "icon");
1147
+ return {
1148
+ name: value.name,
1149
+ ...icon === void 0 ? {} : { icon }
1150
+ };
1151
+ })();
1152
+ const display = intent.display === void 0 ? void 0 : (() => {
1153
+ const value = recordOf(intent.display, "approval display");
1154
+ const question = localizedTextOf(value.question);
1155
+ if (typeof question === "string") throw new TypeError("approval display: question must be localized");
1156
+ const detail = value.detail === void 0 ? void 0 : localizedTextOf(value.detail);
1157
+ const approve = value.approve === void 0 ? void 0 : localizedTextOf(value.approve);
1158
+ if (detail !== void 0 && typeof detail === "string" || approve !== void 0 && typeof approve === "string") throw new TypeError("approval display: detail and approve must be localized");
1159
+ return {
1160
+ question,
1161
+ ...detail === void 0 ? {} : { detail },
1162
+ ...approve === void 0 ? {} : { approve }
1163
+ };
1164
+ })();
1165
+ return {
1166
+ kind: "approval",
1167
+ approve: intent.approve,
1168
+ reject: intent.reject,
1169
+ ...always === void 0 ? {} : { always },
1170
+ ...subject === void 0 ? {} : { subject },
1171
+ ...display === void 0 ? {} : { display }
1172
+ };
1173
+ }
1174
+ throw new TypeError("question intent: unknown kind");
1175
+ }
1176
+ function questionItemOf(value) {
1177
+ const item = recordOf(value, "question item");
1178
+ if (typeof item.id !== "string" || typeof item.question !== "string") throw new TypeError("question item: invalid identity");
1179
+ const detail = optionalString(item, "detail");
1180
+ const header = optionalString(item, "header");
1181
+ const options = item.options === void 0 ? void 0 : (() => {
1182
+ if (!Array.isArray(item.options)) throw new TypeError("question item: invalid options");
1183
+ return item.options.map((optionValue) => {
1184
+ const option = recordOf(optionValue, "question option");
1185
+ if (typeof option.label !== "string") throw new TypeError("question option: label is required");
1186
+ const description = optionalString(option, "description");
1187
+ return {
1188
+ label: option.label,
1189
+ ...description === void 0 ? {} : { description }
1190
+ };
1191
+ });
1192
+ })();
1193
+ if (item.multiSelect !== void 0 && typeof item.multiSelect !== "boolean") throw new TypeError("question item: invalid multiSelect");
1194
+ return {
1195
+ id: item.id,
1196
+ question: item.question,
1197
+ ...detail === void 0 ? {} : { detail },
1198
+ ...header === void 0 ? {} : { header },
1199
+ ...options === void 0 ? {} : { options },
1200
+ ...item.multiSelect === void 0 ? {} : { multiSelect: item.multiSelect },
1201
+ ...item.intent === void 0 ? {} : { intent: questionIntentOf(item.intent) }
1202
+ };
1203
+ }
1204
+ function questionItemsOf(value) {
1205
+ return value.map(questionItemOf);
1206
+ }
1207
+ function historyPageOf(page) {
1208
+ return {
1209
+ cursor: page.cursor,
1210
+ records: page.records.map(sessionEventOf),
1211
+ hasMore: page.hasMore
1212
+ };
1213
+ }
1214
+ /** Resolve one root read's official address, preserving the exact-child contract. */
1215
+ function rootSessionAddress(state, sessionId) {
1216
+ const known = state.sessions.subagentAddress(sessionId);
1217
+ const listedChild = state.sessions.list.getSnapshot().byId[sessionId]?.origin === "subagent";
1218
+ const knownChild = known !== void 0 || listedChild;
1219
+ if (knownChild && !isInitialGenerationCurrent(state)) return staleResult();
1220
+ if (knownChild && known === void 0) return unavailableResult("NATIVE_SUBAGENT_ADDRESS_UNAVAILABLE", "The native child has no current official direct-parent address.");
1221
+ return { address: known === void 0 ? ordinaryAddress(sessionId) : knownSubagentAddress(known) };
1222
+ }
1223
+ async function readRootHistory(state, sessionId, options) {
1224
+ requireNonEmpty(sessionId, "sessionId");
1225
+ validateHistoryOptions(options);
1226
+ const admission = admitRootRead(state, options?.signal);
1227
+ if ("kind" in admission) return admission;
1228
+ const target = rootSessionAddress(state, sessionId);
1229
+ if ("kind" in target) {
1230
+ admission.release();
1231
+ return target;
1232
+ }
1233
+ try {
1234
+ return finalizeRootRead(state, admission, rootReadCandidate(await awaitRootRead(admission, () => state.remote.session.page(historyRequest(target.address, options), admission.signal)), historyPageOf));
1235
+ } finally {
1236
+ admission.release();
1237
+ }
1238
+ }
1239
+ function sessionInfoOf(header, expectedSessionId) {
1240
+ if (header.id !== expectedSessionId) throw new TypeError("Session header: identity does not match the requested Session");
1241
+ return {
1242
+ sessionId: header.id,
1243
+ createdAt: header.createdAt,
1244
+ ...header.cwd === void 0 ? {} : { cwd: header.cwd },
1245
+ ...header.parentSession === void 0 ? {} : { parentSessionId: header.parentSession },
1246
+ isSeeded: header.isSeeded,
1247
+ ...header.origin === void 0 ? {} : { origin: header.origin },
1248
+ ...header.delegationDepth === void 0 ? {} : { delegationDepth: header.delegationDepth },
1249
+ ...header.agentPreset === void 0 ? {} : { agentPreset: header.agentPreset }
1250
+ };
1251
+ }
1252
+ /**
1253
+ * Read one real official follow opening as passive header metadata. The
1254
+ * observation is disposed after its first snapshot; it never activates,
1255
+ * retains or scans the Session.
1256
+ */
1257
+ async function readRootSessionInfo(state, sessionId, signal) {
1258
+ requireNonEmpty(sessionId, "sessionId");
1259
+ const admission = admitRootRead(state, signal);
1260
+ if ("kind" in admission) return admission;
1261
+ const target = rootSessionAddress(state, sessionId);
1262
+ if ("kind" in target) {
1263
+ admission.release();
1264
+ return target;
1265
+ }
1266
+ try {
1267
+ let stream;
1268
+ try {
1269
+ stream = state.remote.session.follow({
1270
+ address: target.address,
1271
+ activate: false,
1272
+ maxMessages: 1
1273
+ }, admission.signal);
1274
+ } catch (error) {
1275
+ return rootReadInterruption(state, admission) ?? readFailure(error, false);
1276
+ }
1277
+ let opening;
1278
+ try {
1279
+ for await (const frame of stream) {
1280
+ opening = frame.type !== "snapshot" ? unavailableResult("NATIVE_HEADER_UNAVAILABLE", "The official Session follow did not open with a snapshot.") : mapRootValue({
1281
+ kind: "ok",
1282
+ value: frame.header
1283
+ }, (header) => sessionInfoOf(header, sessionId));
1284
+ break;
1285
+ }
1286
+ } catch (error) {
1287
+ return rootReadInterruption(state, admission) ?? readFailure(error, true);
1288
+ } finally {
1289
+ stream.dispose();
1290
+ }
1291
+ return rootReadInterruption(state, admission) ?? opening ?? unavailableResult("NATIVE_HEADER_UNAVAILABLE", "The official Session follow ended before its opening snapshot.");
1292
+ } finally {
1293
+ admission.release();
1294
+ }
1295
+ }
1296
+ function sessionStateOf(state) {
1297
+ return {
1298
+ cursor: state.cursor,
1299
+ active: state.active,
1300
+ running: state.running,
1301
+ queue: state.queue === null ? null : state.queue.map((item) => ({
1302
+ id: item.id,
1303
+ placement: item.placement,
1304
+ ...item.rpcId === void 0 ? {} : { rpcId: item.rpcId },
1305
+ content: item.content.map((entry) => nativeJsonValueOf(entry, "queue content"))
1306
+ })),
1307
+ pendingInput: [...state.pendingInput]
1308
+ };
1309
+ }
1310
+ function sessionWaitValueOf(value) {
1311
+ return {
1312
+ reason: value.reason,
1313
+ state: sessionStateOf(value.state),
1314
+ output: {
1315
+ records: value.output.records.map(sessionEventOf),
1316
+ truncated: value.output.truncated
1317
+ }
1318
+ };
1319
+ }
1320
+ function sessionSearchResultOf(value) {
1321
+ return {
1322
+ items: value.items.map((item) => ({
1323
+ sessionId: item.sessionId,
1324
+ snippet: item.snippet
1325
+ })),
1326
+ hasMore: value.hasMore
1327
+ };
1328
+ }
1329
+ /** The exact projection values one configuration read may consume. */
1330
+ function sequencedConfigurationValues(value) {
1331
+ return value !== null && value.kind === "sequenced" ? value.values : void 0;
1332
+ }
1333
+ async function readRootSessionState(state, sessionId, signal) {
1334
+ requireNonEmpty(sessionId, "sessionId");
1335
+ const admission = admitRootRead(state, signal);
1336
+ if ("kind" in admission) return admission;
1337
+ try {
1338
+ return finalizeRootRead(state, admission, rootReadCandidate(await awaitRootRead(admission, () => state.remote.session.state({ sessionId }, admission.signal)), sessionStateOf));
1339
+ } finally {
1340
+ admission.release();
1341
+ }
1342
+ }
1343
+ async function readRootSessionWait(state, sessionId, options) {
1344
+ requireNonEmpty(sessionId, "sessionId");
1345
+ const admission = admitRootRead(state, options?.signal);
1346
+ if ("kind" in admission) return admission;
1347
+ try {
1348
+ return finalizeRootRead(state, admission, rootReadCandidate(await awaitRootRead(admission, () => state.remote.session.wait({
1349
+ sessionId,
1350
+ ...options?.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs },
1351
+ ...options?.afterSeq === void 0 ? {} : { afterSeq: options.afterSeq },
1352
+ ...options?.maxMessages === void 0 ? {} : { maxMessages: options.maxMessages }
1353
+ }, admission.signal)), sessionWaitValueOf));
1354
+ } finally {
1355
+ admission.release();
1356
+ }
1357
+ }
1358
+ async function readRootSessionSearch(state, query, signal) {
1359
+ requireNonEmpty(query, "query");
1360
+ const admission = admitRootRead(state, signal);
1361
+ if ("kind" in admission) return admission;
1362
+ try {
1363
+ return finalizeRootRead(state, admission, rootReadCandidate(await awaitRootRead(admission, () => state.remote.session.search({ query }, admission.signal)), sessionSearchResultOf));
1364
+ } finally {
1365
+ admission.release();
1366
+ }
1367
+ }
1368
+ async function readRootConfiguration(state, sessionId, signal) {
1369
+ requireNonEmpty(sessionId, "sessionId");
1370
+ const admission = admitRootRead(state, signal);
1371
+ if ("kind" in admission) return admission;
1372
+ try {
1373
+ return finalizeRootRead(state, admission, configurationCandidate(await awaitRootRead(admission, () => state.remote.session.projections({ sessionId }, admission.signal))));
1374
+ } finally {
1375
+ admission.release();
1376
+ }
1377
+ }
1378
+ /** Convert the exact projection response without ever falling back to hints. */
1379
+ function configurationCandidate(outcome) {
1380
+ if (!("ok" in outcome)) return outcome;
1381
+ if (!outcome.ok) return readFailure(outcome.error, true);
1382
+ if (outcome.value === null) return unavailableResult("NATIVE_PROJECTIONS_ABSENT", "No exact Session projection baseline exists.");
1383
+ const values = sequencedConfigurationValues(outcome.value);
1384
+ if (values === void 0) return unavailableResult("NATIVE_PROJECTIONS_MIGRATION_REQUIRED", "The Session projections require migration; cached hints are not current values.");
1385
+ return mapRootValue({
1386
+ kind: "ok",
1387
+ value: values
1388
+ }, configurationOf);
1389
+ }
1390
+ async function readRootSessionPolicy(state, sessionId, signal) {
1391
+ requireNonEmpty(sessionId, "sessionId");
1392
+ const admission = admitRootRead(state, signal);
1393
+ if ("kind" in admission) return admission;
1394
+ try {
1395
+ const namespace = state.remote.piTuiSessionPolicy;
1396
+ if (namespace === void 0) return unsupportedResult("NATIVE_SESSION_POLICY_UNAVAILABLE", "The Host does not expose the optional Session policy read.");
1397
+ return finalizeRootRead(state, admission, policyCandidate(await awaitRootRead(admission, () => namespace.read(sessionId, admission.signal))));
1398
+ } finally {
1399
+ admission.release();
1400
+ }
1401
+ }
1402
+ /** Convert the optional live policy response without inventing a default. */
1403
+ function policyCandidate(outcome) {
1404
+ if (!("ok" in outcome)) return outcome;
1405
+ if (!outcome.ok) {
1406
+ const failure = readFailure(outcome.error, true);
1407
+ return failure.kind === "rejected" && failure.code === "gateway/invocation-unavailable" ? unsupportedResult(failure.code, "The Host does not expose the optional Session policy read.") : failure;
1408
+ }
1409
+ if (outcome.value.kind === "unavailable") return unavailableResult("NATIVE_SESSION_NOT_LIVE", "No live Agent exists for this Session.");
1410
+ return {
1411
+ kind: "ok",
1412
+ value: outcome.value
1413
+ };
1414
+ }
1415
+ function sessionSummaryOf(row) {
1416
+ const title = row.projections?.values.title;
1417
+ return {
1418
+ sessionId: row.sessionId,
1419
+ ...typeof title === "string" && title !== "" ? { title } : {},
1420
+ ...row.cwd === void 0 ? {} : { cwd: row.cwd },
1421
+ agentAvailable: row.agentAvailable,
1422
+ running: row.running,
1423
+ blank: row.blank,
1424
+ updatedAt: row.updatedAt,
1425
+ ...row.parentSessionId === void 0 ? {} : { parentSessionId: row.parentSessionId },
1426
+ ...row.origin === void 0 ? {} : { origin: row.origin },
1427
+ ...row.formatStatus === void 0 ? {} : { formatStatus: row.formatStatus }
1428
+ };
1429
+ }
1430
+ function sessionSnapshotFacts(snapshot) {
1431
+ return [
1432
+ snapshot.pendingSubmissions,
1433
+ snapshot.running,
1434
+ snapshot.subagent?.address.parentSessionId,
1435
+ snapshot.subagent?.address.childSessionId,
1436
+ snapshot.subagent?.address.mode,
1437
+ snapshot.removed,
1438
+ snapshot.openState,
1439
+ snapshot.openError,
1440
+ snapshot.hasMore,
1441
+ snapshot.historyWasPartial,
1442
+ snapshot.loadingOlder,
1443
+ snapshot.historyLoadStatus,
1444
+ snapshot.promptError,
1445
+ snapshot.blank,
1446
+ snapshot.lastAgentError,
1447
+ snapshot.promptAttempted,
1448
+ snapshot.awaitingFirstTurn
1449
+ ];
1450
+ }
1451
+ function failureDtoOf(value) {
1452
+ const failure = recordOf(value, "remote failure");
1453
+ if (typeof failure.code !== "string" || typeof failure.message !== "string") throw new TypeError("remote failure: invalid fields");
1454
+ return {
1455
+ code: failure.code,
1456
+ message: failure.message
1457
+ };
1458
+ }
1459
+ function planOf(value) {
1460
+ const plan = recordOf(value, "plan projection");
1461
+ if (typeof plan.active !== "boolean" || typeof plan.pending !== "boolean") throw new TypeError("plan projection: invalid fields");
1462
+ return {
1463
+ active: plan.active,
1464
+ pending: plan.pending
1465
+ };
1466
+ }
1467
+ function tokenUsageOf(value) {
1468
+ const usage = recordOf(value, "token usage");
1469
+ for (const key of [
1470
+ "uncachedInputTokens",
1471
+ "outputTokens",
1472
+ "cacheReadTokens",
1473
+ "cacheWriteTokens"
1474
+ ]) if (typeof usage[key] !== "number" || !Number.isSafeInteger(usage[key]) || usage[key] < 0) throw new TypeError("token usage: invalid counters");
1475
+ return {
1476
+ uncachedInputTokens: usage.uncachedInputTokens,
1477
+ outputTokens: usage.outputTokens,
1478
+ cacheReadTokens: usage.cacheReadTokens,
1479
+ cacheWriteTokens: usage.cacheWriteTokens
1480
+ };
1481
+ }
1482
+ function contextPressureOf(value) {
1483
+ const pressure = recordOf(value, "context pressure");
1484
+ const output = {};
1485
+ for (const key of [
1486
+ "pressureTokens",
1487
+ "projectedTokens",
1488
+ "contextWindow"
1489
+ ]) {
1490
+ const value = pressure[key];
1491
+ if (value !== void 0) {
1492
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new TypeError("context pressure: invalid value");
1493
+ output[key] = value;
1494
+ }
1495
+ }
1496
+ return output;
1497
+ }
1498
+ function questionAnswerOf(value) {
1499
+ const answer = recordOf(value, "question answer");
1500
+ if (typeof answer.id !== "string" || !Array.isArray(answer.selected) || !answer.selected.every((item) => typeof item === "string")) throw new TypeError("question answer: invalid fields");
1501
+ const custom = optionalString(answer, "custom");
1502
+ return {
1503
+ id: answer.id,
1504
+ selected: answer.selected,
1505
+ ...custom === void 0 ? {} : { custom }
1506
+ };
1507
+ }
1508
+ function officialQuestionAnswers(answer) {
1509
+ if (!Array.isArray(answer.answers)) throw new TypeError("question answer: answers must be an array");
1510
+ return answer.answers.map((item) => {
1511
+ if (typeof item.id !== "string" || !Array.isArray(item.selected) || !item.selected.every((selected) => typeof selected === "string") || item.custom !== void 0 && typeof item.custom !== "string") throw new TypeError("question answer: invalid answer item");
1512
+ return {
1513
+ id: item.id,
1514
+ selected: [...item.selected],
1515
+ ...item.custom === void 0 ? {} : { custom: item.custom }
1516
+ };
1517
+ });
1518
+ }
1519
+ function userQuestionsOf(value) {
1520
+ const projection = recordOf(value, "user questions projection");
1521
+ if (!Array.isArray(projection.active) || !Array.isArray(projection.settled)) throw new TypeError("user questions projection: invalid arrays");
1522
+ return {
1523
+ active: projection.active.map((value) => {
1524
+ const active = recordOf(value, "pending question");
1525
+ if (typeof active.callId !== "string" || !Array.isArray(active.questions) || active.state !== "open" && active.state !== "continued") throw new TypeError("pending question: invalid fields");
1526
+ return {
1527
+ callId: active.callId,
1528
+ questions: active.questions.map(questionItemOf),
1529
+ state: active.state
1530
+ };
1531
+ }),
1532
+ settled: projection.settled.map((value) => {
1533
+ const settled = recordOf(value, "settled question");
1534
+ if (typeof settled.callId !== "string" || !Array.isArray(settled.answers)) throw new TypeError("settled question: invalid fields");
1535
+ return {
1536
+ callId: settled.callId,
1537
+ answers: settled.answers.map(questionAnswerOf)
1538
+ };
1539
+ })
1540
+ };
1541
+ }
1542
+ function queuedQuestionReply(value, callId) {
1543
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1544
+ const source = value.source;
1545
+ if (typeof source !== "object" || source === null || Array.isArray(source)) return false;
1546
+ const record = source;
1547
+ return record.kind === "user-question-reply" && record.callId === callId;
1548
+ }
1549
+ function inboxOf(value) {
1550
+ const inbox = recordOf(value, "inbox projection");
1551
+ if (!Array.isArray(inbox["next-turn"]) || !Array.isArray(inbox["next-step"])) throw new TypeError("inbox projection: invalid arrays");
1552
+ return {
1553
+ "next-turn": inbox["next-turn"].map((value) => nativeJsonValueOf(value, "inbox message")),
1554
+ "next-step": inbox["next-step"].map((value) => nativeJsonValueOf(value, "inbox message"))
1555
+ };
1556
+ }
1557
+ function permissionSelectionOf(value) {
1558
+ const selection = recordOf(value, "permission selection");
1559
+ if (typeof selection.currentValue !== "string") throw new TypeError("permission selection: invalid value");
1560
+ return { currentValue: selection.currentValue };
1561
+ }
1562
+ function configurationOf(values) {
1563
+ const modelSelection = values.modelSelection === void 0 ? void 0 : (() => {
1564
+ const value = recordOf(values.modelSelection, "model selection projection");
1565
+ return {
1566
+ lastUsed: nullableModelSelectionOf(value.lastUsed),
1567
+ next: nullableModelSelectionOf(value.next)
1568
+ };
1569
+ })();
1570
+ const currentModel = modelSelection === void 0 ? void 0 : modelSelection.next ?? modelSelection.lastUsed;
1571
+ return {
1572
+ ...modelSelection === void 0 ? {} : { modelSelection },
1573
+ ...currentModel === void 0 || currentModel === null ? {} : { currentModel },
1574
+ ...values.agentPreset === void 0 ? {} : { agentPreset: nullableStringOf(values.agentPreset, "agentPreset projection") },
1575
+ ...values.title === void 0 ? {} : { title: nullableStringOf(values.title, "title projection") },
1576
+ ...values.permissions === void 0 ? {} : { permissions: permissionSelectionOf(values.permissions) },
1577
+ ...values.plan === void 0 ? {} : { plan: planOf(values.plan) }
1578
+ };
1579
+ }
1580
+ function commandDescriptorOf(value) {
1581
+ return {
1582
+ ...value.definitionId === void 0 ? {} : { definitionId: value.definitionId },
1583
+ name: value.name,
1584
+ description: value.description,
1585
+ ...value.input === void 0 ? {} : { input: {
1586
+ hint: value.input.hint,
1587
+ ...value.input.attachments === void 0 ? {} : { attachments: value.input.attachments }
1588
+ } }
1589
+ };
1590
+ }
1591
+ function skillDescriptorOf(value) {
1592
+ return {
1593
+ name: value.name,
1594
+ description: value.description,
1595
+ ...value.whenToUse === void 0 ? {} : { whenToUse: value.whenToUse },
1596
+ modelInvocable: value.modelInvocable
1597
+ };
1598
+ }
1599
+ function commandExecutionOf(value) {
1600
+ return {
1601
+ commandId: value.commandId,
1602
+ result: value.result.kind === "success" ? {
1603
+ kind: "success",
1604
+ ...value.result.text === void 0 ? {} : { text: value.result.text },
1605
+ ...value.result.sourceEventSeq === void 0 ? {} : { sourceEventSeq: value.result.sourceEventSeq }
1606
+ } : {
1607
+ kind: "error",
1608
+ text: value.result.text
1609
+ }
1610
+ };
1611
+ }
1612
+ function jobOf(value) {
1613
+ const job = recordOf(value, "job row");
1614
+ if (typeof job.id !== "string" || typeof job.kind !== "string" || typeof job.label !== "string" || typeof job.startedAt !== "number" || job.status !== "running" && job.status !== "stopping" && job.status !== "completed" && job.status !== "killed" && job.status !== "failed") throw new TypeError("job row: invalid fields");
1615
+ const progress = optionalString(job, "progress");
1616
+ const detail = optionalString(job, "detail");
1617
+ const finishedAt = job.finishedAt;
1618
+ if (finishedAt !== void 0 && typeof finishedAt !== "number") throw new TypeError("job row: invalid finishedAt");
1619
+ return {
1620
+ id: job.id,
1621
+ kind: job.kind,
1622
+ label: job.label,
1623
+ status: job.status,
1624
+ ...progress === void 0 ? {} : { progress },
1625
+ ...detail === void 0 ? {} : { detail },
1626
+ startedAt: job.startedAt,
1627
+ ...finishedAt === void 0 ? {} : { finishedAt }
1628
+ };
1629
+ }
1630
+ function subagentSnapshotOf(value) {
1631
+ const snapshot = recordOf(value, "subagent snapshot");
1632
+ if (typeof snapshot.parentSessionId !== "string" || typeof snapshot.parentAvailable !== "boolean" || !Array.isArray(snapshot.descendants)) throw new TypeError("subagent snapshot: invalid fields");
1633
+ return {
1634
+ parentSessionId: snapshot.parentSessionId,
1635
+ parentAvailable: snapshot.parentAvailable,
1636
+ descendants: snapshot.descendants.map((value) => {
1637
+ const entry = recordOf(value, "subagent entry");
1638
+ if (typeof entry.id !== "string" || typeof entry.parentId !== "string" || typeof entry.depth !== "number") throw new TypeError("subagent entry: invalid identity");
1639
+ if (entry.kind === "diagnostic") {
1640
+ if (entry.reason !== "corrupt" && entry.reason !== "unsupported" && entry.reason !== "unavailable") throw new TypeError("subagent diagnostic: invalid reason");
1641
+ return {
1642
+ kind: "diagnostic",
1643
+ id: entry.id,
1644
+ reason: entry.reason,
1645
+ parentId: entry.parentId,
1646
+ depth: entry.depth
1647
+ };
1648
+ }
1649
+ if (entry.kind !== "child" || entry.mode !== "one-shot" && entry.mode !== "continuable" && entry.mode !== "external" || entry.activity !== "running" && entry.activity !== "inactive" || typeof entry.hasChildren !== "boolean") throw new TypeError("subagent child: invalid fields");
1650
+ const label = optionalString(entry, "label");
1651
+ const path = optionalString(entry, "path");
1652
+ return {
1653
+ kind: "child",
1654
+ id: entry.id,
1655
+ ...label === void 0 ? {} : { label },
1656
+ mode: entry.mode,
1657
+ activity: entry.activity,
1658
+ hasChildren: entry.hasChildren,
1659
+ parentId: entry.parentId,
1660
+ depth: entry.depth,
1661
+ ...path === void 0 ? {} : { path }
1662
+ };
1663
+ })
1664
+ };
1665
+ }
1666
+ function validateHistoryOptions(options) {
1667
+ if (options === void 0) return;
1668
+ for (const key of [
1669
+ "beforeSeq",
1670
+ "throughSeq",
1671
+ "maxMessages"
1672
+ ]) {
1673
+ const value = options[key];
1674
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value < (key === "throughSeq" ? -1 : key === "maxMessages" ? 1 : 0))) throw nativeError("NATIVE_CLIENT_INVALID_INPUT", `${key} is invalid`);
1675
+ }
1676
+ if (options.turnWindow !== void 0) {
1677
+ if (!Number.isSafeInteger(options.turnWindow.minMessages) || options.turnWindow.minMessages <= 0 || !Number.isSafeInteger(options.turnWindow.minTurns) || options.turnWindow.minTurns <= 0 || options.turnWindow.minMessages > (options.maxMessages ?? 50)) throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "turnWindow is invalid");
1678
+ }
1679
+ }
1680
+ function ordinaryAddress(sessionId) {
1681
+ return {
1682
+ kind: "session",
1683
+ sessionId
1684
+ };
1685
+ }
1686
+ function knownSubagentAddress(address) {
1687
+ return {
1688
+ kind: "subagent",
1689
+ parentSessionId: address.parentSessionId,
1690
+ childSessionId: address.childSessionId,
1691
+ mode: address.mode
1692
+ };
1693
+ }
1694
+ function historyRequest(address, options) {
1695
+ return {
1696
+ address,
1697
+ ...options?.beforeSeq === void 0 ? {} : { beforeSeq: options.beforeSeq },
1698
+ ...options?.throughSeq === void 0 ? {} : { throughSeq: options.throughSeq },
1699
+ ...options?.maxMessages === void 0 ? {} : { maxMessages: options.maxMessages },
1700
+ ...options?.turnWindow === void 0 ? {} : { turnWindow: options.turnWindow }
1701
+ };
1702
+ }
1703
+ async function readHistory(state, request, signal) {
1704
+ if (state.closed) return closedResult();
1705
+ const captured = currentGeneration(state);
1706
+ if (captured === void 0) return unavailableResult("NATIVE_DISCONNECTED", "No authenticated Host generation is current.");
1707
+ return await settleRead(() => state.remote.session.page(request, signal), captured, state.generation, historyPageOf);
1708
+ }
1709
+ function sameImage(left, right) {
1710
+ return left.attachmentId === right.attachmentId && left.mediaType === right.mediaType && left.bytes === right.bytes && left.width === right.width && left.height === right.height && left.name === right.name;
1711
+ }
1712
+ function imageRefOf(value) {
1713
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
1714
+ const ref = value;
1715
+ if (typeof ref.attachmentId !== "string" || typeof ref.bytes !== "number" || !Number.isSafeInteger(ref.bytes) || ref.bytes < 0 || typeof ref.width !== "number" || !Number.isSafeInteger(ref.width) || ref.width < 0 || typeof ref.height !== "number" || !Number.isSafeInteger(ref.height) || ref.height < 0 || ref.mediaType !== "image/png" && ref.mediaType !== "image/jpeg" && ref.mediaType !== "image/webp" && ref.mediaType !== "image/gif") return;
1716
+ const name = optionalString(ref, "name");
1717
+ const original = ref.originalDimensions;
1718
+ if (original !== void 0) {
1719
+ const dimensions = recordOf(original, "original dimensions");
1720
+ if (typeof dimensions.width !== "number" || typeof dimensions.height !== "number") return void 0;
1721
+ return {
1722
+ attachmentId: ref.attachmentId,
1723
+ mediaType: ref.mediaType,
1724
+ bytes: ref.bytes,
1725
+ width: ref.width,
1726
+ height: ref.height,
1727
+ ...name === void 0 ? {} : { name },
1728
+ originalDimensions: {
1729
+ width: dimensions.width,
1730
+ height: dimensions.height
1731
+ }
1732
+ };
1733
+ }
1734
+ return {
1735
+ attachmentId: ref.attachmentId,
1736
+ mediaType: ref.mediaType,
1737
+ bytes: ref.bytes,
1738
+ width: ref.width,
1739
+ height: ref.height,
1740
+ ...name === void 0 ? {} : { name }
1741
+ };
1742
+ }
1743
+ function contentHasImage(content, expected) {
1744
+ if (!Array.isArray(content)) return false;
1745
+ return content.some((part) => {
1746
+ if (typeof part !== "object" || part === null) return false;
1747
+ const record = part;
1748
+ if (record.type !== "image") return false;
1749
+ const ref = imageRefOf(record.attachment);
1750
+ return ref !== void 0 && sameImage(ref, expected);
1751
+ });
1752
+ }
1753
+ function eventHasImage(entry, expected) {
1754
+ if (entry.type !== "event") return false;
1755
+ const data = entry.event.data;
1756
+ if (typeof data !== "object" || data === null || Array.isArray(data)) return false;
1757
+ const record = data;
1758
+ if (contentHasImage(record.content, expected)) return true;
1759
+ if (entry.event.type === "agent/inbox/spliced" && Array.isArray(record.inserted)) return record.inserted.some((message) => {
1760
+ if (typeof message !== "object" || message === null || Array.isArray(message)) return false;
1761
+ return contentHasImage(message.content, expected);
1762
+ });
1763
+ return false;
1764
+ }
1765
+ var OwnedNativeSession = class {
1766
+ lifetime = new AbortController();
1767
+ subscriptions = /* @__PURE__ */ new Set();
1768
+ operations = /* @__PURE__ */ new Set();
1769
+ closed = false;
1770
+ closePromise;
1771
+ state;
1772
+ reference;
1773
+ binding;
1774
+ historyAddress;
1775
+ constructor(state, reference, binding, historyAddress) {
1776
+ this.state = state;
1777
+ this.reference = reference;
1778
+ this.binding = binding;
1779
+ this.historyAddress = historyAddress;
1780
+ }
1781
+ get sessionId() {
1782
+ return this.reference.sessionId;
1783
+ }
1784
+ get isClosed() {
1785
+ return this.closed;
1786
+ }
1787
+ matchesSession(session) {
1788
+ return this.binding.session === session;
1789
+ }
1790
+ bindingIdentity() {
1791
+ return this.binding;
1792
+ }
1793
+ isCurrentBinding() {
1794
+ return this.state.sessions.binding(this.sessionId) === this.binding;
1795
+ }
1796
+ lifetimeSignal() {
1797
+ return this.lifetime.signal;
1798
+ }
1799
+ continuedCalls() {
1800
+ if (this.closed || this.state.closed || !isInitialGenerationCurrent(this.state) || !this.isCurrentBinding()) return [];
1801
+ return userQuestionsOf(this.projection("userQuestions")).active;
1802
+ }
1803
+ observeOfficialQuestionFacts(listener) {
1804
+ const questions = this.binding.session.projections.faceOf("userQuestions");
1805
+ const inbox = this.binding.session.projections.faceOf("inbox");
1806
+ const offQuestions = questions.subscribe(listener);
1807
+ const offInbox = inbox.subscribe(listener);
1808
+ return () => {
1809
+ offQuestions();
1810
+ offInbox();
1811
+ };
1812
+ }
1813
+ continuedEligible(callId) {
1814
+ if (this.closed || this.state.closed || !isInitialGenerationCurrent(this.state) || !this.isCurrentBinding()) return false;
1815
+ try {
1816
+ const questions = userQuestionsOf(this.projection("userQuestions"));
1817
+ if (questions.settled.some((entry) => entry.callId === callId) || !questions.active.some((entry) => entry.callId === callId && entry.state === "continued")) return false;
1818
+ const inbox = inboxOf(this.projection("inbox"));
1819
+ if (inbox === void 0) return false;
1820
+ return ![...inbox["next-turn"], ...inbox["next-step"]].some((message) => queuedQuestionReply(message, callId));
1821
+ } catch {
1822
+ return false;
1823
+ }
1824
+ }
1825
+ track(operation) {
1826
+ this.operations.add(operation);
1827
+ observeSettled(operation, () => {
1828
+ this.operations.delete(operation);
1829
+ });
1830
+ return operation;
1831
+ }
1832
+ signal(signal) {
1833
+ return signal === void 0 ? this.lifetime.signal : AbortSignal.any([this.lifetime.signal, signal]);
1834
+ }
1835
+ recheck(generation) {
1836
+ if (this.closed || this.state.closed) return this.closed ? closedSessionResult() : closedResult();
1837
+ if (!Object.is(generation, currentGeneration(this.state)) || !isInitialGenerationCurrent(this.state)) return staleResult();
1838
+ if (this.state.sessions.binding(this.sessionId) !== this.binding) return {
1839
+ kind: "stale",
1840
+ code: "NATIVE_BINDING_STALE",
1841
+ message: "The owned Session binding is no longer current."
1842
+ };
1843
+ }
1844
+ admission(signal) {
1845
+ if (this.closed || this.state.closed) return this.closed ? closedSessionResult() : closedResult();
1846
+ if (signal?.aborted) return notDispatchedResult("NATIVE_OPERATION_CANCELLED", "The operation was cancelled before dispatch.");
1847
+ if (!isInitialGenerationCurrent(this.state)) return staleResult();
1848
+ if (this.state.sessions.binding(this.sessionId) !== this.binding) return {
1849
+ kind: "stale",
1850
+ code: "NATIVE_BINDING_STALE",
1851
+ message: "The owned Session binding is no longer current."
1852
+ };
1853
+ return {
1854
+ signal: this.signal(signal),
1855
+ generation: currentGeneration(this.state)
1856
+ };
1857
+ }
1858
+ projection(key) {
1859
+ return this.binding.session.projections.faceOf(key).getSnapshot();
1860
+ }
1861
+ projectionFacts() {
1862
+ const projection = this.state.sessions.list.getSnapshot().projectionsBySession[this.sessionId];
1863
+ return {
1864
+ state: projection?.state ?? "idle",
1865
+ error: projection?.error ?? null,
1866
+ values: NATIVE_PROJECTION_KEYS.map((key) => this.projection(key))
1867
+ };
1868
+ }
1869
+ snapshot() {
1870
+ const admission = this.admission();
1871
+ if ("kind" in admission) return admission;
1872
+ try {
1873
+ const snapshot = this.binding.session.getSnapshot();
1874
+ const projection = this.projectionFacts();
1875
+ const includeValues = projection.state === "ready" || snapshot.openState === "open" && projection.state === "idle";
1876
+ const [title, plan, tokenUsage, contextPressure, userQuestions, inbox] = projection.values;
1877
+ const values = includeValues ? {
1878
+ ...title === void 0 ? {} : { title: nullableStringOf(title, "title projection") },
1879
+ ...plan === void 0 ? {} : { plan: planOf(plan) },
1880
+ ...tokenUsage === void 0 ? {} : { tokenUsage: tokenUsageOf(tokenUsage) },
1881
+ ...contextPressure === void 0 ? {} : { contextPressure: contextPressureOf(contextPressure) },
1882
+ ...userQuestions === void 0 ? {} : { userQuestions: userQuestionsOf(userQuestions) },
1883
+ ...inbox === void 0 ? {} : { inbox: inboxOf(inbox) }
1884
+ } : {};
1885
+ return {
1886
+ kind: "ok",
1887
+ value: {
1888
+ sessionId: snapshot.sessionId,
1889
+ pendingSubmissions: snapshot.pendingSubmissions.map((submission) => ({
1890
+ requestId: submission.requestId,
1891
+ placement: submission.placement,
1892
+ time: submission.time,
1893
+ text: submission.text,
1894
+ attachments: submission.attachments.map((attachment) => attachment.type === "file" ? {
1895
+ type: "file",
1896
+ value: {
1897
+ attachmentId: attachment.value.attachmentId,
1898
+ name: attachment.value.name,
1899
+ bytes: attachment.value.bytes
1900
+ }
1901
+ } : {
1902
+ type: "image",
1903
+ value: {
1904
+ ...typeof attachment.value.previewUrl === "string" && attachment.value.previewUrl !== "" ? { previewUrl: attachment.value.previewUrl } : {},
1905
+ ...attachment.value.name === void 0 ? {} : { name: attachment.value.name },
1906
+ ...attachment.value.width === void 0 ? {} : { width: attachment.value.width },
1907
+ ...attachment.value.height === void 0 ? {} : { height: attachment.value.height }
1908
+ }
1909
+ })
1910
+ })),
1911
+ running: snapshot.running,
1912
+ subagent: snapshot.subagent === null ? null : {
1913
+ parentSessionId: snapshot.subagent.address.parentSessionId,
1914
+ childSessionId: snapshot.subagent.address.childSessionId,
1915
+ mode: snapshot.subagent.address.mode
1916
+ },
1917
+ removed: snapshot.removed,
1918
+ openState: snapshot.openState,
1919
+ openError: snapshot.openError === null ? null : failureDtoOf(snapshot.openError),
1920
+ hasMore: snapshot.hasMore,
1921
+ historyWasPartial: snapshot.historyWasPartial,
1922
+ loadingOlder: snapshot.loadingOlder,
1923
+ historyLoadStatus: snapshot.historyLoadStatus,
1924
+ promptError: snapshot.promptError === null ? null : {
1925
+ op: snapshot.promptError.op,
1926
+ error: failureDtoOf(snapshot.promptError.error)
1927
+ },
1928
+ blank: snapshot.blank,
1929
+ lastAgentError: snapshot.lastAgentError,
1930
+ promptAttempted: snapshot.promptAttempted,
1931
+ awaitingFirstTurn: snapshot.awaitingFirstTurn,
1932
+ projections: {
1933
+ state: projection.state,
1934
+ ...values
1935
+ }
1936
+ }
1937
+ };
1938
+ } catch {
1939
+ return unavailableResult("NATIVE_INVALID_RESPONSE", "The official Session snapshot is unusable.");
1940
+ }
1941
+ }
1942
+ async history(options) {
1943
+ const admission = this.admission();
1944
+ if ("kind" in admission) return admission;
1945
+ validateHistoryOptions(options);
1946
+ const result = await this.track(readHistory(this.state, historyRequest(this.historyAddress, options), admission.signal));
1947
+ if (result.kind !== "ok") return result;
1948
+ return this.recheck(admission.generation) ?? result;
1949
+ }
1950
+ subscribe(listener) {
1951
+ if (this.closed || this.state.closed) {
1952
+ listener(this.closed ? closedSessionResult() : closedResult());
1953
+ return () => {};
1954
+ }
1955
+ let released = false;
1956
+ let initialized = false;
1957
+ let projection;
1958
+ let deliveredSessionFacts;
1959
+ let deliveredProjectionValues;
1960
+ let deliveredProjectionState;
1961
+ let deliveredProjectionError;
1962
+ const offs = [];
1963
+ const release = () => {
1964
+ if (released) return;
1965
+ released = true;
1966
+ for (const off of offs) {
1967
+ this.subscriptions.delete(off);
1968
+ off();
1969
+ }
1970
+ offs.length = 0;
1971
+ };
1972
+ const terminal = (result) => {
1973
+ if (released) return;
1974
+ release();
1975
+ try {
1976
+ listener(result);
1977
+ } catch (error) {
1978
+ this.state.diag.error("native-client: Session listener failed", { error: safeErrorMessage(error) });
1979
+ }
1980
+ };
1981
+ if (!isInitialGenerationCurrent(this.state)) {
1982
+ terminal(staleResult());
1983
+ return () => {};
1984
+ }
1985
+ if (this.state.sessions.binding(this.sessionId) !== this.binding) {
1986
+ terminal({
1987
+ kind: "stale",
1988
+ code: "NATIVE_BINDING_STALE",
1989
+ message: "The owned Session binding is no longer current."
1990
+ });
1991
+ return () => {};
1992
+ }
1993
+ const notify = () => {
1994
+ if (released || this.closed || this.state.closed) return;
1995
+ const failure = this.recheck(this.state.initialGeneration);
1996
+ if (failure !== void 0) {
1997
+ terminal(failure);
1998
+ return;
1999
+ }
2000
+ let result;
2001
+ try {
2002
+ const source = this.binding.eventSource.getSnapshot();
2003
+ const sessionFacts = sessionSnapshotFacts(this.binding.session.getSnapshot());
2004
+ const facts = this.projectionFacts();
2005
+ const sourceChanged = projection === void 0 || !Object.is(source, projection.source);
2006
+ const stateChanged = !initialized || sessionFacts.length !== deliveredSessionFacts?.length || sessionFacts.some((value, index) => !Object.is(value, deliveredSessionFacts?.[index])) || facts.state !== deliveredProjectionState || !Object.is(facts.error, deliveredProjectionError) || facts.values.length !== deliveredProjectionValues?.length || facts.values.some((value, index) => !Object.is(value, deliveredProjectionValues?.[index]));
2007
+ if (!sourceChanged && !stateChanged) return;
2008
+ const nextProjection = projectNativeSessionWindow(source, projection, true);
2009
+ const snapshot = this.snapshot();
2010
+ if (snapshot.kind !== "ok") throw nativeError(snapshot.code, snapshot.message);
2011
+ result = {
2012
+ kind: "ok",
2013
+ value: {
2014
+ sessionId: this.sessionId,
2015
+ snapshot: snapshot.value,
2016
+ window: nextProjection.window,
2017
+ reconcileRequired: nextProjection.reconcileRequired
2018
+ }
2019
+ };
2020
+ projection = nextProjection;
2021
+ deliveredSessionFacts = sessionFacts;
2022
+ deliveredProjectionValues = facts.values;
2023
+ deliveredProjectionState = facts.state;
2024
+ deliveredProjectionError = facts.error;
2025
+ initialized = true;
2026
+ } catch {
2027
+ result = unavailableResult("NATIVE_INVALID_RESPONSE", "The official Session window is unusable.");
2028
+ }
2029
+ try {
2030
+ listener(result);
2031
+ } catch (error) {
2032
+ this.state.diag.error("native-client: Session listener failed", { error: safeErrorMessage(error) });
2033
+ release();
2034
+ return;
2035
+ }
2036
+ if (result.kind !== "ok") release();
2037
+ };
2038
+ try {
2039
+ offs.push(this.binding.session.subscribe(() => {
2040
+ notify();
2041
+ }));
2042
+ for (const key of NATIVE_PROJECTION_KEYS) offs.push(this.binding.session.projections.faceOf(key).subscribe(() => {
2043
+ notify();
2044
+ }));
2045
+ offs.push(this.state.sessions.list.subscribe(() => {
2046
+ notify();
2047
+ }));
2048
+ offs.push(this.binding.eventSource.subscribe(() => {
2049
+ notify();
2050
+ }));
2051
+ offs.push(this.state.generation.subscribe(() => {
2052
+ notify();
2053
+ }));
2054
+ for (const off of offs) this.subscriptions.add(off);
2055
+ } catch (error) {
2056
+ for (const off of offs.reverse()) off();
2057
+ throw error;
2058
+ }
2059
+ notify();
2060
+ return release;
2061
+ }
2062
+ async prompt(input) {
2063
+ if (!Array.isArray(input.content) || input.content.length === 0) throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "prompt content must contain at least one part");
2064
+ const mode = input.mode ?? "queue";
2065
+ if (mode !== "queue" && mode !== "steer") throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "prompt mode is invalid");
2066
+ const admission = this.admission(input.signal);
2067
+ if ("kind" in admission) return asPromptFailure(admission);
2068
+ const signal = admission.signal;
2069
+ return await this.track((async () => {
2070
+ const content = [];
2071
+ const echoAttachments = [];
2072
+ let text = "";
2073
+ try {
2074
+ for (const part of input.content) {
2075
+ if (typeof part !== "object" || part === null) throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "prompt parts must be objects");
2076
+ switch (part.type) {
2077
+ case "text":
2078
+ if (typeof part.text !== "string") throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "text prompt part must contain text");
2079
+ break;
2080
+ case "image":
2081
+ if (!(part.bytes instanceof Uint8Array)) throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "attachment bytes must be Uint8Array");
2082
+ if (part.mediaType !== "image/png" && part.mediaType !== "image/jpeg" && part.mediaType !== "image/webp" && part.mediaType !== "image/gif") throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "image media type is invalid");
2083
+ if (part.name !== void 0 && typeof part.name !== "string") throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "image name must be a string");
2084
+ break;
2085
+ case "file":
2086
+ if (!(part.bytes instanceof Uint8Array)) throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "attachment bytes must be Uint8Array");
2087
+ requireNonEmpty(part.name, "file name");
2088
+ break;
2089
+ default: throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "prompt part type is invalid");
2090
+ }
2091
+ }
2092
+ for (const part of input.content) switch (part.type) {
2093
+ case "text":
2094
+ text += part.text;
2095
+ content.push({
2096
+ type: "text",
2097
+ text: part.text
2098
+ });
2099
+ break;
2100
+ case "image":
2101
+ content.push({
2102
+ type: "image",
2103
+ mediaType: part.mediaType,
2104
+ data: Buffer.from(part.bytes.buffer, part.bytes.byteOffset, part.bytes.byteLength).toString("base64"),
2105
+ ...part.name === void 0 ? {} : { name: part.name }
2106
+ });
2107
+ echoAttachments.push({
2108
+ type: "image",
2109
+ value: {
2110
+ previewUrl: "",
2111
+ ...part.name === void 0 ? {} : { name: part.name }
2112
+ }
2113
+ });
2114
+ break;
2115
+ case "file": {
2116
+ const interrupted = this.recheck(admission.generation);
2117
+ if (interrupted !== void 0) return asPromptFailure(interrupted);
2118
+ const uploaded = await this.state.uploader.upload(this.sessionId, {
2119
+ name: part.name,
2120
+ byteLength: part.bytes.byteLength,
2121
+ source: {
2122
+ kind: "client-stream",
2123
+ open: () => (async function* () {
2124
+ yield part.bytes;
2125
+ })()
2126
+ }
2127
+ }, signal);
2128
+ content.push({
2129
+ type: "file",
2130
+ receiptId: uploaded.receiptId
2131
+ });
2132
+ echoAttachments.push({
2133
+ type: "file",
2134
+ value: {
2135
+ ...uploaded.file,
2136
+ attachmentId: uploaded.file.attachmentId
2137
+ }
2138
+ });
2139
+ break;
2140
+ }
2141
+ }
2142
+ } catch (error) {
2143
+ if (signal.aborted) return asPromptFailure(unavailableResult("NATIVE_PROMPT_STAGING_INTERRUPTED", "The prompt was not dispatched; attachment staging was interrupted after it began."));
2144
+ return asPromptFailure(notDispatchedResult(remoteFailureCode(error) ?? "NATIVE_PROMPT_STAGING_FAILED", "The prompt was not dispatched; attachment staging did not return a usable receipt."));
2145
+ }
2146
+ if (signal.aborted) return asPromptFailure(notDispatchedResult("NATIVE_OPERATION_CANCELLED", "The operation was cancelled before dispatch."));
2147
+ const interrupted = this.recheck(admission.generation);
2148
+ if (interrupted !== void 0) return asPromptFailure(interrupted);
2149
+ let accepted = false;
2150
+ const submission = this.binding.session.beginSubmission({
2151
+ mode,
2152
+ text,
2153
+ attachments: echoAttachments,
2154
+ onAccept: () => {
2155
+ accepted = true;
2156
+ }
2157
+ });
2158
+ let dispatched = false;
2159
+ try {
2160
+ dispatched = true;
2161
+ const result = await this.binding.session.prompt(content, mode, signal, submission.requestId);
2162
+ if (accepted) return {
2163
+ kind: "accepted",
2164
+ requestId: submission.requestId
2165
+ };
2166
+ if (!result.ok) return nativePromptWriteFailure(classifyRemoteWriteFailure(result.error), submission.requestId);
2167
+ return {
2168
+ kind: "unknown",
2169
+ code: "NATIVE_ACCEPTANCE_UNCONFIRMED",
2170
+ message: "The prompt reply arrived without official acceptance evidence.",
2171
+ requestId: submission.requestId
2172
+ };
2173
+ } catch (error) {
2174
+ if (accepted) return {
2175
+ kind: "accepted",
2176
+ requestId: submission.requestId
2177
+ };
2178
+ if (!dispatched) return asPromptFailure(notDispatchedResult("NATIVE_PROMPT_NOT_DISPATCHED", "The prompt was not dispatched."));
2179
+ return {
2180
+ kind: "unknown",
2181
+ ...failureOf(error, "NATIVE_PROMPT_OUTCOME_UNKNOWN", "The prompt outcome could not be determined.", false),
2182
+ requestId: submission.requestId
2183
+ };
2184
+ } finally {
2185
+ if (!dispatched) submission.abandon();
2186
+ }
2187
+ })());
2188
+ }
2189
+ async resolvePrompt(requestId, options) {
2190
+ requireNonEmpty(requestId, "requestId");
2191
+ const maxMessages = options?.maxMessages ?? 200;
2192
+ const pageLimit = options?.pageLimit ?? 20;
2193
+ validateHistoryOptions({ maxMessages });
2194
+ if (!Number.isSafeInteger(pageLimit) || pageLimit <= 0) throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "pageLimit is invalid");
2195
+ const admission = this.admission();
2196
+ if ("kind" in admission) return asPromptResolutionFailure(admission, requestId);
2197
+ const operation = (async () => {
2198
+ try {
2199
+ const snapshot = this.binding.session.getSnapshot();
2200
+ if (snapshot.subagent !== null) return asPromptResolutionFailure(unsupportedResult("NATIVE_PROMPT_RESOLUTION_SUBAGENT_UNSUPPORTED", "Prompt resolution is supported only for an ordinary root Session."), requestId);
2201
+ if (snapshot.pendingSubmissions.some((submission) => submission.requestId === requestId)) return {
2202
+ kind: "accepted",
2203
+ requestId,
2204
+ value: {
2205
+ source: "accepted-echo",
2206
+ requestId
2207
+ }
2208
+ };
2209
+ } catch {
2210
+ return asPromptResolutionFailure(unavailableResult("NATIVE_INVALID_RESPONSE", "The official Session snapshot is unusable."), requestId);
2211
+ }
2212
+ const pages = [];
2213
+ let throughSeq;
2214
+ let beforeSeq;
2215
+ for (let pageNumber = 0; pageNumber < pageLimit; pageNumber += 1) {
2216
+ const interrupted = this.recheck(admission.generation);
2217
+ if (interrupted !== void 0) return asPromptResolutionFailure(interrupted, requestId);
2218
+ const page = await readHistory(this.state, historyRequest(ordinaryAddress(this.sessionId), {
2219
+ maxMessages,
2220
+ ...throughSeq === void 0 ? {} : { throughSeq },
2221
+ ...beforeSeq === void 0 ? {} : { beforeSeq }
2222
+ }), admission.signal);
2223
+ if (page.kind !== "ok") {
2224
+ const failure = this.recheck(admission.generation) ?? page;
2225
+ return failure.kind === "rejected" ? {
2226
+ kind: "unknown",
2227
+ requestId,
2228
+ code: failure.code,
2229
+ message: failure.message
2230
+ } : asPromptResolutionFailure(failure, requestId);
2231
+ }
2232
+ const interruptedAfterRead = this.recheck(admission.generation);
2233
+ if (interruptedAfterRead !== void 0) return asPromptResolutionFailure(interruptedAfterRead, requestId);
2234
+ const pageEvents = [];
2235
+ for (const entry of page.value.records) if (entry.type === "event") pageEvents.push(entry.event);
2236
+ pages.push(pageEvents);
2237
+ throughSeq ??= page.value.cursor;
2238
+ if (!page.value.hasMore) {
2239
+ const events = pages.slice().reverse().flat();
2240
+ let resolution;
2241
+ try {
2242
+ resolution = promptResolutionOf(events, requestId);
2243
+ } catch {
2244
+ return asPromptResolutionFailure(unavailableResult("NATIVE_INVALID_RESPONSE", "The official prompt evidence is unusable."), requestId);
2245
+ }
2246
+ if (resolution === void 0) return {
2247
+ kind: "unknown",
2248
+ requestId,
2249
+ code: "NATIVE_PROMPT_NOT_OBSERVED",
2250
+ message: "The complete fixed Session cut contains no positive evidence for this request."
2251
+ };
2252
+ const interruptedBeforePublish = this.recheck(admission.generation);
2253
+ if (interruptedBeforePublish !== void 0) return asPromptResolutionFailure(interruptedBeforePublish, requestId);
2254
+ return {
2255
+ kind: "accepted",
2256
+ requestId,
2257
+ value: resolution
2258
+ };
2259
+ }
2260
+ const first = page.value.records[0];
2261
+ if (first?.type !== "event") return asPromptResolutionFailure(unavailableResult("NATIVE_PROMPT_HISTORY_STALLED", "The official history did not advance while resolving the prompt."), requestId);
2262
+ const next = first.event.seq;
2263
+ if (next <= 0 || beforeSeq !== void 0 && next >= beforeSeq) return asPromptResolutionFailure(unavailableResult("NATIVE_PROMPT_HISTORY_STALLED", "The official history did not advance while resolving the prompt."), requestId);
2264
+ beforeSeq = next;
2265
+ }
2266
+ return {
2267
+ kind: "unknown",
2268
+ requestId,
2269
+ code: "NATIVE_PROMPT_HISTORY_INCOMPLETE",
2270
+ message: "The bounded history scan ended before the fixed Session cut was complete."
2271
+ };
2272
+ })();
2273
+ return await this.track(operation);
2274
+ }
2275
+ async cancel() {
2276
+ const admission = this.admission();
2277
+ if ("kind" in admission) return admission;
2278
+ return await this.track(settleWrite(() => abortable(this.binding.session.cancel(), admission.signal), "accepted", () => void 0));
2279
+ }
2280
+ async updateQueue(itemId, action) {
2281
+ requireNonEmpty(itemId, "itemId");
2282
+ if (action.kind === "edit" && (action.content.length === 0 || action.content.some((block) => block.type !== "text" || block.text.trim() === ""))) throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "queue edits require non-empty text content");
2283
+ const admission = this.admission();
2284
+ if ("kind" in admission) return admission;
2285
+ return await this.track(settleWrite(() => abortable(this.binding.session.updateQueue(itemId, action), admission.signal), "accepted", () => void 0));
2286
+ }
2287
+ async rename(title) {
2288
+ requireNonEmpty(title, "title");
2289
+ const admission = this.admission();
2290
+ if ("kind" in admission) return admission;
2291
+ return await this.track(settleWrite(() => abortable(this.binding.session.rename(title), admission.signal), "committed", (value) => ({
2292
+ title: value.title,
2293
+ seq: value.seq
2294
+ })));
2295
+ }
2296
+ async readConfigurationValues(admission) {
2297
+ const interrupted = this.recheck(admission.generation);
2298
+ if (interrupted !== void 0) return interrupted;
2299
+ return await settleRead(() => this.state.remote.session.projections({ sessionId: this.sessionId }, admission.signal), admission.generation, this.state.generation, (value) => {
2300
+ const values = sequencedConfigurationValues(value);
2301
+ if (values === void 0) throw new Error("exact Session projections are unavailable");
2302
+ return values;
2303
+ });
2304
+ }
2305
+ async selectModel(input) {
2306
+ requireNonEmpty(input.provider, "provider");
2307
+ requireNonEmpty(input.model, "model");
2308
+ if (input.reasoningEffort !== void 0) requireNonEmpty(input.reasoningEffort, "reasoningEffort");
2309
+ const admission = this.admission();
2310
+ if ("kind" in admission) return admission;
2311
+ return await this.track(settleWrite(() => abortable(this.state.remote.session.selectModel({
2312
+ sessionId: this.sessionId,
2313
+ provider: input.provider,
2314
+ model: input.model,
2315
+ ...input.reasoningEffort === void 0 ? {} : { reasoningEffort: input.reasoningEffort }
2316
+ }), admission.signal), "committed", (value) => modelSelectionOf(value.selected), classifyRemoteModelFailure));
2317
+ }
2318
+ async selectPreset(presetId) {
2319
+ requireNonEmpty(presetId, "presetId");
2320
+ const admission = this.admission();
2321
+ if ("kind" in admission) return admission;
2322
+ return await this.track(settleWrite(() => abortable(this.state.remote.agentPresets.select(this.sessionId, presetId), admission.signal), "committed", (value) => {
2323
+ if (typeof value !== "string" || value === "") throw new TypeError("invalid preset result");
2324
+ return value;
2325
+ }, classifyRemotePresetFailure));
2326
+ }
2327
+ async execute(line, admission, classify = classifyRemoteWriteFailure) {
2328
+ const interrupted = this.recheck(admission.generation);
2329
+ if (interrupted !== void 0) return interrupted;
2330
+ let result;
2331
+ try {
2332
+ result = await this.state.remote.commands.execute(this.sessionId, line, [], admission.signal);
2333
+ } catch (error) {
2334
+ return unknownResult(failureOf(error, "NATIVE_COMMAND_OUTCOME_UNKNOWN", "The command outcome could not be determined.", false));
2335
+ }
2336
+ if (!result.ok) return nativeWriteFailure(classify(result.error));
2337
+ if (result.value === void 0) return {
2338
+ kind: "committed",
2339
+ value: { matched: false }
2340
+ };
2341
+ try {
2342
+ return {
2343
+ kind: "committed",
2344
+ value: commandExecutionOf(result.value)
2345
+ };
2346
+ } catch {
2347
+ return unknownResult({
2348
+ code: "NATIVE_INVALID_RESPONSE",
2349
+ message: "The official command returned an unusable execution."
2350
+ });
2351
+ }
2352
+ }
2353
+ async command(line) {
2354
+ requireNonEmpty(line, "line");
2355
+ if (!line.startsWith("/")) throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "command line must start with a slash");
2356
+ const admission = this.admission();
2357
+ if ("kind" in admission) return admission;
2358
+ return await this.track(this.execute(line, admission));
2359
+ }
2360
+ async commandDefinition(admission, name) {
2361
+ return await settleRead(() => abortable(this.state.remote.commands.list(this.sessionId), admission.signal), admission.generation, this.state.generation, (value) => value.map(commandDescriptorOf).find((command) => command.name === name));
2362
+ }
2363
+ async commands() {
2364
+ const admission = this.admission();
2365
+ if ("kind" in admission) return admission;
2366
+ return await this.track(settleRead(() => abortable(this.state.remote.commands.list(this.sessionId), admission.signal), admission.generation, this.state.generation, (value) => value.map(commandDescriptorOf)));
2367
+ }
2368
+ async skills() {
2369
+ const admission = this.admission();
2370
+ if ("kind" in admission) return admission;
2371
+ return await this.track(settleRead(() => abortable(this.state.remote.skills.list({ sessionId: this.sessionId }, admission.signal), admission.signal), admission.generation, this.state.generation, (value) => value.skills.map(skillDescriptorOf)));
2372
+ }
2373
+ async selectPermissionPreset(presetId) {
2374
+ requireNonEmpty(presetId, "presetId");
2375
+ const admission = this.admission();
2376
+ if ("kind" in admission) return admission;
2377
+ const operation = (async () => {
2378
+ const catalog = await settleRead(() => abortable(this.state.remote.permissionPresets.catalog(), admission.signal), admission.generation, this.state.generation, permissionCatalogOf);
2379
+ const catalogInterrupted = this.recheck(admission.generation);
2380
+ if (catalogInterrupted !== void 0) return catalogInterrupted;
2381
+ if (catalog.kind !== "ok") return catalog;
2382
+ if (!catalog.value.options.some((option) => option.value === presetId)) return rejectedResult({
2383
+ code: "NATIVE_PERMISSION_PRESET_UNKNOWN",
2384
+ message: "The permission preset is not in the official catalog."
2385
+ });
2386
+ const command = await this.commandDefinition(admission, "permission");
2387
+ const commandInterrupted = this.recheck(admission.generation);
2388
+ if (commandInterrupted !== void 0) return commandInterrupted;
2389
+ if (command.kind !== "ok") return command;
2390
+ if (command.value === void 0) return unsupportedResult("NATIVE_PERMISSION_COMMAND_UNAVAILABLE", "The official permission command is not registered.");
2391
+ if (command.value.definitionId !== "@deepseek-ai/dsh-permission-presets") return unsupportedResult("NATIVE_PERMISSION_COMMAND_UNSUPPORTED", "The effective permission command is not the official canonical definition.");
2392
+ const execution = await this.execute(`/permission ${presetId}`, admission, classifyConfigurationCommandFailure);
2393
+ if (execution.kind !== "committed") return execution;
2394
+ if ("matched" in execution.value) return unsupportedResult("NATIVE_PERMISSION_COMMAND_UNAVAILABLE", "The official permission command is not registered.");
2395
+ const commandId = execution.value.commandId;
2396
+ if (execution.value.result.kind === "error") return unknownResult({
2397
+ code: "NATIVE_PERMISSION_COMMAND_OUTCOME_UNKNOWN",
2398
+ message: execution.value.result.text
2399
+ }, { commandId });
2400
+ const projections = await this.readConfigurationValues(admission);
2401
+ if (this.recheck(admission.generation) !== void 0) return unknownResult({
2402
+ code: "NATIVE_CONFIG_READBACK_STALE",
2403
+ message: "The permission command settled but its Session readback is no longer current."
2404
+ }, { commandId });
2405
+ if (projections.kind !== "ok") return unknownResult({
2406
+ code: "NATIVE_CONFIG_READBACK_FAILED",
2407
+ message: "The permission command settled but its Session readback is unavailable."
2408
+ }, { commandId });
2409
+ if (projections.value.permissions === void 0) return unknownResult({
2410
+ code: "NATIVE_CONFIG_READBACK_MISSING",
2411
+ message: "The official permission projection is absent after the command."
2412
+ }, { commandId });
2413
+ let selection;
2414
+ try {
2415
+ selection = permissionSelectionOf(projections.value.permissions);
2416
+ } catch {
2417
+ return unknownResult({
2418
+ code: "NATIVE_CONFIG_READBACK_INVALID",
2419
+ message: "The official permission projection is unusable after the command."
2420
+ }, { commandId });
2421
+ }
2422
+ if (selection.currentValue !== presetId) return unknownResult({
2423
+ code: "NATIVE_CONFIG_READBACK_MISMATCH",
2424
+ message: "The official permission readback did not match the accepted selection."
2425
+ }, { commandId });
2426
+ return {
2427
+ kind: "committed",
2428
+ value: selection
2429
+ };
2430
+ })();
2431
+ return await this.track(operation);
2432
+ }
2433
+ async selectPlanMode(active) {
2434
+ const admission = this.admission();
2435
+ if ("kind" in admission) return admission;
2436
+ const operation = (async () => {
2437
+ const command = await this.commandDefinition(admission, "plan");
2438
+ const commandInterrupted = this.recheck(admission.generation);
2439
+ if (commandInterrupted !== void 0) return commandInterrupted;
2440
+ if (command.kind !== "ok") return command;
2441
+ if (command.value === void 0) return unsupportedResult("NATIVE_PLAN_COMMAND_UNAVAILABLE", "The official plan command is not registered.");
2442
+ if (command.value.definitionId !== "@deepseek-ai/dsh-plan-mode") return unsupportedResult("NATIVE_PLAN_COMMAND_UNSUPPORTED", "The effective plan command is not the official canonical definition.");
2443
+ const execution = await this.execute(active ? "/plan" : "/plan off", admission, classifyConfigurationCommandFailure);
2444
+ if (execution.kind !== "committed") return execution;
2445
+ if ("matched" in execution.value) return unsupportedResult("NATIVE_PLAN_COMMAND_UNAVAILABLE", "The official plan command is not registered.");
2446
+ const commandId = execution.value.commandId;
2447
+ if (execution.value.result.kind === "error") return unknownResult({
2448
+ code: "NATIVE_PLAN_COMMAND_OUTCOME_UNKNOWN",
2449
+ message: execution.value.result.text
2450
+ }, { commandId });
2451
+ const projections = await this.readConfigurationValues(admission);
2452
+ if (this.recheck(admission.generation) !== void 0) return unknownResult({
2453
+ code: "NATIVE_CONFIG_READBACK_STALE",
2454
+ message: "The plan command settled but its Session readback is no longer current."
2455
+ }, { commandId });
2456
+ if (projections.kind !== "ok") return unknownResult({
2457
+ code: "NATIVE_CONFIG_READBACK_FAILED",
2458
+ message: "The plan command settled but its Session readback is unavailable."
2459
+ }, { commandId });
2460
+ if (projections.value.plan === void 0) return unknownResult({
2461
+ code: "NATIVE_CONFIG_READBACK_MISSING",
2462
+ message: "The official plan projection is absent after the command."
2463
+ }, { commandId });
2464
+ let plan;
2465
+ try {
2466
+ plan = planOf(projections.value.plan);
2467
+ } catch {
2468
+ return unknownResult({
2469
+ code: "NATIVE_CONFIG_READBACK_INVALID",
2470
+ message: "The official plan projection is unusable after the command."
2471
+ }, { commandId });
2472
+ }
2473
+ if (!(plan.pending ? plan.active !== active : plan.active === active)) return unknownResult({
2474
+ code: "NATIVE_CONFIG_READBACK_MISMATCH",
2475
+ message: "The official plan readback did not confirm the requested mode."
2476
+ }, { commandId });
2477
+ return {
2478
+ kind: "committed",
2479
+ value: plan
2480
+ };
2481
+ })();
2482
+ return await this.track(operation);
2483
+ }
2484
+ async readFile(input) {
2485
+ requireNonEmpty(input.path, "path");
2486
+ if (input.range !== void 0) {
2487
+ for (const value of [input.range.offset, input.range.length]) if (value !== void 0 && (!Number.isSafeInteger(value) || value < 0)) throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "file range is invalid");
2488
+ }
2489
+ const admission = this.admission();
2490
+ if ("kind" in admission) return admission;
2491
+ const range = input.range === void 0 ? void 0 : {
2492
+ ...input.range.offset === void 0 ? {} : { offset: input.range.offset },
2493
+ ...input.range.length === void 0 ? {} : { length: input.range.length }
2494
+ };
2495
+ return await this.track(settleRead(() => this.state.remote.workspaceFiles.readBytes(this.sessionId, input.path, {
2496
+ ...input.baseFile === void 0 ? {} : { baseFile: input.baseFile },
2497
+ ...range === void 0 ? {} : { range }
2498
+ }, admission.signal), admission.generation, this.state.generation, (value) => ({
2499
+ absolutePath: value.absolutePath,
2500
+ version: value.version,
2501
+ ...value.bytes === void 0 ? {} : { bytes: value.bytes },
2502
+ offset: value.offset,
2503
+ data: value.data,
2504
+ eof: value.eof
2505
+ })));
2506
+ }
2507
+ async readAttachment(attachment) {
2508
+ if (attachment.attachmentId === "" || !Number.isSafeInteger(attachment.bytes) || attachment.bytes < 0 || !Number.isSafeInteger(attachment.width) || attachment.width < 0 || !Number.isSafeInteger(attachment.height) || attachment.height < 0 || attachment.mediaType !== "image/png" && attachment.mediaType !== "image/jpeg" && attachment.mediaType !== "image/webp" && attachment.mediaType !== "image/gif") throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "attachment reference is invalid");
2509
+ const officialAttachment = {
2510
+ ...attachment,
2511
+ attachmentId: attachment.attachmentId
2512
+ };
2513
+ const admission = this.admission();
2514
+ if ("kind" in admission) return admission;
2515
+ const operation = (async () => {
2516
+ let beforeSeq;
2517
+ while (true) {
2518
+ const interrupted = this.recheck(admission.generation);
2519
+ if (interrupted !== void 0) return interrupted;
2520
+ const historyOptions = {
2521
+ maxMessages: 50,
2522
+ ...beforeSeq === void 0 ? {} : { beforeSeq }
2523
+ };
2524
+ validateHistoryOptions(historyOptions);
2525
+ const page = await readHistory(this.state, historyRequest(ordinaryAddress(this.sessionId), historyOptions), admission.signal);
2526
+ if (page.kind !== "ok") return page;
2527
+ if (page.value.records.some((entry) => eventHasImage(entry, attachment))) break;
2528
+ const first = page.value.records[0];
2529
+ if (!page.value.hasMore || first === void 0 || first.type !== "event" || first.event.seq === 0) return rejectedResult({
2530
+ code: "NATIVE_ATTACHMENT_NOT_IN_SESSION",
2531
+ message: "The image reference is not present in this Session canonical history."
2532
+ });
2533
+ const next = first.event.seq;
2534
+ if (next === beforeSeq) return rejectedResult({
2535
+ code: "NATIVE_ATTACHMENT_HISTORY_STALLED",
2536
+ message: "The canonical history did not advance."
2537
+ });
2538
+ beforeSeq = next;
2539
+ }
2540
+ const interrupted = this.recheck(admission.generation);
2541
+ if (interrupted !== void 0) return interrupted;
2542
+ return await settleRead(() => abortable(this.binding.session.readAttachment(officialAttachment), admission.signal), admission.generation, this.state.generation, (value) => {
2543
+ const ref = imageRefOf(value.attachment);
2544
+ if (ref === void 0 || !sameImage(ref, attachment)) throw new TypeError("attachment readback mismatch");
2545
+ return {
2546
+ attachment: ref,
2547
+ data: value.data
2548
+ };
2549
+ });
2550
+ })();
2551
+ return await this.track(operation);
2552
+ }
2553
+ observeJobs(listener) {
2554
+ if (this.closed || this.state.closed) {
2555
+ listener(this.closed ? closedSessionResult() : closedResult());
2556
+ return () => {};
2557
+ }
2558
+ if (this.state.sessions.binding(this.sessionId) !== this.binding) {
2559
+ try {
2560
+ listener(staleResult());
2561
+ } catch (error) {
2562
+ this.state.diag.error("native-client: Job listener failed", { error: safeErrorMessage(error) });
2563
+ }
2564
+ return () => {};
2565
+ }
2566
+ const carrierError = this.state.carrierError;
2567
+ if (carrierError === void 0) {
2568
+ listener(unavailableResult("NATIVE_JOBS_UNAVAILABLE", "The official Job stream authority is unavailable."));
2569
+ return () => {};
2570
+ }
2571
+ let released = false;
2572
+ let bindingInvalidated = false;
2573
+ let observedGeneration = currentGeneration(this.state);
2574
+ let openedGeneration;
2575
+ let release;
2576
+ const publish = (result) => {
2577
+ if (released || this.closed || this.state.closed) return;
2578
+ try {
2579
+ listener(result);
2580
+ } catch (error) {
2581
+ this.state.diag.error("native-client: Job listener failed", { error: safeErrorMessage(error) });
2582
+ release();
2583
+ }
2584
+ };
2585
+ const invalidateBinding = () => {
2586
+ if (bindingInvalidated) return;
2587
+ bindingInvalidated = true;
2588
+ publish(staleResult());
2589
+ release();
2590
+ };
2591
+ const stream = this.state.remote.$stream({
2592
+ name: "native-client: Job roster observation",
2593
+ open: (signal) => {
2594
+ if (released || this.closed || this.state.closed) throw new Error("native-client: the Job roster observer is closed");
2595
+ openedGeneration = currentGeneration(this.state);
2596
+ if (openedGeneration === void 0) throw new carrierError("native-client: the Job roster open is waiting for an authenticated generation");
2597
+ if (this.state.sessions.binding(this.sessionId) !== this.binding) throw nativeError("NATIVE_BINDING_STALE", "The owned Session binding is not current for a Job roster open.");
2598
+ return this.state.remote.job.list({ sessionId: this.sessionId }, signal);
2599
+ },
2600
+ ended: (accepted) => accepted ? new carrierError("native-client: the Job roster stream ended after an accepted frame") : /* @__PURE__ */ new Error("native-client: the Job roster stream ended before its opening frame"),
2601
+ carrierFailed: () => {
2602
+ publish(staleResult());
2603
+ }
2604
+ });
2605
+ const offGeneration = this.state.generation.subscribe(() => {
2606
+ const generation = currentGeneration(this.state);
2607
+ if (Object.is(generation, observedGeneration)) return;
2608
+ observedGeneration = generation;
2609
+ if (this.state.sessions.binding(this.sessionId) !== this.binding) {
2610
+ invalidateBinding();
2611
+ return;
2612
+ }
2613
+ if (generation !== void 0) stream.restart();
2614
+ publish(staleResult());
2615
+ });
2616
+ release = () => {
2617
+ if (released) return;
2618
+ released = true;
2619
+ offGeneration();
2620
+ this.subscriptions.delete(release);
2621
+ const disposal = stream.dispose();
2622
+ this.operations.add(disposal);
2623
+ observeSettled(disposal, () => {
2624
+ this.operations.delete(disposal);
2625
+ });
2626
+ runDetached("native-client: Job roster dispose", () => disposal, {
2627
+ diag: this.state.diag,
2628
+ sessionId: () => this.sessionId
2629
+ });
2630
+ };
2631
+ this.subscriptions.add(release);
2632
+ runDetached("native-client: Job roster observation", async () => {
2633
+ try {
2634
+ for await (const item of stream) {
2635
+ if (released || this.closed || this.state.closed) return;
2636
+ const current = currentGeneration(this.state);
2637
+ if (this.state.sessions.binding(this.sessionId) !== this.binding) {
2638
+ invalidateBinding();
2639
+ return;
2640
+ }
2641
+ if (current === void 0 || item.signal.aborted) {
2642
+ publish(staleResult());
2643
+ continue;
2644
+ }
2645
+ if (!Object.is(openedGeneration, current)) {
2646
+ publish(staleResult());
2647
+ continue;
2648
+ }
2649
+ if (item.value.type !== "rows") continue;
2650
+ let value;
2651
+ try {
2652
+ value = item.value.jobs.map(jobOf);
2653
+ } catch {
2654
+ publish(unavailableResult("NATIVE_INVALID_RESPONSE", "The official Job roster row is unusable."));
2655
+ release();
2656
+ return;
2657
+ }
2658
+ item.accept();
2659
+ publish({
2660
+ kind: "ok",
2661
+ value
2662
+ });
2663
+ }
2664
+ } catch (error) {
2665
+ const cause = error instanceof Error ? error.cause : void 0;
2666
+ if (remoteFailureCode(error) === "NATIVE_BINDING_STALE" || remoteFailureCode(cause) === "NATIVE_BINDING_STALE") invalidateBinding();
2667
+ else publish(unavailableResult(remoteFailureCode(error) ?? "NATIVE_JOBS_UNAVAILABLE", "The official Job roster stream is unavailable."));
2668
+ } finally {
2669
+ release();
2670
+ }
2671
+ }, {
2672
+ diag: this.state.diag,
2673
+ sessionId: () => this.sessionId
2674
+ });
2675
+ return release;
2676
+ }
2677
+ observeSubagents(listener) {
2678
+ if (this.closed || this.state.closed) {
2679
+ listener(this.closed ? closedSessionResult() : closedResult());
2680
+ return () => {};
2681
+ }
2682
+ const captured = this.state.initialGeneration;
2683
+ const initialFailure = this.recheck(captured);
2684
+ if (initialFailure !== void 0) {
2685
+ try {
2686
+ listener(initialFailure);
2687
+ } catch (error) {
2688
+ this.state.diag.error("native-client: Subagent listener failed", { error: safeErrorMessage(error) });
2689
+ }
2690
+ return () => {};
2691
+ }
2692
+ if (captured === void 0) return () => {};
2693
+ const jobs = this.state.jobs;
2694
+ if (jobs === void 0) {
2695
+ listener(unsupportedResult("NATIVE_SUBAGENTS_UNAVAILABLE", "The official Jobs service required by subagent observation is unavailable."));
2696
+ return () => {};
2697
+ }
2698
+ const reader = new RemoteTaskReader(this.state.sessions, jobs, this.state.generation);
2699
+ const controller = new AbortController();
2700
+ const observerSignal = AbortSignal.any([controller.signal, this.lifetime.signal]);
2701
+ let released = false;
2702
+ let reading = false;
2703
+ let again = false;
2704
+ const offs = [];
2705
+ const release = () => {
2706
+ if (released) return;
2707
+ released = true;
2708
+ controller.abort(/* @__PURE__ */ new Error("native-client: Subagent observer released"));
2709
+ for (const off of offs) off();
2710
+ reader.dispose();
2711
+ this.subscriptions.delete(release);
2712
+ };
2713
+ const terminal = (result) => {
2714
+ if (released || this.closed || this.state.closed) {
2715
+ release();
2716
+ return;
2717
+ }
2718
+ release();
2719
+ if (this.closed || this.state.closed) return;
2720
+ try {
2721
+ listener(result);
2722
+ } catch (error) {
2723
+ this.state.diag.error("native-client: Subagent listener failed", { error: safeErrorMessage(error) });
2724
+ }
2725
+ };
2726
+ const consumeTrailing = () => {
2727
+ if (again && !released) {
2728
+ again = false;
2729
+ read();
2730
+ }
2731
+ };
2732
+ const activityDeps = {
2733
+ roster: () => this.state.sessions.list.getSnapshot(),
2734
+ parentEvidence: () => {
2735
+ const snapshot = this.binding.session.getSnapshot();
2736
+ return this.isCurrentBinding() && snapshot.openState === "open" && !snapshot.removed;
2737
+ },
2738
+ state: (childId, signal) => this.state.remote.session.state({ sessionId: childId }, signal),
2739
+ isCurrent: () => !released && !this.closed && !this.state.closed && !observerSignal.aborted && this.recheck(captured) === void 0
2740
+ };
2741
+ const read = () => {
2742
+ if (released || this.closed || this.state.closed) return;
2743
+ const interrupted = this.recheck(captured);
2744
+ if (interrupted !== void 0) {
2745
+ terminal(interrupted);
2746
+ return;
2747
+ }
2748
+ if (released || this.closed || this.state.closed) return;
2749
+ if (reading) {
2750
+ again = true;
2751
+ return;
2752
+ }
2753
+ reading = true;
2754
+ const operation = (async () => {
2755
+ const value = await reader.readDescendants(this.sessionId, observerSignal);
2756
+ if (released || this.closed || this.state.closed || observerSignal.aborted) return void 0;
2757
+ const interruptedAfterRead = this.recheck(captured);
2758
+ if (interruptedAfterRead !== void 0) {
2759
+ terminal(interruptedAfterRead);
2760
+ return;
2761
+ }
2762
+ if (value === void 0) return void 0;
2763
+ return await prepareNativeSubagentActivity(value, activityDeps, observerSignal);
2764
+ })().then((prepared) => {
2765
+ reading = false;
2766
+ if (released || this.closed || this.state.closed) return;
2767
+ if (prepared === void 0) {
2768
+ const interrupted = this.recheck(captured);
2769
+ if (interrupted !== void 0) terminal(interrupted);
2770
+ else consumeTrailing();
2771
+ return;
2772
+ }
2773
+ const outcome = settleNativeSubagentActivity(prepared, activityDeps, observerSignal);
2774
+ if (outcome.kind === "abandoned") {
2775
+ const interrupted = this.recheck(captured);
2776
+ if (interrupted !== void 0) terminal(interrupted);
2777
+ else consumeTrailing();
2778
+ return;
2779
+ }
2780
+ let result;
2781
+ try {
2782
+ result = {
2783
+ kind: "ok",
2784
+ value: subagentSnapshotOf(outcome.value)
2785
+ };
2786
+ } catch {
2787
+ result = unavailableResult("NATIVE_INVALID_RESPONSE", "The official subagent snapshot is unusable.");
2788
+ }
2789
+ try {
2790
+ listener(result);
2791
+ } catch (error) {
2792
+ this.state.diag.error("native-client: Subagent listener failed", { error: safeErrorMessage(error) });
2793
+ release();
2794
+ return;
2795
+ }
2796
+ consumeTrailing();
2797
+ }, (error) => {
2798
+ reading = false;
2799
+ if (released || this.closed || this.state.closed || observerSignal.aborted) return;
2800
+ const interruptedAfterRead = this.recheck(captured);
2801
+ if (interruptedAfterRead !== void 0) {
2802
+ terminal(interruptedAfterRead);
2803
+ return;
2804
+ }
2805
+ try {
2806
+ listener(unavailableResult(remoteFailureCode(error) ?? "NATIVE_SUBAGENTS_UNAVAILABLE", "The official subagent catalog is unavailable."));
2807
+ } catch (listenerError) {
2808
+ this.state.diag.error("native-client: Subagent listener failed", { error: safeErrorMessage(listenerError) });
2809
+ release();
2810
+ return;
2811
+ }
2812
+ consumeTrailing();
2813
+ });
2814
+ this.operations.add(operation);
2815
+ observeSettled(operation, () => {
2816
+ this.operations.delete(operation);
2817
+ });
2818
+ };
2819
+ offs.push(this.state.sessions.list.subscribe(read));
2820
+ offs.push(jobs.state.subscribe(read));
2821
+ offs.push(this.state.generation.subscribe(() => {
2822
+ if (released || this.closed || this.state.closed) return;
2823
+ terminal(staleResult());
2824
+ }));
2825
+ this.subscriptions.add(release);
2826
+ read();
2827
+ return release;
2828
+ }
2829
+ close() {
2830
+ if (this.closePromise !== void 0) return this.closePromise;
2831
+ let settle;
2832
+ let fail;
2833
+ this.closePromise = new Promise((resolve, reject) => {
2834
+ settle = resolve;
2835
+ fail = reject;
2836
+ });
2837
+ runOwned("native-client: Session close", async () => {
2838
+ this.closed = true;
2839
+ this.lifetime.abort(/* @__PURE__ */ new Error("native-client: Session closed"));
2840
+ const errors = [];
2841
+ for (const release of [...this.subscriptions]) try {
2842
+ release();
2843
+ } catch (error) {
2844
+ errors.push(error);
2845
+ }
2846
+ this.subscriptions.clear();
2847
+ await Promise.allSettled([...this.operations]);
2848
+ try {
2849
+ this.reference.release();
2850
+ } catch (error) {
2851
+ errors.push(error);
2852
+ }
2853
+ this.state.handles.delete(this);
2854
+ const siblings = this.state.handlesBySession.get(this.sessionId);
2855
+ siblings?.delete(this);
2856
+ if (siblings?.size === 0) this.state.handlesBySession.delete(this.sessionId);
2857
+ this.state.notifyHandles();
2858
+ if (errors.length > 0) {
2859
+ const primary = errors[0] instanceof Error ? errors[0] : new Error(String(errors[0]));
2860
+ for (const error of errors.slice(1)) mergeCause(primary, error);
2861
+ throw primary;
2862
+ }
2863
+ }, {
2864
+ diag: this.state.diag,
2865
+ sessionId: () => this.sessionId,
2866
+ onResult: () => settle(),
2867
+ onError: (error) => fail(error)
2868
+ });
2869
+ return this.closePromise;
2870
+ }
2871
+ };
2872
+ function createNativeInteractionReceivers(state, options) {
2873
+ let disposed = false;
2874
+ let pending = 0;
2875
+ let identityGaps = 0;
2876
+ const owned = [];
2877
+ const changed = () => {
2878
+ if (!disposed) state.notifyStatus();
2879
+ };
2880
+ const liveQuestionCalls = /* @__PURE__ */ new Set();
2881
+ const currentBindingHandle = (sessionId, binding) => [...state.handlesBySession.get(sessionId) ?? []].find((handle) => !handle.isClosed && handle.bindingIdentity() === binding && handle.isCurrentBinding());
2882
+ const continuedFencesValid = (reservation) => {
2883
+ if (disposed || state.closed || reservation.controller.signal.aborted || !Object.is(reservation.generation, currentGeneration(state))) return false;
2884
+ const handle = currentBindingHandle(reservation.sessionId, reservation.binding);
2885
+ return handle !== void 0 && handle.continuedEligible(reservation.callId);
2886
+ };
2887
+ const deliverContinued = async (reservation, callId, questions, onQuestion) => {
2888
+ if (!continuedFencesValid(reservation)) throw nativeError("NATIVE_INTERACTION_STALE", "the continued Question answer is no longer current");
2889
+ const lifetime = AbortSignal.any([reservation.controller.signal, state.lifetime.signal]);
2890
+ const answer = await abortable(onQuestion({
2891
+ sessionId: reservation.sessionId,
2892
+ callId,
2893
+ timed: true,
2894
+ questions,
2895
+ signal: lifetime
2896
+ }), lifetime);
2897
+ if (!continuedFencesValid(reservation) || lifetime.aborted) throw nativeError("NATIVE_INTERACTION_STALE", "the continued Question answer is no longer current");
2898
+ const result = await state.remote.userQuestions.answer(reservation.sessionId, callId, { answers: officialQuestionAnswers(answer) });
2899
+ if (!result.ok) throw nativeError(remoteFailureCode(result.error) ?? "NATIVE_QUESTION_ANSWER_FAILED", "The continued Question answer was not accepted.");
2900
+ if (result.value !== true) throw nativeError("NATIVE_QUESTION_NOT_CONTINUED", "The continued Question was no longer answerable.");
2901
+ };
2902
+ let continued;
2903
+ if (options.onQuestion !== void 0) {
2904
+ const onQuestion = options.onQuestion;
2905
+ continued = createNativeContinuedQuestionReceiver({
2906
+ generation: state.generation,
2907
+ handles: state.handles,
2908
+ handlesBySession: state.handlesBySession,
2909
+ handleListeners: state.handleListeners,
2910
+ isClosed: () => state.closed,
2911
+ onInvalidProjection: (error) => {
2912
+ state.diag.error("native-client: continued Question projection was unusable", { error: safeErrorMessage(error) });
2913
+ },
2914
+ onOffer: (reservation, callId, questions) => {
2915
+ if (liveQuestionCalls.has(callId) || !continuedFencesValid(reservation)) return false;
2916
+ const operation = Promise.resolve().then(() => deliverContinued(reservation, callId, questions, onQuestion)).finally(() => {
2917
+ pending -= 1;
2918
+ changed();
2919
+ });
2920
+ trackClientOperation(state, operation);
2921
+ pending += 1;
2922
+ changed();
2923
+ runDetached("native-client: continued Question delivery", () => operation, {
2924
+ diag: state.diag,
2925
+ sessionId: () => reservation.sessionId
2926
+ });
2927
+ return true;
2928
+ }
2929
+ });
2930
+ owned.push(() => continued?.dispose());
2931
+ }
2932
+ const waitForHandle = async (sessionId, session, signal, captured) => {
2933
+ const find = () => [...state.handlesBySession.get(sessionId) ?? []].find((handle) => !handle.isClosed && handle.matchesSession(session));
2934
+ const current = find();
2935
+ if (current !== void 0 && Object.is(captured, currentGeneration(state))) return current;
2936
+ return await new Promise((resolve, reject) => {
2937
+ let settled = false;
2938
+ let offGeneration;
2939
+ const cleanup = () => {
2940
+ state.handleListeners.delete(check);
2941
+ offGeneration?.();
2942
+ signal?.removeEventListener("abort", abort);
2943
+ };
2944
+ const settle = (handle) => {
2945
+ if (settled) return;
2946
+ if (state.closed || disposed) {
2947
+ settled = true;
2948
+ cleanup();
2949
+ reject(nativeError("NATIVE_INTERACTION_CLOSED", "the Native Client closed before the interaction could be attributed"));
2950
+ } else if (handle !== void 0 && Object.is(captured, currentGeneration(state))) {
2951
+ settled = true;
2952
+ cleanup();
2953
+ resolve(handle);
2954
+ } else if (!Object.is(captured, currentGeneration(state))) {
2955
+ settled = true;
2956
+ cleanup();
2957
+ reject(nativeError("NATIVE_INTERACTION_GENERATION_STALE", "the interaction generation was replaced"));
2958
+ }
2959
+ };
2960
+ const abort = () => {
2961
+ if (settled) return;
2962
+ settled = true;
2963
+ cleanup();
2964
+ reject(signal?.reason ?? /* @__PURE__ */ new Error("native-client: interaction aborted"));
2965
+ };
2966
+ const check = () => settle(find());
2967
+ state.handleListeners.add(check);
2968
+ offGeneration = state.generation.subscribe(check);
2969
+ if (signal?.aborted) abort();
2970
+ else signal?.addEventListener("abort", abort, { once: true });
2971
+ check();
2972
+ });
2973
+ };
2974
+ owned.push(state.remote.$on("user-questions/request", async function(request, next) {
2975
+ const sessionId = state.sessions.scopeOf(this);
2976
+ const planIntent = Array.isArray(request.questions) ? request.questions.find((question) => question.intent?.kind === "plan-review")?.intent : void 0;
2977
+ const planCallId = planIntent?.kind === "plan-review" ? planIntent.callId : void 0;
2978
+ const callId = request.wait?.callId ?? planCallId;
2979
+ if (sessionId === void 0 || typeof callId !== "string" || options.onQuestion === void 0) {
2980
+ if (sessionId === void 0 || typeof callId !== "string") identityGaps += 1;
2981
+ changed();
2982
+ return await next();
2983
+ }
2984
+ const captured = currentGeneration(state);
2985
+ const session = state.sessions.sessionOf(this);
2986
+ if (session === void 0) {
2987
+ identityGaps += 1;
2988
+ changed();
2989
+ return await next();
2990
+ }
2991
+ liveQuestionCalls.add(callId);
2992
+ pending += 1;
2993
+ changed();
2994
+ try {
2995
+ const handle = await waitForHandle(sessionId, session, request.signal, captured);
2996
+ const lifetime = request.signal === void 0 ? handle.lifetimeSignal() : AbortSignal.any([request.signal, handle.lifetimeSignal()]);
2997
+ if (disposed || state.closed || handle.isClosed || lifetime.aborted || !Object.is(captured, currentGeneration(state)) || !handle.matchesSession(state.sessions.sessionOf(this))) throw nativeError("NATIVE_INTERACTION_STALE", "the interaction answer is no longer current");
2998
+ const answer = await abortable(options.onQuestion({
2999
+ sessionId,
3000
+ callId,
3001
+ timed: request.wait?.timed === true,
3002
+ questions: questionItemsOf(request.questions),
3003
+ signal: lifetime
3004
+ }), lifetime);
3005
+ if (disposed || state.closed || handle.isClosed || lifetime.aborted || !Object.is(captured, currentGeneration(state)) || !handle.matchesSession(state.sessions.sessionOf(this))) throw nativeError("NATIVE_INTERACTION_STALE", "the interaction answer is no longer current");
3006
+ return { answers: officialQuestionAnswers(answer) };
3007
+ } finally {
3008
+ liveQuestionCalls.delete(callId);
3009
+ pending -= 1;
3010
+ changed();
3011
+ continued?.reconcile();
3012
+ }
3013
+ }));
3014
+ owned.push(state.remote.$on("approval/request", async function(request, next) {
3015
+ const sessionId = state.sessions.scopeOf(this);
3016
+ const callId = request.callId;
3017
+ if (sessionId === void 0 || typeof callId !== "string" || options.onApproval === void 0) {
3018
+ if (sessionId === void 0 || typeof callId !== "string") identityGaps += 1;
3019
+ changed();
3020
+ return await next();
3021
+ }
3022
+ const captured = currentGeneration(state);
3023
+ const session = state.sessions.sessionOf(this);
3024
+ if (session === void 0) {
3025
+ identityGaps += 1;
3026
+ changed();
3027
+ return await next();
3028
+ }
3029
+ pending += 1;
3030
+ changed();
3031
+ try {
3032
+ const handle = await waitForHandle(sessionId, session, request.signal, captured);
3033
+ const lifetime = request.signal === void 0 ? handle.lifetimeSignal() : AbortSignal.any([request.signal, handle.lifetimeSignal()]);
3034
+ if (disposed || state.closed || handle.isClosed || lifetime.aborted || !Object.is(captured, currentGeneration(state)) || !handle.matchesSession(state.sessions.sessionOf(this))) throw nativeError("NATIVE_INTERACTION_STALE", "the approval answer is no longer current");
3035
+ const outcome = await abortable(options.onApproval({
3036
+ sessionId,
3037
+ callId,
3038
+ toolName: request.toolName,
3039
+ ...request.reason === void 0 ? {} : { reason: request.reason },
3040
+ ...request.displayReason === void 0 ? {} : { displayReason: request.displayReason },
3041
+ signal: lifetime
3042
+ }), lifetime);
3043
+ if (disposed || state.closed || handle.isClosed || lifetime.aborted || !Object.is(captured, currentGeneration(state)) || !handle.matchesSession(state.sessions.sessionOf(this))) throw nativeError("NATIVE_INTERACTION_STALE", "the approval answer is no longer current");
3044
+ if (outcome !== "allowed-once" && outcome !== "rejected" && outcome !== "cancelled" && outcome !== "unavailable") throw new TypeError("approval answer: invalid outcome");
3045
+ return outcome;
3046
+ } finally {
3047
+ pending -= 1;
3048
+ changed();
3049
+ }
3050
+ }));
3051
+ return {
3052
+ get pendingCount() {
3053
+ return pending;
3054
+ },
3055
+ get identityGaps() {
3056
+ return identityGaps;
3057
+ },
3058
+ dispose() {
3059
+ if (disposed) return;
3060
+ disposed = true;
3061
+ for (const off of owned.splice(0)) off();
3062
+ changed();
3063
+ }
3064
+ };
3065
+ }
3066
+ async function attachNativeClient(options) {
3067
+ options.signal?.throwIfAborted();
3068
+ validateNodeAndPlatform();
3069
+ const dshAnchor = validateDshAnchor(options.dshAnchor);
3070
+ const packageRoot = realpathSync(installedPackageRootFromEntry(import.meta.url));
3071
+ const profile = requireNonEmpty(options.profile, "profile");
3072
+ validateProfileName(profile);
3073
+ if (options.expectedScopeId !== void 0) requireNonEmpty(options.expectedScopeId, "expectedScopeId");
3074
+ if (options.expectedInstanceId !== void 0) requireNonEmpty(options.expectedInstanceId, "expectedInstanceId");
3075
+ options.signal?.throwIfAborted();
3076
+ const releaseRealm = reserveNativeClientRealm();
3077
+ let cleanupStarted = false;
3078
+ let cleanupPromise;
3079
+ let context;
3080
+ let diag;
3081
+ let loaderFiber;
3082
+ let installedTransport;
3083
+ let prerequisites;
3084
+ let mountedDomains;
3085
+ let interactions;
3086
+ let gate;
3087
+ let state;
3088
+ const cleanup = (reason) => {
3089
+ if (cleanupStarted) return cleanupPromise ?? Promise.resolve();
3090
+ cleanupStarted = true;
3091
+ cleanupPromise = completeNativeClientRealm(releaseRealm, async () => {
3092
+ const errors = [];
3093
+ if (state !== void 0) {
3094
+ state.closed = true;
3095
+ state.lifetime.abort(/* @__PURE__ */ new Error("native-client: closed"));
3096
+ state.notifyStatus();
3097
+ state.notifyHandles();
3098
+ await Promise.allSettled([...state.operations]);
3099
+ for (const handle of [...state.handles]) try {
3100
+ await handle.close();
3101
+ } catch (error) {
3102
+ errors.push(error);
3103
+ }
3104
+ }
3105
+ for (const release of state?.statusSubscriptions ?? []) try {
3106
+ release();
3107
+ } catch (error) {
3108
+ errors.push(error);
3109
+ }
3110
+ try {
3111
+ interactions?.dispose();
3112
+ } catch (error) {
3113
+ errors.push(error);
3114
+ }
3115
+ try {
3116
+ await installedTransport?.dispose();
3117
+ } catch (error) {
3118
+ errors.push(error);
3119
+ }
3120
+ if (installedTransport !== void 0 && state !== void 0) try {
3121
+ state.terminalStatus = installedTransport.status();
3122
+ } catch (error) {
3123
+ errors.push(error);
3124
+ }
3125
+ try {
3126
+ await prerequisites?.dispose();
3127
+ } catch (error) {
3128
+ errors.push(error);
3129
+ }
3130
+ try {
3131
+ await mountedDomains?.dispose();
3132
+ } catch (error) {
3133
+ errors.push(error);
3134
+ }
3135
+ gate?.cancel(reason);
3136
+ try {
3137
+ await loaderFiber?.dispose();
3138
+ } catch (error) {
3139
+ errors.push(error);
3140
+ }
3141
+ try {
3142
+ await context?.fiber.dispose();
3143
+ } catch (error) {
3144
+ errors.push(error);
3145
+ }
3146
+ diag?.dispose();
3147
+ if (errors.length > 0) {
3148
+ if (state !== void 0) state.closeFailed = true;
3149
+ for (const error of errors) mergeCause(reason, error);
3150
+ reason.cleanupFailed = true;
3151
+ throw reason;
3152
+ }
3153
+ });
3154
+ return cleanupPromise;
3155
+ };
3156
+ try {
3157
+ const hostModules = await loadOfficialClientHost(dshAnchor);
3158
+ options.signal?.throwIfAborted();
3159
+ const dshHome = hostModules.resolveDshHome();
3160
+ const profileDir = hostModules.resolveProfileDir(profile, dshHome);
3161
+ try {
3162
+ hostModules.readProfileManifest("native-client", profileDir);
3163
+ } catch {
3164
+ throw nativeError("NATIVE_CLIENT_PROFILE_NOT_INITIALIZED", "the official profile is not initialized");
3165
+ }
3166
+ const scope = inspectInstalledProfileScope({
3167
+ dshHome,
3168
+ profileDir,
3169
+ packageRoot,
3170
+ dshVersion: readInstalledDshVersion(dshAnchor)
3171
+ });
3172
+ if (options.expectedScopeId !== void 0 && scope.scopeId !== options.expectedScopeId) throw nativeError("NATIVE_CLIENT_SCOPE_MISMATCH", "the resolved profile scope does not match expectedScopeId");
3173
+ const record = readLocalRecord(scope);
3174
+ if (record === void 0) throw nativeError("NATIVE_CLIENT_HOST_UNAVAILABLE", "the target Host is not running");
3175
+ if (inspectHostProcess(record) !== "alive") throw nativeError("NATIVE_CLIENT_HOST_STALE", "the target Host process is not alive");
3176
+ if (options.expectedInstanceId !== void 0 && record.instanceId !== options.expectedInstanceId) throw nativeError("NATIVE_CLIENT_INSTANCE_MISMATCH", "the target Host instance does not match expectedInstanceId");
3177
+ assertClientHostCompatible(record, scope);
3178
+ const host = await authenticateLocalHost(record, scope, options.signal);
3179
+ assertRecordedHostKernelIdentityCurrent(host.identity);
3180
+ options.signal?.throwIfAborted();
3181
+ const loadedProfile = hostModules.loadProfileDirectory("native-client", profileDir, dshAnchor);
3182
+ options.signal?.throwIfAborted();
3183
+ const resolution = await hostModules.createRuntimeResolution({
3184
+ installAnchor: dshAnchor,
3185
+ profile: loadedProfile
3186
+ });
3187
+ options.signal?.throwIfAborted();
3188
+ context = new hostModules.Context();
3189
+ diag = createDiag({ stderrLevel: "off" });
3190
+ const nativeDiag = diag;
3191
+ await context.plugin(hostModules.PluginPackages, { resolution });
3192
+ options.signal?.throwIfAborted();
3193
+ const { mountRemoteClientDomainPrerequisites } = await import("./native-client-domains-Dg4srzYt.mjs");
3194
+ options.signal?.throwIfAborted();
3195
+ loaderFiber = context.plugin(hostModules.Loader, { baseUrl: pathToFileURL(join(profileDir, "package.json")).href });
3196
+ await loaderFiber;
3197
+ options.signal?.throwIfAborted();
3198
+ const loader = context.get("loader");
3199
+ if (loader === void 0) throw new Error("native-client: official Loader did not install");
3200
+ gate = createStartupGate();
3201
+ loader.builtins["pi-tui-interaction-startup-gate"] = gate.plugin;
3202
+ await loader.create({ name: "cordis:pi-tui-interaction-startup-gate" });
3203
+ options.signal?.throwIfAborted();
3204
+ if (!gate.pending) throw new Error("native-client: interaction startup gate failed before transport install");
3205
+ const localTransport = await import("./local-transport-DeWmdZ5E.mjs");
3206
+ options.signal?.throwIfAborted();
3207
+ installedTransport = await localTransport.installLocalTransport(context, {
3208
+ dshAnchor,
3209
+ host,
3210
+ scope,
3211
+ diag,
3212
+ signal: options.signal,
3213
+ onFatal: (error) => {
3214
+ if (state !== void 0) {
3215
+ state.fatalError = error;
3216
+ state.notifyStatus();
3217
+ }
3218
+ }
3219
+ });
3220
+ options.signal?.throwIfAborted();
3221
+ prerequisites = await mountRemoteClientDomainPrerequisites({
3222
+ context,
3223
+ dshAnchor
3224
+ });
3225
+ options.signal?.throwIfAborted();
3226
+ const nativeTransport = installedTransport;
3227
+ const generationSource = {
3228
+ getSnapshot: () => nativeTransport.connection.generation.getSnapshot(),
3229
+ subscribe: (listener) => nativeTransport.connection.generation.subscribe(listener)
3230
+ };
3231
+ const identity = projectIdentity(host.identity);
3232
+ const handles = /* @__PURE__ */ new Set();
3233
+ const handlesBySession = /* @__PURE__ */ new Map();
3234
+ const handleListeners = /* @__PURE__ */ new Set();
3235
+ const statusListeners = /* @__PURE__ */ new Set();
3236
+ const statusSubscriptions = [];
3237
+ const notifyHandles = () => {
3238
+ for (const listener of [...handleListeners]) listener();
3239
+ };
3240
+ const status = () => {
3241
+ if (state?.closed === true) {
3242
+ if (state.closeFailed || state.terminalStatus === void 0) return closedResult();
3243
+ const current = state.terminalStatus;
3244
+ return {
3245
+ kind: "ok",
3246
+ value: {
3247
+ transport: "closed",
3248
+ activeWrappers: current.activeWrappers,
3249
+ liveSockets: current.liveSockets,
3250
+ pendingInteractions: 0,
3251
+ interactionIdentityGaps: interactions?.identityGaps ?? 0,
3252
+ identity
3253
+ }
3254
+ };
3255
+ }
3256
+ if (state?.fatalError !== void 0) return unavailableResult("NATIVE_CLIENT_FATAL", "The authenticated Native Client transport failed.");
3257
+ const current = nativeTransport.status();
3258
+ return {
3259
+ kind: "ok",
3260
+ value: {
3261
+ transport: current.transport,
3262
+ ...current.generationId === void 0 ? {} : { generationId: current.generationId },
3263
+ activeWrappers: current.activeWrappers,
3264
+ liveSockets: current.liveSockets,
3265
+ pendingInteractions: interactions?.pendingCount ?? 0,
3266
+ interactionIdentityGaps: interactions?.identityGaps ?? 0,
3267
+ identity
3268
+ }
3269
+ };
3270
+ };
3271
+ const notifyStatus = () => {
3272
+ const result = status();
3273
+ for (const listener of [...statusListeners]) try {
3274
+ listener(result);
3275
+ } catch (error) {
3276
+ nativeDiag.error("native-client: status listener failed", { error: safeErrorMessage(error) });
3277
+ }
3278
+ };
3279
+ const activeState = {
3280
+ sessions: prerequisites.sessions,
3281
+ remote: prerequisites.remote,
3282
+ jobs: void 0,
3283
+ transport: nativeTransport,
3284
+ uploader: createRemoteFileReceiptUploader(nativeTransport.authenticatedFetch),
3285
+ generation: generationSource,
3286
+ initialGeneration: void 0,
3287
+ identity,
3288
+ diag: nativeDiag,
3289
+ handles,
3290
+ handlesBySession,
3291
+ handleListeners,
3292
+ statusListeners,
3293
+ statusSubscriptions,
3294
+ lifetime: new AbortController(),
3295
+ operations: /* @__PURE__ */ new Set(),
3296
+ closed: false,
3297
+ closeFailed: false,
3298
+ fatalError: void 0,
3299
+ notifyStatus,
3300
+ notifyHandles
3301
+ };
3302
+ state = activeState;
3303
+ interactions = createNativeInteractionReceivers(activeState, options);
3304
+ const agentResolver = context.get("typert")?.contexts?.getClient("agent");
3305
+ if (!gate.pending || agentResolver === void 0) throw new Error("native-client: Session Agent resolver was not ready before interaction gate release");
3306
+ statusSubscriptions.push(nativeTransport.connection.state.subscribe(notifyStatus));
3307
+ statusSubscriptions.push(nativeTransport.connection.generation.subscribe(notifyStatus));
3308
+ gate.release();
3309
+ await localTransport.awaitLocalTransportReady(nativeTransport, { signal: options.signal });
3310
+ mountedDomains = await prerequisites.complete({ signal: options.signal });
3311
+ prerequisites = void 0;
3312
+ activeState.jobs = mountedDomains.jobs;
3313
+ activeState.carrierError = mountedDomains.workspaceStream.carrierError;
3314
+ activeState.initialGeneration = mountedDomains.initialGeneration;
3315
+ options.signal?.throwIfAborted();
3316
+ if (!isInitialGenerationCurrent(activeState)) throw nativeError("NATIVE_GENERATION_STALE", "the first authenticated Connection generation was replaced before the Native Client was published");
3317
+ return {
3318
+ status,
3319
+ subscribeStatus: (listener) => {
3320
+ if (activeState.closed) {
3321
+ try {
3322
+ listener(status());
3323
+ } catch (error) {
3324
+ nativeDiag.error("native-client: status listener failed", { error: safeErrorMessage(error) });
3325
+ }
3326
+ return () => {};
3327
+ }
3328
+ statusListeners.add(listener);
3329
+ try {
3330
+ listener(status());
3331
+ } catch (error) {
3332
+ nativeDiag.error("native-client: status listener failed", { error: safeErrorMessage(error) });
3333
+ }
3334
+ let active = true;
3335
+ return () => {
3336
+ if (!active) return;
3337
+ active = false;
3338
+ statusListeners.delete(listener);
3339
+ };
3340
+ },
3341
+ listSessions: (options) => trackClientOperation(activeState, (async () => {
3342
+ const admission = admitRootRead(activeState, options?.signal);
3343
+ if ("kind" in admission) return admission;
3344
+ try {
3345
+ const outcome = await awaitRootRead(admission, () => activeState.remote.session.list({}, admission.signal));
3346
+ return finalizeRootRead(activeState, admission, rootReadCandidate(outcome, (value) => value.items.map(sessionSummaryOf)));
3347
+ } finally {
3348
+ admission.release();
3349
+ }
3350
+ })()),
3351
+ searchSessions: (query, options) => trackClientOperation(activeState, readRootSessionSearch(activeState, query, options?.signal)),
3352
+ readSessionInfo: (sessionId, options) => trackClientOperation(activeState, readRootSessionInfo(activeState, sessionId, options?.signal)),
3353
+ readSessionState: (sessionId, options) => trackClientOperation(activeState, readRootSessionState(activeState, sessionId, options?.signal)),
3354
+ waitSession: (sessionId, options) => trackClientOperation(activeState, readRootSessionWait(activeState, sessionId, options)),
3355
+ listWorkspaces: () => trackClientOperation(activeState, readNativeWorkspaceBaseline({
3356
+ follow: (signal) => activeState.remote.workspace.follow(signal),
3357
+ generation: activeState.generation,
3358
+ lifetime: activeState.lifetime.signal,
3359
+ isClosed: () => activeState.closed
3360
+ }, (error) => readFailure(error, false))),
3361
+ readSession: (sessionId, options) => trackClientOperation(activeState, readRootHistory(activeState, sessionId, options)),
3362
+ createWorkspace: (path) => trackClientOperation(activeState, (async () => {
3363
+ requireNonEmpty(path, "path");
3364
+ if (!isAbsolute(path)) throw nativeError("NATIVE_CLIENT_INVALID_INPUT", "workspace path must be absolute");
3365
+ if (activeState.closed) return closedResult();
3366
+ if (currentGeneration(activeState) === void 0) return unavailableResult("NATIVE_DISCONNECTED", "No authenticated Host generation is current.");
3367
+ return await settleWrite(() => abortable(activeState.remote.workspace.create({ path }), activeState.lifetime.signal), "committed", (value) => ({
3368
+ workspace: {
3369
+ workspaceId: value.workspace.workspaceId,
3370
+ path: value.workspace.path,
3371
+ title: value.workspace.title
3372
+ },
3373
+ created: value.created
3374
+ }), classifyCreateWriteFailure);
3375
+ })()),
3376
+ createSession: (input) => trackClientOperation(activeState, (async () => {
3377
+ if (activeState.closed) return closedResult();
3378
+ if (input?.workspaceId !== void 0) requireNonEmpty(input.workspaceId, "workspaceId");
3379
+ if (input?.agentPreset !== void 0) requireNonEmpty(input.agentPreset, "agentPreset");
3380
+ const requestedSessionId = input?.sessionId === void 0 ? `session-${randomUUID()}` : requireNonEmpty(input.sessionId, "sessionId");
3381
+ if (currentGeneration(activeState) === void 0) return unavailableResult("NATIVE_DISCONNECTED", "No authenticated Host generation is current.");
3382
+ try {
3383
+ const sessionId = await abortable(activeState.sessions.create({
3384
+ ...input?.workspaceId === void 0 ? {} : { workspaceId: input.workspaceId },
3385
+ sessionId: requestedSessionId,
3386
+ ...input?.agentPreset === void 0 ? {} : { agentPreset: input.agentPreset }
3387
+ }), activeState.lifetime.signal);
3388
+ if (sessionId === "") return unknownResult({
3389
+ code: "NATIVE_INVALID_RESPONSE",
3390
+ message: "The official Session create returned an empty identity."
3391
+ }, { requestedSessionId });
3392
+ return {
3393
+ kind: "committed",
3394
+ value: { sessionId }
3395
+ };
3396
+ } catch (error) {
3397
+ const officialError = sessionCreateRpcErrorOf(error);
3398
+ const published = publishedSessionIdOfCreateError(officialError);
3399
+ if (published !== void 0) return {
3400
+ kind: "published-with-error",
3401
+ sessionId: published,
3402
+ code: "session/workspace-attach-failed",
3403
+ message: "The Session was published but its workspace attachment failed.",
3404
+ requestedSessionId
3405
+ };
3406
+ const code = remoteFailureCode(officialError);
3407
+ if (code !== void 0 && (code === "workspace/not-found" || GATEWAY_PRE_INVOCATION_CODES.has(code))) return rejectedResult({
3408
+ code,
3409
+ message: "The official Session create refused the request."
3410
+ });
3411
+ return unknownResult({
3412
+ code: code ?? "NATIVE_SESSION_CREATE_UNKNOWN",
3413
+ message: "The Session create outcome could not be determined."
3414
+ }, { requestedSessionId });
3415
+ }
3416
+ })()),
3417
+ openSession: (sessionId) => trackClientOperation(activeState, (async () => {
3418
+ requireNonEmpty(sessionId, "sessionId");
3419
+ if (activeState.closed) return closedResult();
3420
+ if (!isInitialGenerationCurrent(activeState)) return staleResult();
3421
+ const captured = currentGeneration(activeState);
3422
+ if (captured === void 0) return unavailableResult("NATIVE_DISCONNECTED", "No authenticated Host generation is current.");
3423
+ const reference = activeState.sessions.retain(sessionId, {
3424
+ source: "controllerOperation",
3425
+ signal: activeState.lifetime.signal
3426
+ });
3427
+ try {
3428
+ await abortable(reference.ready, activeState.lifetime.signal);
3429
+ const binding = reference.binding;
3430
+ const snapshot = binding.session.getSnapshot();
3431
+ if (activeState.closed) {
3432
+ reference.release();
3433
+ return closedResult();
3434
+ }
3435
+ if (!Object.is(captured, currentGeneration(activeState)) || !isInitialGenerationCurrent(activeState)) {
3436
+ reference.release();
3437
+ return staleResult();
3438
+ }
3439
+ if (activeState.sessions.binding(sessionId) !== binding) {
3440
+ reference.release();
3441
+ return {
3442
+ kind: "stale",
3443
+ code: "NATIVE_BINDING_STALE",
3444
+ message: "The owned Session binding is no longer current."
3445
+ };
3446
+ }
3447
+ if (snapshot.openState !== "open") {
3448
+ reference.release();
3449
+ return unavailableResult("NATIVE_SESSION_OPEN_FAILED", "The official Session history open did not complete.");
3450
+ }
3451
+ const historyAddress = snapshot.subagent === null ? ordinaryAddress(sessionId) : knownSubagentAddress(snapshot.subagent.address);
3452
+ const handle = new OwnedNativeSession(activeState, reference, binding, historyAddress);
3453
+ activeState.handles.add(handle);
3454
+ const siblings = activeState.handlesBySession.get(sessionId) ?? /* @__PURE__ */ new Set();
3455
+ siblings.add(handle);
3456
+ activeState.handlesBySession.set(sessionId, siblings);
3457
+ activeState.notifyHandles();
3458
+ if (activeState.closed || handle.isClosed || !Object.is(captured, currentGeneration(activeState)) || !isInitialGenerationCurrent(activeState) || activeState.sessions.binding(sessionId) !== binding) {
3459
+ await handle.close();
3460
+ return activeState.closed ? closedResult() : staleResult();
3461
+ }
3462
+ return {
3463
+ kind: "ok",
3464
+ value: handle
3465
+ };
3466
+ } catch (error) {
3467
+ reference.release();
3468
+ if (activeState.closed) return closedResult();
3469
+ if (!isInitialGenerationCurrent(activeState)) return staleResult();
3470
+ return unknownResult(failureOf(error, "NATIVE_SESSION_OPEN_UNKNOWN", "The Session open outcome could not be determined.", false), { requestedSessionId: sessionId });
3471
+ }
3472
+ })()),
3473
+ readConfiguration: (sessionId, options) => trackClientOperation(activeState, readRootConfiguration(activeState, sessionId, options?.signal)),
3474
+ readSessionPolicy: (sessionId, options) => trackClientOperation(activeState, readRootSessionPolicy(activeState, sessionId, options?.signal)),
3475
+ modelCatalog: () => trackClientOperation(activeState, (async () => {
3476
+ if (activeState.closed) return closedResult();
3477
+ const captured = currentGeneration(activeState);
3478
+ if (captured === void 0) return unavailableResult("NATIVE_DISCONNECTED", "No authenticated Host generation is current.");
3479
+ const result = await settleRead(() => abortable(activeState.remote.session.modelCatalog(), activeState.lifetime.signal), captured, activeState.generation, modelCatalogOf);
3480
+ if (activeState.closed) return closedResult();
3481
+ if (!Object.is(captured, currentGeneration(activeState))) return staleResult();
3482
+ return result;
3483
+ })()),
3484
+ listPresets: () => trackClientOperation(activeState, (async () => {
3485
+ if (activeState.closed) return closedResult();
3486
+ const captured = currentGeneration(activeState);
3487
+ if (captured === void 0) return unavailableResult("NATIVE_DISCONNECTED", "No authenticated Host generation is current.");
3488
+ const result = await settleRead(() => abortable(activeState.remote.agentPresets.list(), activeState.lifetime.signal), captured, activeState.generation, presetRosterOf);
3489
+ if (activeState.closed) return closedResult();
3490
+ if (!Object.is(captured, currentGeneration(activeState))) return staleResult();
3491
+ return result;
3492
+ })()),
3493
+ permissionCatalog: () => trackClientOperation(activeState, (async () => {
3494
+ if (activeState.closed) return closedResult();
3495
+ const captured = currentGeneration(activeState);
3496
+ if (captured === void 0) return unavailableResult("NATIVE_DISCONNECTED", "No authenticated Host generation is current.");
3497
+ const result = await settleRead(() => abortable(activeState.remote.permissionPresets.catalog(), activeState.lifetime.signal), captured, activeState.generation, permissionCatalogOf);
3498
+ if (activeState.closed) return closedResult();
3499
+ if (!Object.is(captured, currentGeneration(activeState))) return staleResult();
3500
+ return result;
3501
+ })()),
3502
+ close: () => {
3503
+ if (activeState.closePromise !== void 0) return activeState.closePromise;
3504
+ let settle;
3505
+ let fail;
3506
+ activeState.closePromise = new Promise((resolve, reject) => {
3507
+ settle = resolve;
3508
+ fail = reject;
3509
+ });
3510
+ activeState.closed = true;
3511
+ runOwned("native-client: Client close", async () => {
3512
+ await cleanup(/* @__PURE__ */ new Error("native-client: closed"));
3513
+ }, {
3514
+ diag: activeState.diag,
3515
+ onResult: () => settle(),
3516
+ onError: (error) => fail(error)
3517
+ });
3518
+ activeState.notifyStatus();
3519
+ return activeState.closePromise;
3520
+ }
3521
+ };
3522
+ } catch (error) {
3523
+ const failure = error instanceof Error ? error : new Error(String(error));
3524
+ try {
3525
+ await cleanup(failure);
3526
+ } catch (cleanupError) {
3527
+ if (!cleanupStarted) releaseRealm();
3528
+ throw cleanupError;
3529
+ }
3530
+ throw error;
3531
+ }
3532
+ }
3533
+ //#endregion
3534
+ export { NATIVE_CLIENT_API_VERSION, attachNativeClient };