@xmoon76/dsh-pi-tui 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.en.md +64 -26
  2. package/README.md +64 -26
  3. package/cordis.patch.yml +13 -0
  4. package/dist/acp-stdio.mjs +151 -0
  5. package/dist/{bootstrap-C9nl6e13.mjs → bootstrap-CVyHGQDX.mjs} +22330 -6888
  6. package/dist/browser-CDUSHIIr.mjs +76 -0
  7. package/dist/builtins.mjs +2 -2
  8. package/dist/{client-bootstrap-CGezi85O.mjs → client-bootstrap-4UoeVIHE.mjs} +2407 -1830
  9. package/dist/client-runtime-BHBlVUf5.mjs +1376 -0
  10. package/dist/{daemon-launcher-H_1r5Cqs.mjs → daemon-launcher-DxIgjBHW.mjs} +1551 -57
  11. package/dist/daemon-launcher.d.mts +85 -14
  12. package/dist/daemon-launcher.mjs +2 -2
  13. package/dist/diagnostics-Db5iVcuJ.mjs +123 -0
  14. package/dist/{entry-control-jBfKn1qO.mjs → entry-control-BDLZgg4m.mjs} +1 -1
  15. package/dist/{extensions-6a5vvJUT.mjs → extensions-Dx7ncPNA.mjs} +1 -4
  16. package/dist/extensions.mjs +1 -1
  17. package/dist/handoff-BjoEy3f8.mjs +106 -0
  18. package/dist/history-search-limits-Cx2UvRC2.mjs +16 -0
  19. package/dist/history-search-remote-BHuoellG.mjs +113 -0
  20. package/dist/history-search-remote-BzXdvrxk.mjs +26 -0
  21. package/dist/history-search-seat-BcHJTpeB.mjs +639 -0
  22. package/dist/history-search-seat-rZcq0XV6.mjs +639 -0
  23. package/dist/{host-bootstrap-MVxks641.mjs → host-bootstrap-BfnufpnW.mjs} +37 -72
  24. package/dist/{host-foundation-probe-DK7n5jDu.mjs → host-foundation-probe-DlD8-N_Q.mjs} +2 -2
  25. package/dist/host-runtime.mjs +5611 -290
  26. package/dist/index.d.mts +13 -6
  27. package/dist/index.mjs +22766 -6893
  28. package/dist/installed-dsh-BjUiJSwR.mjs +142 -0
  29. package/dist/interaction-port-D1Yv9zgu.mjs +45 -0
  30. package/dist/local-acp-control-CC5z4Xbq.mjs +304 -0
  31. package/dist/local-acp-endpoint-D1jYdJdv.mjs +41 -0
  32. package/dist/local-acp-listener-Cmgb5M0H.mjs +9493 -0
  33. package/dist/local-acp-status-B_25Q6kU.mjs +101 -0
  34. package/dist/local-client.mjs +719 -93
  35. package/dist/local-daemon-control-BFJAC8Kg.mjs +2199 -0
  36. package/dist/local-daemon-control-Bm3imctD.mjs +2101 -0
  37. package/dist/{local-discovery-BPZw1wEd.mjs → local-discovery-BMhaGIiJ.mjs} +254 -544
  38. package/dist/{local-discovery-BMoNXZjJ.mjs → local-discovery-Ba7_-NNC.mjs} +1 -1
  39. package/dist/{local-discovery-Bq3jLAn1.mjs → local-discovery-QSbFpjK2.mjs} +301 -544
  40. package/dist/local-host.mjs +970 -501
  41. package/dist/local-profile-daemon-admin-otpm69R6.mjs +469 -0
  42. package/dist/{local-scope-DEuGAy8l.mjs → local-scope-5DEKA_lW.mjs} +1075 -31
  43. package/dist/{local-transport-X4ZCe2uE.mjs → local-transport-DeWmdZ5E.mjs} +14 -3
  44. package/dist/{local-web-control-DKWtXIkr.mjs → local-web-control-Dny93N-r.mjs} +10 -7
  45. package/dist/{local-workspace-object-D06GL0UO.mjs → local-workspace-object-D0RVQt8U.mjs} +33 -9
  46. package/dist/model-selection-CYlqg2DV.mjs +83 -0
  47. package/dist/native-client-domains-Dg4srzYt.mjs +2 -0
  48. package/dist/native-client.d.mts +735 -0
  49. package/dist/native-client.mjs +3534 -0
  50. package/dist/{open-CmOBxSjN.mjs → open-QQva8-ar.mjs} +24 -20
  51. package/dist/{pi-tui-remote-contribution-Do8ECrUy.mjs → pi-tui-remote-contribution-565wiLWp.mjs} +741 -150
  52. package/dist/preferences.mjs +1 -1
  53. package/dist/{profile-preferences-migration-CThz4rHH.mjs → profile-preferences-migration-CNOWIdnr.mjs} +1 -1
  54. package/dist/{profile-preferences-migration-BfUGdPZx.mjs → profile-preferences-migration-IrnXcJWK.mjs} +10 -8
  55. package/dist/{prompt-sections-DXmjB58H.mjs → prompt-sections-Bi-9_Gr_.mjs} +28 -10
  56. package/dist/{prompt-sections-DUKmWb8g.mjs → prompt-sections-DFS1dqsY.mjs} +342 -56
  57. package/dist/{dist-BFgC-5tL.mjs → recall-scope-9Nuoto_i.mjs} +353 -1
  58. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  59. package/dist/schema-CCLvDa7Q.mjs +177 -0
  60. package/dist/{schema-qE_P09zJ.mjs → schema-t97l3aK8.mjs} +56 -3
  61. package/dist/{session-DC0XQr5O.mjs → session-Cs8iLCEx.mjs} +784 -342
  62. package/dist/{session-Cihe8PPS.mjs → session-EBRZF6Ow.mjs} +783 -341
  63. package/dist/session-create-facts-CkfG5DpQ.mjs +20 -0
  64. package/dist/{startup-CarQxWwi.d.mts → startup-Dti3Udne.d.mts} +30 -3
  65. package/dist/{startup-CARqn3kV.mjs → startup-UtFQSDe_.mjs} +90 -15
  66. package/dist/startup.d.mts +2 -2
  67. package/dist/startup.mjs +1 -1
  68. package/dist/task-read-remote-DRtkXDrZ.mjs +1083 -0
  69. package/dist/{terminal-progress-source-D4DHyXDo.mjs → terminal-progress-source-VsczdXA-.mjs} +610 -335
  70. package/dist/{transcript-view-a7cROAaI.mjs → transcript-view-B6vCnukn.mjs} +2284 -1166
  71. package/dist/{transcript-view-hvNVkPtv.mjs → transcript-view-DSSdE2vK.mjs} +2191 -765
  72. package/dist/write-failure-xNKczXH7.mjs +189 -0
  73. package/package.json +25 -8
  74. package/dist/local-acp-listener-CNkguN5-.mjs +0 -2566
  75. package/dist/local-daemon-control-Bg9s2aYi.mjs +0 -1424
  76. package/dist/local-daemon-control-Cu_4FIdd.mjs +0 -1585
  77. package/dist/local-profile-daemon-admin-AXgVH-6y.mjs +0 -91
  78. package/dist/preset-BcWqOtY7.mjs +0 -46
@@ -1,13 +1,758 @@
1
1
  import { n as runSyncDisposalStepsWithPrimary } from "./disposal-BYBbEpVY.mjs";
2
+ import { i as installedDshAnchor, s as resolveDshKoffi } from "./installed-dsh-BjUiJSwR.mjs";
2
3
  import { createRequire } from "node:module";
3
- import { closeSync, constants, existsSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, statSync, writeSync } from "node:fs";
4
+ import { accessSync, closeSync, constants, existsSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, statSync, writeSync } from "node:fs";
4
5
  import { constants as constants$1, userInfo } from "node:os";
5
6
  import { dirname, isAbsolute, join, relative, sep } from "node:path";
6
7
  import { createHash } from "node:crypto";
7
8
  import { spawn } from "node:child_process";
8
9
  import { fileURLToPath, pathToFileURL } from "node:url";
9
- import { createServer } from "node:net";
10
10
  import { Buffer as Buffer$1 } from "node:buffer";
11
+ import { createServer } from "node:net";
12
+ /** Strip the `session-`/`session_` prefix and keep the first 8 characters, like
13
+ * the kimicode card's short id. */
14
+ function shortSessionId(id) {
15
+ return id.replace(/^session[-_]/i, "").slice(0, 8);
16
+ }
17
+ /** A canonical full Session id: the `session-`/`session_` prefix plus 32 hex
18
+ * characters, optionally written as a hyphenated canonical UUID. A BARE UUID
19
+ * is NOT a canonical Session id — it must match an official listed row. */
20
+ const CANONICAL_SESSION_ID = /^session[-_](?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
21
+ /** The CLI automatic-prefix rule: at least four ASCII hex digits after the
22
+ * optional `session-`/`session_` prefix. Deliberately stricter than the
23
+ * `/resume` matcher; the CLI must not auto-resume a word-like query. */
24
+ const CLI_PREFIX = /^[0-9a-f]{4,}$/i;
25
+ /** Whether `query` is a canonical full Session id that may be opened WITHOUT
26
+ * a roster read (the explicit full-id launch contract). */
27
+ function canonicalFullSessionId(query) {
28
+ return CANONICAL_SESSION_ID.test(query);
29
+ }
30
+ /** The legal automatic prefix `query` carries, or undefined. The returned
31
+ * value is the bare hex prefix (the leading Session prefix stripped). */
32
+ function cliAutoPrefix(query) {
33
+ const bare = query.replace(/^session[-_]/i, "");
34
+ return CLI_PREFIX.test(bare) ? bare : void 0;
35
+ }
36
+ /**
37
+ * Resolve one session row for a typed resume query. A full id wins over the
38
+ * row order; otherwise only a UNIQUE non-empty prefix (the `session-` form or
39
+ * the short id) is resolved. An ambiguous or missing prefix returns undefined
40
+ * so the read owner seeds the same global Browser search instead of guessing.
41
+ * @param rows - the listed main-session rows (never re-filtered here).
42
+ * @param query - the resume query.
43
+ * @returns the matching row, or undefined.
44
+ */
45
+ function findSessionMatch(rows, query) {
46
+ const exact = rows.find((row) => row.id === query);
47
+ if (exact !== void 0) return exact;
48
+ const bare = query.replace(/^session[-_]/i, "");
49
+ if (bare === "") return void 0;
50
+ let candidate;
51
+ for (const row of rows) {
52
+ if (!row.id.replace(/^session[-_]/i, "").startsWith(bare) && !shortSessionId(row.id).startsWith(bare)) continue;
53
+ if (candidate !== void 0) return void 0;
54
+ candidate = row;
55
+ }
56
+ return candidate;
57
+ }
58
+ /**
59
+ * Resolve one CLI `--session` value before the Browser mounts: an exact
60
+ * official row id first (including historical non-standard ids), then — only
61
+ * for a legal CLI automatic prefix — the SAME unique-prefix primitive
62
+ * `/resume` uses. An ambiguous, missing or word-like query returns undefined
63
+ * so the startup Browser keeps it as one global search instead of guessing.
64
+ * A subagent child is never an automatic main-Session selection.
65
+ */
66
+ function chooseListedSession(rows, query) {
67
+ if (query === "" || /^session[-_]$/i.test(query)) return void 0;
68
+ const exact = rows.find((row) => row.id === query);
69
+ if (exact !== void 0) return exact;
70
+ if (cliAutoPrefix(query) === void 0) return void 0;
71
+ return findSessionMatch(rows.filter((row) => row.origin !== "subagent"), query);
72
+ }
73
+ /** Canonicalize one user query for both metadata matching and Host search. */
74
+ function sanitizeSessionSearchInput(value) {
75
+ const trimmed = value.replace(/\0/g, "").trim();
76
+ if (trimmed.length <= 500) return trimmed;
77
+ const truncated = trimmed.slice(0, 500);
78
+ const last = truncated.charCodeAt(499);
79
+ return last >= 55296 && last <= 56319 ? truncated.slice(0, 499) : truncated;
80
+ }
81
+ /** Metadata-only membership; content membership belongs to SessionReader.search(). */
82
+ function sessionRowMatchesQuery(row, query) {
83
+ const needle = query.toLowerCase();
84
+ return row.id.toLowerCase().includes(needle) || (row.title ?? "").toLowerCase().includes(needle) || (row.cwd ?? "").toLowerCase().includes(needle) || (row.preset ?? "").toLowerCase().includes(needle) || (row.workspace?.title ?? "").toLowerCase().includes(needle) || (row.workspace?.path ?? "").toLowerCase().includes(needle);
85
+ }
86
+ //#endregion
87
+ //#region src/runtime/native-process/win32.ts
88
+ /**
89
+ * Win32 native process identity, kernel seats, per-instance stop events and
90
+ * private object-security primitives.
91
+ *
92
+ * This module is the ONLY owner of the Win32 FFI layout for these operations.
93
+ * It lazily loads Koffi from the running DSH installation (the verified anchor
94
+ * -> `@deepseek-ai/dsh-subprocess-local` -> that package's own declared
95
+ * `koffi`), decodes exact kernel facts and never decides product policy.
96
+ *
97
+ * The module is imported on every platform (it is part of the native-process
98
+ * layer), but no DLL is loaded until a Win32 function is actually called.
99
+ *
100
+ * @module runtime/native-process/win32
101
+ */
102
+ const ERROR_INVALID_PARAMETER = 87;
103
+ const ERROR_ACCESS_DENIED = 5;
104
+ const ERROR_INVALID_HANDLE = 6;
105
+ const ERROR_ALREADY_EXISTS = 183;
106
+ const WAIT_OBJECT_0 = 0;
107
+ const WAIT_ABANDONED = 128;
108
+ const WAIT_TIMEOUT = 258;
109
+ const WAIT_FAILED = 4294967295;
110
+ const TOKEN_QUERY = 8;
111
+ const LOCAL_SYSTEM_SID = "S-1-5-18";
112
+ const BUILTIN_ADMINISTRATORS_SID = "S-1-5-32-544";
113
+ const ACCESS_ALLOWED_ACE_TYPE = 0;
114
+ const ACCESS_DENIED_ACE_TYPE = 1;
115
+ const FILE_ATTRIBUTE_DIRECTORY = 16;
116
+ const FILE_ATTRIBUTE_REPARSE_POINT = 1024;
117
+ const FILE_SHARE_ALL = 7;
118
+ const OPEN_EXISTING = 3;
119
+ const DRIVE_FIXED = 3;
120
+ const SE_FILE_OBJECT = 1;
121
+ const SE_KERNEL_OBJECT = 6;
122
+ const OBJECT_INHERIT_ACE = 1;
123
+ const CONTAINER_INHERIT_ACE = 2;
124
+ const SE_DACL_PRESENT = 4;
125
+ const SDDL_REVISION_1 = 1;
126
+ let loaded$1;
127
+ function bind(context, library, name, result, args) {
128
+ return library.func("__stdcall", name, result, [...args]);
129
+ }
130
+ function loadBridge$1() {
131
+ if (loaded$1 !== void 0) return loaded$1;
132
+ let result;
133
+ try {
134
+ const anchor = installedDshAnchor();
135
+ if (anchor === void 0) throw new Error("native win32: no installed DSH anchor");
136
+ const koffi = createRequire(import.meta.url)(resolveDshKoffi(anchor));
137
+ const kernel32 = koffi.load("kernel32.dll");
138
+ const advapi32 = koffi.load("advapi32.dll");
139
+ const context = {
140
+ koffi,
141
+ kernel32,
142
+ advapi32
143
+ };
144
+ result = {
145
+ ok: true,
146
+ bridge: {
147
+ koffi,
148
+ closeHandle: bind(context, kernel32, "CloseHandle", "int", ["void *"]),
149
+ getLastError: bind(context, kernel32, "GetLastError", "uint32", []),
150
+ setLastError: bind(context, kernel32, "SetLastError", "void", ["uint32"]),
151
+ openProcess: bind(context, kernel32, "OpenProcess", "void *", [
152
+ "uint32",
153
+ "bool",
154
+ "uint32"
155
+ ]),
156
+ getProcessTimes: bind(context, kernel32, "GetProcessTimes", "int", [
157
+ "void *",
158
+ "void *",
159
+ "void *",
160
+ "void *",
161
+ "void *"
162
+ ]),
163
+ waitForSingleObject: bind(context, kernel32, "WaitForSingleObject", "uint32", ["void *", "uint32"]),
164
+ waitForMultipleObjects: bind(context, kernel32, "WaitForMultipleObjects", "uint32", [
165
+ "uint32",
166
+ "uintptr_t *",
167
+ "int",
168
+ "uint32"
169
+ ]),
170
+ openProcessToken: bind(context, kernel32, "OpenProcessToken", "int", [
171
+ "void *",
172
+ "uint32",
173
+ "void *"
174
+ ]),
175
+ getTokenInformation: bind(context, advapi32, "GetTokenInformation", "int", [
176
+ "void *",
177
+ "uint32",
178
+ "void *",
179
+ "uint32",
180
+ "void *"
181
+ ]),
182
+ createMutexW: bind(context, kernel32, "CreateMutexW", "void *", [
183
+ "void *",
184
+ "int",
185
+ "const char16_t *"
186
+ ]),
187
+ releaseMutex: bind(context, kernel32, "ReleaseMutex", "int", ["void *"]),
188
+ createEventW: bind(context, kernel32, "CreateEventW", "void *", [
189
+ "void *",
190
+ "int",
191
+ "int",
192
+ "const char16_t *"
193
+ ]),
194
+ openEventW: bind(context, kernel32, "OpenEventW", "void *", [
195
+ "uint32",
196
+ "int",
197
+ "const char16_t *"
198
+ ]),
199
+ setEvent: bind(context, kernel32, "SetEvent", "int", ["void *"]),
200
+ createNamedPipeW: bind(context, kernel32, "CreateNamedPipeW", "void *", [
201
+ "const char16_t *",
202
+ "uint32",
203
+ "uint32",
204
+ "uint32",
205
+ "uint32",
206
+ "uint32",
207
+ "uint32",
208
+ "void *"
209
+ ]),
210
+ createDirectoryW: bind(context, kernel32, "CreateDirectoryW", "int", ["const char16_t *", "void *"]),
211
+ createFileW: bind(context, kernel32, "CreateFileW", "void *", [
212
+ "const char16_t *",
213
+ "uint32",
214
+ "uint32",
215
+ "void *",
216
+ "uint32",
217
+ "uint32",
218
+ "void *"
219
+ ]),
220
+ getFileAttributesW: bind(context, kernel32, "GetFileAttributesW", "uint32", ["const char16_t *"]),
221
+ getDriveTypeW: bind(context, kernel32, "GetDriveTypeW", "uint32", ["const char16_t *"]),
222
+ getVolumeInformationW: bind(context, kernel32, "GetVolumeInformationW", "int", [
223
+ "const char16_t *",
224
+ "void *",
225
+ "uint32",
226
+ "void *",
227
+ "void *",
228
+ "void *",
229
+ "void *",
230
+ "uint32"
231
+ ]),
232
+ getSystemDirectoryW: bind(context, kernel32, "GetSystemDirectoryW", "uint32", ["void *", "uint32"]),
233
+ convertStringSecurityDescriptor: bind(context, advapi32, "ConvertStringSecurityDescriptorToSecurityDescriptorW", "int", [
234
+ "const char16_t *",
235
+ "uint32",
236
+ "void *",
237
+ "void *"
238
+ ]),
239
+ getSecurityDescriptorDacl: bind(context, advapi32, "GetSecurityDescriptorDacl", "int", [
240
+ "void *",
241
+ "void *",
242
+ "void *",
243
+ "void *"
244
+ ]),
245
+ setSecurityInfo: bind(context, advapi32, "SetSecurityInfo", "uint32", [
246
+ "void *",
247
+ "int",
248
+ "uint32",
249
+ "void *",
250
+ "void *",
251
+ "void *",
252
+ "void *"
253
+ ]),
254
+ getSecurityInfo: bind(context, advapi32, "GetSecurityInfo", "uint32", [
255
+ "void *",
256
+ "int",
257
+ "uint32",
258
+ "void *",
259
+ "void *",
260
+ "void *",
261
+ "void *",
262
+ "void *"
263
+ ]),
264
+ getSecurityDescriptorLength: bind(context, advapi32, "GetSecurityDescriptorLength", "uint32", ["void *"]),
265
+ getSecurityDescriptorControl: bind(context, advapi32, "GetSecurityDescriptorControl", "int", [
266
+ "void *",
267
+ "void *",
268
+ "void *"
269
+ ]),
270
+ localFree: bind(context, kernel32, "LocalFree", "void *", ["void *"])
271
+ }
272
+ };
273
+ } catch {
274
+ result = {
275
+ ok: false,
276
+ code: "NATIVE_UNAVAILABLE"
277
+ };
278
+ }
279
+ loaded$1 = result;
280
+ return result;
281
+ }
282
+ /** `GetLastError()` from the live bridge, or 0 when the native addon is unavailable. */
283
+ function lastError(bridge) {
284
+ return bridge.getLastError();
285
+ }
286
+ /** A wide (UTF-16RO) Koffi string is passed through the `const char16_t *` type. */
287
+ function parseSid(bytes, offset) {
288
+ const revision = bytes[offset];
289
+ const count = bytes[offset + 1];
290
+ let authority = 0n;
291
+ for (let i = 0; i < 6; i += 1) authority = authority << 8n | BigInt(bytes[offset + 2 + i]);
292
+ let value = `S-${revision}-${authority}`;
293
+ for (let i = 0; i < count; i += 1) value += `-${bytes.readUInt32LE(offset + 8 + i * 4)}`;
294
+ return value;
295
+ }
296
+ function filetimeFrom(buffer, offset) {
297
+ const low = buffer.readUInt32LE(offset);
298
+ const high = buffer.readUInt32LE(offset + 4);
299
+ return (BigInt(high) << 32n | BigInt(low)).toString(10);
300
+ }
301
+ /** The real Windows system directory reported by kernel32, never an environment value. */
302
+ function win32SystemDirectory() {
303
+ const load = loadBridge$1();
304
+ if (!load.ok) return void 0;
305
+ const buffer = Buffer.alloc(65536);
306
+ const length = load.bridge.getSystemDirectoryW(buffer, Math.floor(buffer.length / 2));
307
+ if (length === 0 || length >= Math.floor(buffer.length / 2)) return void 0;
308
+ const value = buffer.toString("utf16le", 0, length * 2).replace(/\0.*$/u, "");
309
+ return value === "" ? void 0 : value;
310
+ }
311
+ /** The SID of the token's real user (TokenUser), never a username or environment value. */
312
+ function win32CurrentTokenSid() {
313
+ const load = loadBridge$1();
314
+ if (!load.ok) return void 0;
315
+ const bridge = load.bridge;
316
+ const processHandle = bridge.openProcess(1052672, false, process.pid);
317
+ if (processHandle === null || processHandle === void 0) return void 0;
318
+ const token = Buffer.alloc(8);
319
+ if (!bridge.openProcessToken(processHandle, TOKEN_QUERY, token)) {
320
+ bridge.closeHandle(processHandle);
321
+ return;
322
+ }
323
+ const tokenHandle = token.readBigUInt64LE(0);
324
+ try {
325
+ const needed = Buffer.alloc(4);
326
+ bridge.getTokenInformation(tokenHandle, 1, Buffer.alloc(0), 0, needed);
327
+ const length = needed.readUInt32LE(0);
328
+ if (length === 0) return void 0;
329
+ const info = Buffer.alloc(length);
330
+ if (!bridge.getTokenInformation(tokenHandle, 1, info, length, needed)) return void 0;
331
+ const sidAddress = info.readBigUInt64LE(0);
332
+ return parseSid(info, Number(sidAddress - bridge.koffi.address(info)));
333
+ } finally {
334
+ bridge.closeHandle(tokenHandle);
335
+ bridge.closeHandle(processHandle);
336
+ }
337
+ }
338
+ /** Read the current kernel identity of one pid through Win32. */
339
+ function readWin32KernelProcessObservation(pid) {
340
+ if (process.platform !== "win32") return {
341
+ kind: "unknown",
342
+ code: "NATIVE_UNAVAILABLE"
343
+ };
344
+ const opened = openWin32Process(pid);
345
+ if (opened.kind !== "ok") return opened;
346
+ try {
347
+ return {
348
+ kind: "alive",
349
+ identity: opened.capture.identity
350
+ };
351
+ } finally {
352
+ closeWin32Handle(opened.capture.handle);
353
+ }
354
+ }
355
+ /** Open a process handle and return its exact identity after one live observation. */
356
+ function openWin32Process(pid) {
357
+ const load = loadBridge$1();
358
+ if (!load.ok) return {
359
+ kind: "unknown",
360
+ code: load.code
361
+ };
362
+ const bridge = load.bridge;
363
+ const handle = bridge.openProcess(1052672, false, pid);
364
+ if (!handle) {
365
+ const code = lastError(bridge);
366
+ if (code === ERROR_INVALID_PARAMETER) return { kind: "gone" };
367
+ if (code === ERROR_ACCESS_DENIED) return {
368
+ kind: "unknown",
369
+ code: "ACCESS_DENIED"
370
+ };
371
+ return {
372
+ kind: "unknown",
373
+ code: "READ_FAILED"
374
+ };
375
+ }
376
+ const fail = (code) => {
377
+ bridge.closeHandle(handle);
378
+ return {
379
+ kind: "unknown",
380
+ code
381
+ };
382
+ };
383
+ try {
384
+ const times = Buffer.alloc(32);
385
+ if (!bridge.getProcessTimes(handle, times, Buffer.alloc(32), Buffer.alloc(32), Buffer.alloc(32))) return fail(lastError(bridge) === ERROR_ACCESS_DENIED ? "ACCESS_DENIED" : "READ_FAILED");
386
+ const token = Buffer.alloc(8);
387
+ if (!bridge.openProcessToken(handle, TOKEN_QUERY, token)) return fail(lastError(bridge) === ERROR_ACCESS_DENIED ? "ACCESS_DENIED" : "READ_FAILED");
388
+ const tokenHandle = token.readBigUInt64LE(0);
389
+ let sid;
390
+ try {
391
+ const needed = Buffer.alloc(4);
392
+ bridge.getTokenInformation(tokenHandle, 1, Buffer.alloc(0), 0, needed);
393
+ const length = needed.readUInt32LE(0);
394
+ if (length === 0) return fail("READ_FAILED");
395
+ const info = Buffer.alloc(length);
396
+ if (!bridge.getTokenInformation(tokenHandle, 1, info, length, needed)) return fail("READ_FAILED");
397
+ const sidAddress = info.readBigUInt64LE(0);
398
+ sid = parseSid(info, Number(sidAddress - bridge.koffi.address(info)));
399
+ } finally {
400
+ bridge.closeHandle(tokenHandle);
401
+ }
402
+ if (sid === void 0) return fail("READ_FAILED");
403
+ const wait = bridge.waitForSingleObject(handle, 0);
404
+ if (wait === WAIT_OBJECT_0) {
405
+ bridge.closeHandle(handle);
406
+ return { kind: "gone" };
407
+ }
408
+ if (wait !== WAIT_TIMEOUT) return fail("READ_FAILED");
409
+ return {
410
+ kind: "ok",
411
+ capture: {
412
+ handle,
413
+ identity: {
414
+ platform: "win32",
415
+ pid,
416
+ ownerSid: sid,
417
+ creationFiletime: filetimeFrom(times, 0)
418
+ }
419
+ }
420
+ };
421
+ } catch {
422
+ bridge.closeHandle(handle);
423
+ return {
424
+ kind: "unknown",
425
+ code: "READ_FAILED"
426
+ };
427
+ }
428
+ }
429
+ /** Close one Win32 handle; callers track ownership exactly once. */
430
+ function closeWin32Handle(handle) {
431
+ const load = loadBridge$1();
432
+ if (!load.ok) return;
433
+ load.bridge.closeHandle(handle);
434
+ }
435
+ /** Wait for one held process handle to become terminal within a bound. */
436
+ async function waitWin32Handle(handle, timeoutMs) {
437
+ const load = loadBridge$1();
438
+ if (!load.ok) return {
439
+ kind: "failed",
440
+ code: WAIT_FAILED
441
+ };
442
+ return await new Promise((resolve) => {
443
+ load.bridge.waitForSingleObject.async(handle, timeoutMs, (error, code) => {
444
+ if (error !== null) resolve({
445
+ kind: "failed",
446
+ code: WAIT_FAILED
447
+ });
448
+ else if (code === WAIT_OBJECT_0) resolve({
449
+ kind: "terminal",
450
+ code
451
+ });
452
+ else if (code === WAIT_TIMEOUT) resolve({
453
+ kind: "timeout",
454
+ code
455
+ });
456
+ else resolve({
457
+ kind: "failed",
458
+ code
459
+ });
460
+ });
461
+ });
462
+ }
463
+ /** Read the security descriptor of one open kernel/file handle. */
464
+ function readSecurityInfo(handle, objectType) {
465
+ const load = loadBridge$1();
466
+ if (!load.ok) return void 0;
467
+ const bridge = load.bridge;
468
+ const owner = Buffer.alloc(8);
469
+ const group = Buffer.alloc(8);
470
+ const dacl = Buffer.alloc(8);
471
+ const sacl = Buffer.alloc(8);
472
+ const sd = Buffer.alloc(8);
473
+ if (bridge.getSecurityInfo(handle, objectType, 5, owner, group, dacl, sacl, sd) !== 0) return void 0;
474
+ if (sd.readBigUInt64LE(0) === 0n) return void 0;
475
+ const sdPtr = sd.readBigUInt64LE(0);
476
+ try {
477
+ const length = bridge.getSecurityDescriptorLength(sdPtr);
478
+ if (length === 0) return void 0;
479
+ const bytes = Buffer.from(bridge.koffi.decode(sdPtr, "uint8", length));
480
+ const control = Buffer.alloc(2);
481
+ const revision = Buffer.alloc(4);
482
+ if (!bridge.getSecurityDescriptorControl(sdPtr, control, revision)) return void 0;
483
+ const flags = control.readUInt16LE(0);
484
+ const ownerOffset = bytes.readUInt32LE(4);
485
+ const daclOffset = bytes.readUInt32LE(16);
486
+ const aces = [];
487
+ if (daclOffset !== 0) {
488
+ const aceCount = bytes.readUInt16LE(daclOffset + 4);
489
+ let offset = daclOffset + 8;
490
+ for (let i = 0; i < aceCount; i += 1) {
491
+ const type = bytes[offset];
492
+ const aceFlags = bytes[offset + 1];
493
+ const size = bytes.readUInt16LE(offset + 2);
494
+ const mask = bytes.readUInt32LE(offset + 4);
495
+ aces.push({
496
+ sid: parseSid(bytes, offset + 8),
497
+ mask,
498
+ type,
499
+ flags: aceFlags
500
+ });
501
+ offset += size;
502
+ }
503
+ }
504
+ return {
505
+ ownerSid: ownerOffset === 0 ? null : parseSid(bytes, ownerOffset),
506
+ daclPresent: (flags & SE_DACL_PRESENT) !== 0,
507
+ daclNull: daclOffset === 0,
508
+ aces
509
+ };
510
+ } finally {
511
+ bridge.localFree(sdPtr);
512
+ }
513
+ }
514
+ /** Turn one SDDL into a SECURITY_ATTRIBUTES buffer for a new kernel object. */
515
+ function securityAttributesForSddl(bridge, sddl) {
516
+ const sd = Buffer.alloc(8);
517
+ const size = Buffer.alloc(4);
518
+ if (!bridge.convertStringSecurityDescriptor(sddl, SDDL_REVISION_1, sd, size)) throw new Error(`native win32: invalid security descriptor (${String(lastError(bridge))})`);
519
+ const sdPtr = sd.readBigUInt64LE(0);
520
+ const attributes = Buffer.alloc(24);
521
+ attributes.writeUInt32LE(24, 0);
522
+ attributes.writeBigUInt64LE(sd.readBigUInt64LE(0), 8);
523
+ attributes.writeUInt32LE(0, 16);
524
+ return {
525
+ attributes,
526
+ sd: sdPtr
527
+ };
528
+ }
529
+ /**
530
+ * The ACL contract for an EXISTING private product object: owned by the current
531
+ * SID, with a present non-null DACL that grants only to the current SID or to
532
+ * LocalSystem / BUILTIN Administrators (outside the ordinary-account threat
533
+ * model). Deny ACEs never widen access. ACE count, order, protected bit and
534
+ * explicit-vs-inherited representation are ordinary ACL representations, not a
535
+ * security boundary. An ACE type this reader cannot interpret is not proof of
536
+ * safety, so it fails closed.
537
+ */
538
+ function isOwnerPrivateAcl(view, sid) {
539
+ if (view === void 0 || !view.daclPresent || view.daclNull || view.ownerSid !== sid) return false;
540
+ for (const ace of view.aces) {
541
+ if (ace.type === ACCESS_DENIED_ACE_TYPE) continue;
542
+ if (ace.type !== ACCESS_ALLOWED_ACE_TYPE) return false;
543
+ if (ace.sid !== sid && ace.sid !== LOCAL_SYSTEM_SID && ace.sid !== BUILTIN_ADMINISTRATORS_SID) return false;
544
+ }
545
+ return true;
546
+ }
547
+ /** A private directory must additionally pass a current-SID grant to ordinary
548
+ * files and subdirectories. OI/CI can be distributed across multiple ACEs;
549
+ * inherit-only entries still express child inheritance and are not treated as
550
+ * proof of current-directory access. Actual OS access decides usability. */
551
+ function isOwnerPrivateDirectoryAcl(view, sid) {
552
+ if (!isOwnerPrivateAcl(view, sid)) return false;
553
+ let objectInherit = false;
554
+ let containerInherit = false;
555
+ for (const ace of view.aces) {
556
+ if (ace.type !== ACCESS_ALLOWED_ACE_TYPE || ace.sid !== sid) continue;
557
+ objectInherit ||= (ace.flags & OBJECT_INHERIT_ACE) !== 0;
558
+ containerInherit ||= (ace.flags & CONTAINER_INHERIT_ACE) !== 0;
559
+ }
560
+ return objectInherit && containerInherit;
561
+ }
562
+ /** A held named mutex seat with one idempotent release. */
563
+ var NamedMutexSeat = class {
564
+ handle;
565
+ bridge;
566
+ name;
567
+ constructor(bridge, handle, name) {
568
+ this.bridge = bridge;
569
+ this.handle = handle;
570
+ this.name = name;
571
+ }
572
+ assertCurrent() {
573
+ if (this.handle === void 0) throw new Error(`native win32: seat ${this.name} is already closed`);
574
+ }
575
+ async close() {
576
+ const handle = this.handle;
577
+ if (handle === void 0) return;
578
+ this.handle = void 0;
579
+ this.bridge.releaseMutex(handle);
580
+ this.bridge.closeHandle(handle);
581
+ }
582
+ };
583
+ /**
584
+ * Acquire one named `Global\` mutex seat. `conflictCode` is thrown when another
585
+ * live process holds it. A newly created object gets the supplied protected
586
+ * descriptor; only an already existing object needs its descriptor proved
587
+ * before this process adopts it.
588
+ */
589
+ async function acquireWin32KernelSeat(name, conflictCode) {
590
+ const load = loadBridge$1();
591
+ if (!load.ok) throw new Error(`native win32: ${load.code}`);
592
+ const bridge = load.bridge;
593
+ const sid = win32CurrentTokenSid();
594
+ if (sid === void 0) throw new Error("native win32: the current token SID is unavailable");
595
+ const security = securityAttributesForSddl(bridge, `D:P(A;;GA;;;${sid})`);
596
+ let handle;
597
+ let createError = 0;
598
+ try {
599
+ bridge.setLastError(0);
600
+ handle = bridge.createMutexW(security.attributes, 0, name);
601
+ createError = lastError(bridge);
602
+ } finally {
603
+ bridge.localFree(security.sd);
604
+ }
605
+ if (handle === null || handle === void 0) {
606
+ if (createError === ERROR_ACCESS_DENIED) throw new Error("native win32: the named seat is owned by another account");
607
+ if (createError === ERROR_INVALID_HANDLE) throw new Error("native win32: the named seat is another object type");
608
+ throw new Error(`native win32: the named seat could not be created (${String(createError)})`);
609
+ }
610
+ try {
611
+ if (createError === ERROR_ALREADY_EXISTS && !isOwnerPrivateAcl(readSecurityInfo(handle, SE_KERNEL_OBJECT), sid)) throw new Error("native win32: the named seat has a foreign or broad security descriptor");
612
+ const wait = bridge.waitForSingleObject(handle, 0);
613
+ if (wait === WAIT_TIMEOUT) throw Object.assign(/* @__PURE__ */ new Error("native win32: the named seat is already held"), { code: conflictCode });
614
+ if (wait !== WAIT_OBJECT_0 && wait !== WAIT_ABANDONED) throw new Error(`native win32: the named seat wait failed (${String(wait)})`);
615
+ return new NamedMutexSeat(bridge, handle, name);
616
+ } catch (error) {
617
+ bridge.closeHandle(handle);
618
+ throw error;
619
+ }
620
+ }
621
+ /** The deterministic Host/admin mutex name: no secret, bound to scopeId only. */
622
+ function win32SeatName(scopeId, purpose) {
623
+ return `Global\\dsh-pi-tui-${purpose}-${scopeId.slice(0, 48)}`;
624
+ }
625
+ /** The deterministic per-instance stop event name. */
626
+ function win32StopEventName(scopeId, instanceId) {
627
+ return `Global\\dsh-pi-tui-stop-${scopeId.slice(0, 24)}-${instanceId}`;
628
+ }
629
+ /** Open one control-side per-instance stop event and verify its existing-object private boundary. */
630
+ function openWin32StopSignal(scopeId, instanceId) {
631
+ const load = loadBridge$1();
632
+ if (!load.ok) throw new Error(`native win32: ${load.code}`);
633
+ const bridge = load.bridge;
634
+ const sid = win32CurrentTokenSid();
635
+ if (sid === void 0) throw new Error("native win32: the current token SID is unavailable");
636
+ const handle = bridge.openEventW(1179650, 0, win32StopEventName(scopeId, instanceId));
637
+ if (handle === null || handle === void 0) {
638
+ const code = lastError(bridge);
639
+ if (code === 5) throw new Error("native win32: the stop event is owned by another account");
640
+ throw new Error(`native win32: the stop event is unavailable (${String(code)})`);
641
+ }
642
+ if (!isOwnerPrivateAcl(readSecurityInfo(handle, SE_KERNEL_OBJECT), sid)) {
643
+ bridge.closeHandle(handle);
644
+ throw new Error("native win32: the stop event has a foreign or broad security descriptor");
645
+ }
646
+ let set = false;
647
+ let closed = false;
648
+ return {
649
+ setOnce() {
650
+ if (set || closed) return;
651
+ set = true;
652
+ if (!bridge.setEvent(handle)) throw new Error(`native win32: SetEvent failed (${String(lastError(bridge))})`);
653
+ },
654
+ close() {
655
+ if (closed) return;
656
+ closed = true;
657
+ bridge.closeHandle(handle);
658
+ }
659
+ };
660
+ }
661
+ /** Whether a path is on a local fixed NTFS volume (the PR2 supported domain). */
662
+ function isWin32LocalFixedNtfs(path) {
663
+ const load = loadBridge$1();
664
+ if (!load.ok) return false;
665
+ const bridge = load.bridge;
666
+ const root = path.slice(0, 2) + "\\";
667
+ if (!/^[A-Za-z]:\\/u.test(root)) return false;
668
+ if (bridge.getDriveTypeW(root) !== DRIVE_FIXED) return false;
669
+ const fsNameChars = 32;
670
+ const fsName = Buffer.alloc(64);
671
+ const flags = Buffer.alloc(4);
672
+ return bridge.getVolumeInformationW(root, null, 0, null, null, flags, fsName, fsNameChars) && fsName.toString("utf16le").replace(/\0.*$/u, "").toUpperCase() === "NTFS";
673
+ }
674
+ /** Read Win32 file attributes; undefined when the path is absent or unreadable. */
675
+ function win32FileAttributes(path) {
676
+ const load = loadBridge$1();
677
+ if (!load.ok) return void 0;
678
+ const value = load.bridge.getFileAttributesW(path) >>> 0;
679
+ if (value === 4294967295) return void 0;
680
+ return {
681
+ directory: (value & FILE_ATTRIBUTE_DIRECTORY) !== 0,
682
+ reparse: (value & FILE_ATTRIBUTE_REPARSE_POINT) !== 0
683
+ };
684
+ }
685
+ /** Open one existing path for a security-descriptor read without following a final reparse. */
686
+ function openExistingPath(path) {
687
+ const load = loadBridge$1();
688
+ if (!load.ok) return void 0;
689
+ const handle = load.bridge.createFileW(path, 131200, FILE_SHARE_ALL, null, OPEN_EXISTING, 35651584, null);
690
+ return handle === null || handle === void 0 ? void 0 : handle;
691
+ }
692
+ /** Verify one existing product directory is a real, non-reparse, private object. */
693
+ function win32PrivateDirectorySafe(path) {
694
+ const attributes = win32FileAttributes(path);
695
+ if (attributes === void 0 || !attributes.directory || attributes.reparse) return false;
696
+ const handle = openExistingPath(path);
697
+ if (handle === void 0) return false;
698
+ try {
699
+ const sid = win32CurrentTokenSid();
700
+ return sid !== void 0 && isOwnerPrivateDirectoryAcl(readSecurityInfo(handle, SE_FILE_OBJECT), sid);
701
+ } finally {
702
+ closeWin32Handle(handle);
703
+ }
704
+ }
705
+ /** Verify one existing product file is a real, non-reparse, private object. */
706
+ function win32PrivateFileSafe(path) {
707
+ const attributes = win32FileAttributes(path);
708
+ if (attributes === void 0 || attributes.directory || attributes.reparse) return false;
709
+ const handle = openExistingPath(path);
710
+ if (handle === void 0) return false;
711
+ try {
712
+ const sid = win32CurrentTokenSid();
713
+ return sid !== void 0 && isOwnerPrivateAcl(readSecurityInfo(handle, SE_FILE_OBJECT), sid);
714
+ } finally {
715
+ closeWin32Handle(handle);
716
+ }
717
+ }
718
+ /** Classify one existing product file before any write/append/cleanup. Only a
719
+ * true missing path is `missing`; every other lstat/open/type/ACL failure is
720
+ * `unsafe` so a caller cannot treat a dangling link or unreadable target as
721
+ * absent. */
722
+ function win32PrivateFileStatus(path) {
723
+ let info;
724
+ try {
725
+ info = lstatSync(path);
726
+ } catch (error) {
727
+ return error.code === "ENOENT" ? "missing" : "unsafe";
728
+ }
729
+ if (info.isSymbolicLink() || !info.isFile()) return "unsafe";
730
+ return win32PrivateFileSafe(path) ? "private" : "unsafe";
731
+ }
732
+ /** Create one directory with a protected owner-only DACL; an already existing
733
+ * directory is reused only after its current owner SID, DACL and child-inherit
734
+ * grants are proved. Created files inherit the directory's ACL and are checked
735
+ * by the shared private-file predicate; the file itself need not carry the
736
+ * protected bit. */
737
+ function ensureWin32PrivateDirectory(path) {
738
+ const load = loadBridge$1();
739
+ if (!load.ok) throw new Error(`native win32: ${load.code}`);
740
+ const bridge = load.bridge;
741
+ const sid = win32CurrentTokenSid();
742
+ if (sid === void 0) throw new Error("native win32: the current token SID is unavailable");
743
+ const security = securityAttributesForSddl(bridge, `D:P(A;OICI;FA;;;${sid})`);
744
+ let created;
745
+ let createError = 0;
746
+ try {
747
+ created = bridge.createDirectoryW(path, security.attributes);
748
+ if (!created) createError = lastError(bridge);
749
+ } finally {
750
+ bridge.localFree(security.sd);
751
+ }
752
+ if (created) return;
753
+ if (createError !== ERROR_ALREADY_EXISTS) throw new Error(`native win32: the private directory could not be created (${String(createError)})`);
754
+ if (!win32PrivateDirectorySafe(path)) throw new Error("native win32: an existing private directory is not private");
755
+ }
11
756
  /** `<sys/proc_info.h>`: PROC_PIDTBSDINFO. */
12
757
  const PROC_PIDTBSDINFO_FLAVOR = 3;
13
758
  /** XNU's private flavor 17 (PROC_PIDUNIQIDENTIFIERINFO), not in the public SDK. */
@@ -62,7 +807,9 @@ function loadBridge() {
62
807
  if (loaded !== void 0) return loaded;
63
808
  let result;
64
809
  try {
65
- const koffi = createRequire(import.meta.url)("koffi");
810
+ const anchor = installedDshAnchor();
811
+ if (anchor === void 0) throw new Error("native process identity: no installed DSH anchor");
812
+ const koffi = createRequire(import.meta.url)(resolveDshKoffi(anchor));
66
813
  const libproc = koffi.load(LIBPROC);
67
814
  const libsystem = koffi.load(LIBSYSTEM);
68
815
  const bsdInfo = koffi.struct({
@@ -498,6 +1245,7 @@ function readDarwinKernelProcess(pid) {
498
1245
  function readKernelProcess(pid) {
499
1246
  if (process.platform === "linux") return readLinuxKernelProcess(pid);
500
1247
  if (process.platform === "darwin") return readDarwinKernelProcess(pid);
1248
+ if (process.platform === "win32") return readWin32KernelProcessObservation(pid);
501
1249
  return {
502
1250
  kind: "unknown",
503
1251
  code: "NATIVE_UNAVAILABLE"
@@ -515,12 +1263,14 @@ function sameKernelProcess(expected, observed) {
515
1263
  if (actual.platform !== expected.platform || actual.pid !== expected.pid) return "different";
516
1264
  if (expected.platform === "linux" && actual.platform === "linux") return actual.startTicks === expected.startTicks ? "same" : "different";
517
1265
  if (expected.platform === "darwin" && actual.platform === "darwin") return actual.bootUUID === expected.bootUUID && actual.uniqueId === expected.uniqueId && actual.processUUID === expected.processUUID && actual.startSec === expected.startSec && actual.startUsec === expected.startUsec ? "same" : "different";
1266
+ if (expected.platform === "win32" && actual.platform === "win32") return actual.ownerSid === expected.ownerSid && actual.creationFiletime === expected.creationFiletime ? "same" : "different";
518
1267
  return "different";
519
1268
  }
520
1269
  /** Whether one identity is a member of BOTH the target process group and the
521
1270
  * session the owner created for it (`setsid`: sid === pgid). A member that
522
1271
  * changed its group/session no longer proves ownership of the captured group. */
523
1272
  function isOwnedGroupMember(identity, pgid) {
1273
+ if (identity.platform === "win32") return false;
524
1274
  return identity.pgid === pgid && identity.sid === pgid;
525
1275
  }
526
1276
  /**
@@ -594,6 +1344,337 @@ function listKernelGroupMembers(pgid) {
594
1344
  };
595
1345
  }
596
1346
  //#endregion
1347
+ //#region src/client/program-resume/codec.ts
1348
+ /**
1349
+ * The OSC 7577 Program Resume Protocol v0.5 encoder (sender side).
1350
+ *
1351
+ * Pure computation only: no terminal IO, no process state and no clock. The
1352
+ * caller supplies the owning pid, the current Unix second and the already
1353
+ * validated resume command. Every argument is standard Base64 of UTF-8 and
1354
+ * the frame is `ESC ] 7577 ; body :mac=<sha256> ESC \`.
1355
+ *
1356
+ * The MAC is a plain SHA-256 of `body:token`, NOT an HMAC. A valid frame is an
1357
+ * offer to the terminal, never an acknowledgement.
1358
+ *
1359
+ * @module @xmoon76/dsh-pi-tui/client/program-resume/codec
1360
+ */
1361
+ /** The protocol's application budget: complete frame bytes including OSC/ST. */
1362
+ const PROGRAM_RESUME_MAX_WIRE_BYTES = 2048;
1363
+ /** The protocol token grammar. */
1364
+ const TOKEN = /^[A-Za-z0-9_-]{22,64}$/u;
1365
+ /** C0, DEL and C1 are forbidden in decoded text. */
1366
+ const FORBIDDEN_TEXT = /[\u0000-\u001F\u007F-\u009F]/u;
1367
+ const OSC_PREFIX = "\x1B]7577;";
1368
+ const ST = "\x1B\\";
1369
+ /** Whether `value` is a legal protocol capability token. */
1370
+ function isProgramResumeToken(value) {
1371
+ return value !== void 0 && TOKEN.test(value);
1372
+ }
1373
+ /** A positive safe integer rendered without signs or decimals. */
1374
+ function positiveInteger(value, field) {
1375
+ if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`program resume: ${field} must be a positive safe integer`);
1376
+ return value;
1377
+ }
1378
+ /** Standard Base64 of one UTF-8 argument, rejecting invalid Unicode/control. */
1379
+ function encodeText(value, field, allowEmpty) {
1380
+ if (!allowEmpty && value === "") throw new Error(`program resume: ${field} must not be empty`);
1381
+ if (FORBIDDEN_TEXT.test(value)) throw new Error(`program resume: ${field} contains a control character`);
1382
+ const bytes = Buffer.from(value, "utf8");
1383
+ if (bytes.toString("utf8") !== value) throw new Error(`program resume: ${field} is not valid Unicode text`);
1384
+ return bytes.toString("base64");
1385
+ }
1386
+ /** The resume command's first element: an absolute path or a bare command name. */
1387
+ function encodeExecutable(value) {
1388
+ if (value === "" || value.startsWith("-")) throw new Error("program resume: argv[0] must be a command name or absolute path");
1389
+ if (!isAbsolute(value) && value.includes("/")) throw new Error("program resume: a relative argv[0] path is forbidden");
1390
+ return encodeText(value, "argv[0]", false);
1391
+ }
1392
+ function encodeArgv(argv) {
1393
+ if (argv.length === 0 || argv.length > 64) throw new Error(`program resume: argv must contain 1..${String(64)} elements`);
1394
+ const encoded = [encodeExecutable(argv[0])];
1395
+ for (let index = 1; index < argv.length; index += 1) encoded.push(encodeText(argv[index], `argv[${String(index)}]`, true));
1396
+ return encoded.join(",");
1397
+ }
1398
+ function macOf(body, token) {
1399
+ if (!isProgramResumeToken(token)) throw new Error("program resume: the token is not a legal capability token");
1400
+ return createHash("sha256").update(`${body}:${token}`, "utf8").digest("hex");
1401
+ }
1402
+ function frameOf(body, token) {
1403
+ const frame = `${OSC_PREFIX}${body}:mac=${macOf(body, token)}${ST}`;
1404
+ if (Buffer.byteLength(frame, "utf8") > 2048) throw new Error(`program resume: the complete frame exceeds ${String(PROGRAM_RESUME_MAX_WIRE_BYTES)} bytes`);
1405
+ return frame;
1406
+ }
1407
+ /**
1408
+ * Encode one resume report. Throws rather than truncating or emitting a
1409
+ * partial frame; the caller may send a legal clear instead.
1410
+ */
1411
+ function encodeProgramResumeReport(input) {
1412
+ const pid = positiveInteger(input.pid, "pid");
1413
+ const time = positiveInteger(input.time, "time");
1414
+ const cwdValue = input.cwd;
1415
+ let cwd = "";
1416
+ if (cwdValue !== void 0) {
1417
+ if (!isAbsolute(cwdValue)) throw new Error("program resume: cwd must be absolute");
1418
+ cwd = `:cwd=${encodeText(cwdValue, "cwd", false)}`;
1419
+ }
1420
+ return frameOf(`pid=${String(pid)}:time=${String(time)}:argv=${encodeArgv(input.argv)}${cwd}`, input.token);
1421
+ }
1422
+ /**
1423
+ * Encode one clear report. A clear removes the matching record; it is the
1424
+ * only legal replacement for a resume command the product cannot express.
1425
+ */
1426
+ function encodeProgramResumeClear(input) {
1427
+ const pid = positiveInteger(input.pid, "pid");
1428
+ const time = positiveInteger(input.time, "time");
1429
+ return frameOf(`pid=${String(pid)}:time=${String(time)}:clear=1`, input.token);
1430
+ }
1431
+ //#endregion
1432
+ //#region src/client/program-resume/handoff.ts
1433
+ /**
1434
+ * The private program-resume handoff between the daemon supervisor and its
1435
+ * foreground Client, plus the environment keys the OSC 7577 sender owns.
1436
+ *
1437
+ * The handoff carries only non-secret launch facts. The capability token rides
1438
+ * in its own protocol environment variable and is never duplicated into this
1439
+ * JSON, a log, argv, a Session or a Host DTO.
1440
+ *
1441
+ * @module @xmoon76/dsh-pi-tui/client/program-resume/handoff
1442
+ */
1443
+ /** The protocol's capability environment variable. */
1444
+ const PROGRAM_RESUME_TOKEN_ENV = "OSC7577_TOKEN";
1445
+ /** The private, versioned supervisor -> foreground Client fact channel. */
1446
+ const PROGRAM_RESUME_HANDOFF_ENV = "SPLIT_PROCESS_OSC7577_V1";
1447
+ /** Encode the non-secret facts for the foreground Client environment. */
1448
+ function encodeProgramResumeHandoff(facts) {
1449
+ return JSON.stringify({
1450
+ version: facts.version,
1451
+ ownerPid: facts.ownerPid,
1452
+ home: facts.home,
1453
+ profile: facts.profile,
1454
+ backend: facts.backend,
1455
+ cwd: facts.cwd,
1456
+ nodePath: facts.nodePath,
1457
+ cliPath: facts.cliPath
1458
+ });
1459
+ }
1460
+ /** Remove both fields from a child-environment copy. */
1461
+ function scrubProgramResumeEnvironment(env) {
1462
+ delete env[PROGRAM_RESUME_TOKEN_ENV];
1463
+ delete env[PROGRAM_RESUME_HANDOFF_ENV];
1464
+ }
1465
+ //#endregion
1466
+ //#region src/client/program-resume/target.ts
1467
+ /**
1468
+ * The authoritative OSC 7577 resume target: exact launch scope -> the public
1469
+ * cold-open command. This module is Client-local and performs only boot-time
1470
+ * proof; Session identity stays with the production ownership core.
1471
+ *
1472
+ * A target is produced only when EVERY launch fact is losslessly expressible:
1473
+ * the real official Profile, absolute DSH home, the actual backend, the real
1474
+ * CLI launch cwd, the current Node executable and the exact official DSH JS
1475
+ * entry. Overlays, an explicit preset, telemetry overrides, special Node flags,
1476
+ * a multiplexer/SSH topology, a non-TTY launch or an untrusted token source
1477
+ * disable the sender instead of guessing.
1478
+ *
1479
+ * @module @xmoon76/dsh-pi-tui/client/program-resume/target
1480
+ */
1481
+ /** The fixed protocol command prefix; `/usr/bin/env` is a real executable. */
1482
+ const ENV = "/usr/bin/env";
1483
+ const FORBIDDEN_PATH_TEXT = /[\u0000-\u001F\u007F-\u009F]/u;
1484
+ /** A readable regular file. */
1485
+ function regularFile(path) {
1486
+ try {
1487
+ if (!statSync(path).isFile()) return false;
1488
+ accessSync(path, constants.R_OK);
1489
+ return true;
1490
+ } catch {
1491
+ return false;
1492
+ }
1493
+ }
1494
+ /** An executable regular file. */
1495
+ function executableFile(path) {
1496
+ try {
1497
+ if (!statSync(path).isFile()) return false;
1498
+ accessSync(path, constants.X_OK);
1499
+ return true;
1500
+ } catch {
1501
+ return false;
1502
+ }
1503
+ }
1504
+ /** A readable/traversable directory. */
1505
+ function directory(path) {
1506
+ try {
1507
+ if (!statSync(path).isDirectory()) return false;
1508
+ accessSync(path, constants.X_OK);
1509
+ return true;
1510
+ } catch {
1511
+ return false;
1512
+ }
1513
+ }
1514
+ /** Resolve the exact official CLI entry from the installed DSH manifest. */
1515
+ function resolveOfficialCliEntry(installAnchor, expectedEntry) {
1516
+ if (!isAbsolute(installAnchor)) return void 0;
1517
+ let manifestPath;
1518
+ let manifest;
1519
+ try {
1520
+ manifestPath = realpathSync(installAnchor);
1521
+ manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
1522
+ } catch {
1523
+ return;
1524
+ }
1525
+ if (manifest === null || typeof manifest !== "object" || Array.isArray(manifest)) return void 0;
1526
+ const record = manifest;
1527
+ if (record.name !== "@deepseek-ai/dsh" || typeof record.version !== "string") return void 0;
1528
+ const bin = record.bin;
1529
+ const relative = bin !== null && typeof bin === "object" && !Array.isArray(bin) ? bin.dsh : void 0;
1530
+ if (typeof relative !== "string" || relative === "" || isAbsolute(relative)) return void 0;
1531
+ const root = dirname(manifestPath);
1532
+ let entry;
1533
+ try {
1534
+ entry = realpathSync(join(root, relative));
1535
+ } catch {
1536
+ return;
1537
+ }
1538
+ if (entry !== root && !entry.startsWith(`${root}${sep}`)) return void 0;
1539
+ if (!regularFile(entry)) return void 0;
1540
+ if (expectedEntry !== void 0) try {
1541
+ if (realpathSync(expectedEntry) !== entry) return void 0;
1542
+ } catch {
1543
+ return;
1544
+ }
1545
+ return entry;
1546
+ }
1547
+ /** The inherited process-layer value, or undefined. */
1548
+ function processLayer(launch, name) {
1549
+ const entry = launch.getFrom(name, ["process"]);
1550
+ return entry === void 0 || entry.value === "" ? void 0 : entry.value;
1551
+ }
1552
+ /** Whether the launch topology may report at all. */
1553
+ function topologyAdmitted(env, launch) {
1554
+ if (processLayer(launch, "SSH_CONNECTION") !== void 0 || processLayer(launch, "SSH_TTY") !== void 0) return false;
1555
+ for (const name of [
1556
+ "TMUX",
1557
+ "STY",
1558
+ "ZELLIJ"
1559
+ ]) {
1560
+ const value = env[name];
1561
+ if (value !== void 0 && value !== "") return false;
1562
+ }
1563
+ return true;
1564
+ }
1565
+ /** The frozen resume argv cannot carry either official preset input form. */
1566
+ function presetAdmitted(presetId, env) {
1567
+ return (presetId === void 0 || presetId === "") && (env.DSH_PI_TUI_PRESET?.trim() ?? "") === "";
1568
+ }
1569
+ /** The one official-profile admission shared by Direct and the daemon supervisor. */
1570
+ function profileAdmitted(input) {
1571
+ if (input.platform !== "linux" && input.platform !== "darwin") return false;
1572
+ if (!input.stdinIsTTY || !input.stdoutIsTTY) return false;
1573
+ if (!presetAdmitted(input.presetId, input.env)) return false;
1574
+ if (input.profileContext.overlays.length !== 0) return false;
1575
+ if ((input.profileContext.telemetryDisabledEnv ?? "") !== "") return false;
1576
+ if (input.execArgv.length !== 0) return false;
1577
+ if (processLayer(input.launch, "NODE_OPTIONS") !== void 0) return false;
1578
+ const flatNodeOptions = input.env.NODE_OPTIONS;
1579
+ if (flatNodeOptions !== void 0 && flatNodeOptions !== "") return false;
1580
+ if (!topologyAdmitted(input.env, input.launch)) return false;
1581
+ return true;
1582
+ }
1583
+ /** An absolute, control-free path string. */
1584
+ function pathTextAdmitted(value) {
1585
+ return isAbsolute(value) && !FORBIDDEN_PATH_TEXT.test(value);
1586
+ }
1587
+ /** Validate the profile name/path text the command must carry verbatim. */
1588
+ function scopeTextAdmitted(input) {
1589
+ if (input.name === "" || input.name.startsWith("-") || FORBIDDEN_PATH_TEXT.test(input.name)) return false;
1590
+ return pathTextAdmitted(input.home) && pathTextAdmitted(input.cwd) && directory(input.home) && directory(input.cwd);
1591
+ }
1592
+ /** Build the non-secret facts once the caller has the trusted token. */
1593
+ function capabilityOf(input) {
1594
+ if (!isProgramResumeToken(input.token)) return void 0;
1595
+ if (!Number.isSafeInteger(input.ownerPid) || input.ownerPid <= 0) return void 0;
1596
+ if (!pathTextAdmitted(input.nodePath) || !pathTextAdmitted(input.cliPath)) return void 0;
1597
+ if (!executableFile(ENV) || !executableFile(input.nodePath) || !regularFile(input.cliPath)) return void 0;
1598
+ if (!scopeTextAdmitted(input.profileContext)) return void 0;
1599
+ return {
1600
+ token: input.token,
1601
+ facts: {
1602
+ version: 1,
1603
+ ownerPid: input.ownerPid,
1604
+ home: input.profileContext.home,
1605
+ profile: input.profileContext.name,
1606
+ backend: input.backend,
1607
+ cwd: input.profileContext.cwd,
1608
+ nodePath: input.nodePath,
1609
+ cliPath: input.cliPath
1610
+ }
1611
+ };
1612
+ }
1613
+ /** The Direct CLI's capability: token must come from the inherited layer only. */
1614
+ function directProgramResumeCapability(input) {
1615
+ if (!profileAdmitted(input)) return void 0;
1616
+ const token = processLayer(input.launch, "OSC7577_TOKEN");
1617
+ if (token === void 0) return void 0;
1618
+ const argv1 = input.argv[1];
1619
+ if (argv1 === void 0) return void 0;
1620
+ const cli = resolveOfficialCliEntry(input.profileContext.installAnchor, argv1);
1621
+ if (cli === void 0) return void 0;
1622
+ return capabilityOf({
1623
+ profileContext: input.profileContext,
1624
+ launch: input.launch,
1625
+ token,
1626
+ backend: "direct",
1627
+ ownerPid: process.pid,
1628
+ nodePath: input.execPath,
1629
+ cliPath: cli
1630
+ });
1631
+ }
1632
+ /** The daemon supervisor's capability: same proof, daemon backend and own PID. */
1633
+ function daemonProgramResumeCapability(input) {
1634
+ if (!profileAdmitted(input)) return void 0;
1635
+ const token = processLayer(input.launch, "OSC7577_TOKEN");
1636
+ if (token === void 0) return void 0;
1637
+ const argv1 = input.argv[1];
1638
+ if (argv1 === void 0) return void 0;
1639
+ const cli = resolveOfficialCliEntry(input.profileContext.installAnchor, argv1);
1640
+ if (cli === void 0) return void 0;
1641
+ return capabilityOf({
1642
+ profileContext: input.profileContext,
1643
+ launch: input.launch,
1644
+ token,
1645
+ backend: "daemon",
1646
+ ownerPid: process.pid,
1647
+ nodePath: input.execPath,
1648
+ cliPath: cli
1649
+ });
1650
+ }
1651
+ /**
1652
+ * Freeze the exact cold-open command for one committed canonical Session.
1653
+ * @param capability - the already-admitted launch capability.
1654
+ * @param sessionId - the committed main-owner Session id.
1655
+ * @returns the command, or undefined when the id is not canonical.
1656
+ */
1657
+ function programResumeTarget(capability, sessionId) {
1658
+ if (sessionId === void 0 || !canonicalFullSessionId(sessionId)) return void 0;
1659
+ const facts = capability.facts;
1660
+ return {
1661
+ token: capability.token,
1662
+ ownerPid: facts.ownerPid,
1663
+ cwd: facts.cwd,
1664
+ argv: [
1665
+ ENV,
1666
+ `DSH_HOME=${facts.home}`,
1667
+ `DSH_PI_TUI_BACKEND=${facts.backend}`,
1668
+ facts.nodePath,
1669
+ facts.cliPath,
1670
+ "--profile",
1671
+ facts.profile,
1672
+ "--session",
1673
+ sessionId
1674
+ ]
1675
+ };
1676
+ }
1677
+ //#endregion
597
1678
  //#region src/app/remote-process/local-scope.ts
598
1679
  /**
599
1680
  * Local Host/Client scope, process seats and installed-build identity.
@@ -660,19 +1741,22 @@ function assertDarwin() {
660
1741
  function processSeatPath(scopeDir, scopeId, kind) {
661
1742
  return join(scopeDir, `seat-${kind}-${scopeId}.lock`);
662
1743
  }
663
- /** Validate one already-claimed seat file: a real regular file, owned by this
664
- * user, readable/writable by this user ONLY, with exactly one link. */
665
- function assertSeatFileSafe(path, uid) {
1744
+ /** Read and validate one seat file: a real regular file, owned by this user,
1745
+ * readable/writable by this user ONLY, with exactly one link. Absence is the
1746
+ * normal create path; every other read or validation failure is unsafe. */
1747
+ function readSafeSeatFile(path, uid) {
666
1748
  let info;
667
1749
  try {
668
1750
  info = lstatSync(path);
669
1751
  } catch (error) {
1752
+ if (error.code === "ENOENT") return void 0;
670
1753
  throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} is not accessible`, error);
671
1754
  }
672
1755
  if (info.isSymbolicLink()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} must not be a symlink`);
673
1756
  if (!info.isFile()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} must be a regular file`);
674
1757
  if (info.uid !== uid || (info.mode & 511) !== DARWIN_SEAT_FILE_MODE) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} must be owned by uid ${String(uid)} with mode 0600`);
675
1758
  if (info.nlink !== 1) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} must have exactly one link`);
1759
+ return info;
676
1760
  }
677
1761
  /** Validate the private 0700 directory the seat file lives in. */
678
1762
  function assertSeatDirectorySafe(dir, uid) {
@@ -714,9 +1798,9 @@ var DarwinKernelSeat = class {
714
1798
  if (this.fd === void 0) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", `local scope: seat ${this.path} was already closed`);
715
1799
  const directory = assertSeatDirectorySafe(this.dir, this.uid);
716
1800
  if (directory.dev !== this.dirDev || directory.ino !== this.dirIno) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat directory ${this.dir} was replaced`);
717
- assertSeatFileSafe(this.path, this.uid);
1801
+ const pathInfo = readSafeSeatFile(this.path, this.uid);
1802
+ if (pathInfo === void 0) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${this.path} is no longer present`);
718
1803
  const held = fstatSync(this.fd);
719
- const pathInfo = lstatSync(this.path);
720
1804
  if (held.dev !== pathInfo.dev || held.ino !== pathInfo.ino || held.uid !== pathInfo.uid || (held.mode & 511) !== (pathInfo.mode & 511) || held.nlink !== pathInfo.nlink) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", `local scope: seat ${this.path} no longer matches the held inode`);
721
1805
  }
722
1806
  /**
@@ -741,14 +1825,7 @@ async function bindDarwinKernelSeat(scopeDir, scopeId, kind, conflictCode) {
741
1825
  const uid = assertDarwin();
742
1826
  const dirIdentity = assertSeatDirectorySafe(scopeDir, uid);
743
1827
  const path = processSeatPath(scopeDir, scopeId, kind);
744
- let existing = true;
745
- try {
746
- lstatSync(path);
747
- } catch (error) {
748
- if (error.code !== "ENOENT") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: seat ${path} is not accessible`, error);
749
- existing = false;
750
- }
751
- if (existing) assertSeatFileSafe(path, uid);
1828
+ readSafeSeatFile(path, uid);
752
1829
  let fd;
753
1830
  try {
754
1831
  fd = openSync(path, DARWIN_SEAT_FLAGS, DARWIN_SEAT_FILE_MODE);
@@ -1039,7 +2116,8 @@ function listInstalledDistFiles(packageRoot) {
1039
2116
  * Fingerprint the actual installed payload. Every regular `dist/**` `.mjs`
1040
2117
  * contributes `relative-posix-name NUL sha256(content) LF` in UTF-8 byte
1041
2118
  * order; the bundle and DSH versions close the stream. The value is computed
1042
- * once by the Host at startup and once by each Client from its own install.
2119
+ * once by the Host at startup and by surface Client startup/reexec paths that
2120
+ * need exact process identity.
1043
2121
  */
1044
2122
  function computeBuildId(packageRoot, dshVersion) {
1045
2123
  if (dshVersion === "") throw new Error("local scope: the installed DSH version must not be empty");
@@ -1062,6 +2140,54 @@ function computeBuildId(packageRoot, dshVersion) {
1062
2140
  hash.update("\n");
1063
2141
  return hash.digest("hex");
1064
2142
  }
2143
+ /** Canonicalize one official Windows directory to the local fixed-NTFS domain. */
2144
+ function canonicalWin32Directory(pathValue, label) {
2145
+ let real;
2146
+ try {
2147
+ real = realpathSync.native(pathValue);
2148
+ } catch (error) {
2149
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} is not a readable directory`, error);
2150
+ }
2151
+ if (!/^[A-Za-z]:\\/u.test(real)) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} must be a local drive path`);
2152
+ const canonical = real.slice(0, 1).toUpperCase() + real.slice(1);
2153
+ if (!isWin32LocalFixedNtfs(canonical)) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} must be on a local fixed NTFS volume`);
2154
+ if (!statSync(canonical).isDirectory()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} must be a directory`);
2155
+ return canonical;
2156
+ }
2157
+ /** The read-only Win32 scope: SID + canonical profile path, fixed hash domain. */
2158
+ function inspectWin32ProfileScope(facts) {
2159
+ const dshHome = canonicalWin32Directory(facts.dshHome, "DSH home");
2160
+ const profileRealpath = canonicalWin32Directory(facts.profileDir, "profile directory");
2161
+ const sid = win32CurrentTokenSid();
2162
+ if (sid === void 0) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the current token SID is unavailable");
2163
+ const bundleVersion = readBundleVersion(facts.packageRoot);
2164
+ const scopeId = createHash("sha256").update(`dsh-pi-tui/local-scope/win32/1\0${sid}\0${profileRealpath}`).digest("hex");
2165
+ return Object.freeze({
2166
+ scopeId,
2167
+ dshHome,
2168
+ profileRealpath,
2169
+ dir: join(dshHome, RUN_ROOT_NAME, SCOPE_ROOT_NAME, scopeId),
2170
+ bundleVersion,
2171
+ dshVersion: facts.dshVersion
2172
+ });
2173
+ }
2174
+ /** Create the Win32 private run chain with protected owner-only DACLs on new
2175
+ * directories; existing directories are reused under the shared private-object
2176
+ * predicate, and files inside inherit the directory ACL and are admitted by the
2177
+ * shared private-file predicate. */
2178
+ function ensureWin32ScopeDirectory(dshHome, scopeId) {
2179
+ const dir = join(dshHome, RUN_ROOT_NAME, SCOPE_ROOT_NAME, scopeId);
2180
+ for (const path of [
2181
+ join(dshHome, RUN_ROOT_NAME),
2182
+ join(dshHome, RUN_ROOT_NAME, SCOPE_ROOT_NAME),
2183
+ dir
2184
+ ]) try {
2185
+ ensureWin32PrivateDirectory(path);
2186
+ } catch (error) {
2187
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not a private product directory`, error);
2188
+ }
2189
+ return dir;
2190
+ }
1065
2191
  /**
1066
2192
  * Compute the READ-ONLY identity of one installed profile scope. The caller
1067
2193
  * supplies the official DSH home/profile resolution results; this module never
@@ -1072,9 +2198,10 @@ function computeBuildId(packageRoot, dshVersion) {
1072
2198
  * the exact same computation with the one directory-creation step.
1073
2199
  */
1074
2200
  function inspectInstalledProfileScope(facts) {
2201
+ if (process.platform === "win32") return inspectWin32ProfileScope(facts);
1075
2202
  const uid = assertSupportedPosixScopePlatform();
1076
2203
  const dshHome = process.platform === "darwin" ? canonicalOwnedDirectory(facts.dshHome, uid, "DSH home") : canonicalDirectory(facts.dshHome, "DSH home");
1077
- const profileRealpath = process.platform === "darwin" ? canonicalOwnedDirectory(facts.profileDir, uid, "profile directory") : canonicalDirectory(facts.profileDir, "profile directory");
2204
+ const profileRealpath = canonicalDirectory(facts.profileDir, "profile directory");
1078
2205
  const bundleVersion = readBundleVersion(facts.packageRoot);
1079
2206
  const scopeId = createHash("sha256").update(`dsh-pi-tui/local-scope/1\0${String(uid)}\0${profileRealpath}`).digest("hex");
1080
2207
  return Object.freeze({
@@ -1084,24 +2211,35 @@ function inspectInstalledProfileScope(facts) {
1084
2211
  dir: join(dshHome, RUN_ROOT_NAME, SCOPE_ROOT_NAME, scopeId),
1085
2212
  hostSocketName: `${HOST_SEAT_PREFIX}${scopeId.slice(0, 40)}`,
1086
2213
  clientSeatSocketName: `${CLIENT_SEAT_PREFIX}${scopeId.slice(0, 40)}`,
1087
- buildId: computeBuildId(facts.packageRoot, facts.dshVersion),
1088
2214
  bundleVersion,
1089
2215
  dshVersion: facts.dshVersion
1090
2216
  });
1091
2217
  }
1092
2218
  /**
1093
- * Build the one scope for an installed profile AND create/prove its private
1094
- * 0700 run directory, before any process seat or Host Context exists. The
1095
- * scope identity comes from the same read-only computation above; only the run
1096
- * directory creation is added here, so Host admission and stdout/qualification
1097
- * shapes stay unchanged.
2219
+ * Strictly materialize the current installed build for one previously resolved
2220
+ * scope identity. Callers that publish a Host or start a detached process call
2221
+ * this explicitly; a failed walk cannot be hidden
2222
+ * by a placeholder or replaced by a version/mtime.
2223
+ */
2224
+ function materializeBuild(identity, packageRoot) {
2225
+ return Object.freeze({
2226
+ ...identity,
2227
+ buildId: computeBuildId(packageRoot, identity.dshVersion)
2228
+ });
2229
+ }
2230
+ /**
2231
+ * Create/prove the private run directory for one scope identity, preserving the
2232
+ * caller's exact scope type. This directory step does not materialize a build.
1098
2233
  */
1099
- function scopeFromInstalledProfile(facts) {
1100
- const inspected = inspectInstalledProfileScope(facts);
2234
+ function ensureInstalledProfileScopeDirectory(scope) {
2235
+ if (process.platform === "win32") return Object.freeze({
2236
+ ...scope,
2237
+ dir: ensureWin32ScopeDirectory(scope.dshHome, scope.scopeId)
2238
+ });
1101
2239
  const uid = assertSupportedPosixScopePlatform();
1102
- const dir = ensureScopeDirectory(inspected.dshHome, inspected.scopeId, uid);
2240
+ const dir = ensureScopeDirectory(scope.dshHome, scope.scopeId, uid);
1103
2241
  return Object.freeze({
1104
- ...inspected,
2242
+ ...scope,
1105
2243
  dir
1106
2244
  });
1107
2245
  }
@@ -1177,6 +2315,31 @@ function bindProcessSeat(name, conflictCode) {
1177
2315
  name
1178
2316
  }, conflictCode);
1179
2317
  }
2318
+ async function bindProfileKernelSeat(scope, kind, conflictCode, options = {}) {
2319
+ if (process.platform === "linux") {
2320
+ if (kind === "admin") throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", "local scope: the Linux admin seat uses bindProcessSeat");
2321
+ return bindKernelSeat({
2322
+ claim: "linux-abstract",
2323
+ name: kind === "host" ? scope.hostSocketName : scope.clientSeatSocketName
2324
+ }, conflictCode);
2325
+ }
2326
+ if (process.platform === "darwin") return bindKernelSeat({
2327
+ claim: "darwin-file",
2328
+ dir: kind === "host" ? darwinHostProfileSeatDir(scope.scopeId, options.accountHome) : scope.dir,
2329
+ scopeId: scope.scopeId,
2330
+ kind
2331
+ }, conflictCode);
2332
+ if (process.platform === "win32") {
2333
+ if (kind === "qualification-client") throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", "local scope: the Windows qualification Client seat is not available");
2334
+ try {
2335
+ return await acquireWin32KernelSeat(win32SeatName(scope.scopeId, kind), conflictCode);
2336
+ } catch (error) {
2337
+ if (error.code === conflictCode) throw new LocalScopeError(conflictCode, `local scope: the ${kind} seat of this profile is already held by another live process`, error);
2338
+ throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: the ${kind} seat could not be acquired`, error);
2339
+ }
2340
+ }
2341
+ throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", `local scope: no profile kernel seat is implemented for ${process.platform}`);
2342
+ }
1180
2343
  //#endregion
1181
2344
  //#region src/app/remote-process/entry-control.ts
1182
2345
  /** The single opt-in for the raw M4-A0 JSONL stream, frozen at process start. */
@@ -1293,6 +2456,55 @@ function createEntryDiag(processRole, sink) {
1293
2456
  };
1294
2457
  }
1295
2458
  //#endregion
2459
+ //#region src/app/renderer-opt-in.ts
2460
+ /**
2461
+ * The ONE experimental renderer opt-in predicate. It lives outside the
2462
+ * `app/bootstrap/**` composition zone so every application owner can share the
2463
+ * exact rule without importing bootstrap helpers.
2464
+ *
2465
+ * @module @xmoon76/dsh-pi-tui/app/renderer-opt-in
2466
+ */
2467
+ /** Whether this boot explicitly asked for the experimental TSP renderer. */
2468
+ function tspRequested(env) {
2469
+ return env.DSH_PI_TUI_RENDERER === "tsp";
2470
+ }
2471
+ //#endregion
2472
+ //#region src/app/program-resume-admission.ts
2473
+ /**
2474
+ * The ONE OSC 7577 admission gate shared by the Direct root, the daemon
2475
+ * supervisor and the Client entry. `DSH_PI_TUI_RENDERER=tsp` is an explicit
2476
+ * renderer opt-in: even when the SDK later declines and PiTui fallback mounts,
2477
+ * the boot is still a TSP attempt and must not publish a program-resume record.
2478
+ *
2479
+ * @module @xmoon76/dsh-pi-tui/app/program-resume-admission
2480
+ */
2481
+ /** True only when this boot never requested the experimental TSP renderer. */
2482
+ function programResumeAdmitted(env) {
2483
+ return !tspRequested(env);
2484
+ }
2485
+ /**
2486
+ * Build a capability only when this boot is admitted. A TSP opt-in never
2487
+ * invokes the builder, so the fallback cannot create a reporter later.
2488
+ */
2489
+ function admitProgramResume(env, build) {
2490
+ return programResumeAdmitted(env) ? build() : void 0;
2491
+ }
2492
+ //#endregion
2493
+ //#region src/app/remote-process/program-resume-child.ts
2494
+ /**
2495
+ * The private spawn-boundary fill for one admitted foreground Client's OSC 7577
2496
+ * handoff. The public daemon-launcher child-environment builder stays
2497
+ * capability-free, so its emitted declaration cannot leak the Client-local
2498
+ * target/handoff module paths.
2499
+ *
2500
+ * @module @xmoon76/dsh-pi-tui/app/remote-process/program-resume-child
2501
+ */
2502
+ /** Add the protocol token and non-secret facts only to the admitted child env. */
2503
+ function applyProgramResumeChildEnvironment(env, capability) {
2504
+ env[PROGRAM_RESUME_TOKEN_ENV] = capability.token;
2505
+ env[PROGRAM_RESUME_HANDOFF_ENV] = encodeProgramResumeHandoff(capability.facts);
2506
+ }
2507
+ //#endregion
1296
2508
  //#region src/app/remote-process/daemon-launcher.ts
1297
2509
  /**
1298
2510
  * The M6-2A daemon Coordinator (`@xmoon76/dsh-pi-tui/daemon-launcher`).
@@ -1318,6 +2530,8 @@ const name = "pi-tui-daemon-launcher";
1318
2530
  const inject = ["tuiDaemonStartup"];
1319
2531
  /** The private v1 public-launch data channel (shared shape with the Client entry). */
1320
2532
  const CLIENT_LAUNCH_ENVELOPE_ENV = "SPLIT_PROCESS_CLIENT_LAUNCH_V1";
2533
+ /** The private ACP stdio Adapter target channel. The Parent overwrites it. */
2534
+ const ACP_STDIO_SOCKET_ENV = "DSH_PI_TUI_ACP_STDIO_SOCKET_V1";
1321
2535
  /** The one-shot public launch envelope encoded for the Client child. */
1322
2536
  function encodeLaunchEnvelope(startup) {
1323
2537
  return JSON.stringify({
@@ -1328,20 +2542,21 @@ function encodeLaunchEnvelope(startup) {
1328
2542
  });
1329
2543
  }
1330
2544
  /**
1331
- * Resolve the installed Client entry from THIS package root and prove its real
1332
- * target is a regular file. A shared npm package, a root-owned system install
1333
- * and a legal entry symlink are normal installs; only a missing or non-regular
1334
- * target is a hard failure — never a fallback to a source tree or `tsx`.
2545
+ * Resolve one installed internal process entry from THIS package root and prove
2546
+ * its real target is a regular file. A shared npm package, a root-owned system
2547
+ * install and a legal entry symlink are normal installs; only a missing or
2548
+ * non-regular target is a hard failure — never a fallback to a source tree or
2549
+ * `tsx`.
1335
2550
  */
1336
- function resolveClientEntry(packageRoot) {
1337
- const entry = join(packageRoot, "dist", "local-client.mjs");
2551
+ function resolveProcessEntry(packageRoot, fileName, label) {
2552
+ const entry = join(packageRoot, "dist", fileName);
1338
2553
  let real;
1339
2554
  try {
1340
2555
  real = realpathSync(entry);
1341
2556
  } catch (error) {
1342
- throw new Error(`pi-tui daemon launcher: the Client entry ${entry} is missing`, { cause: error });
2557
+ throw new Error(`pi-tui daemon launcher: the ${label} entry ${entry} is missing`, { cause: error });
1343
2558
  }
1344
- if (!lstatSync(real).isFile()) throw new Error(`pi-tui daemon launcher: the Client entry ${entry} must resolve to a regular file`);
2559
+ if (!lstatSync(real).isFile()) throw new Error(`pi-tui daemon launcher: the ${label} entry ${entry} must resolve to a regular file`);
1345
2560
  let expectedRoot;
1346
2561
  try {
1347
2562
  expectedRoot = realpathSync(packageRoot);
@@ -1352,11 +2567,19 @@ function resolveClientEntry(packageRoot) {
1352
2567
  try {
1353
2568
  entryRoot = installedPackageRootFromEntry(pathToFileURL(entry).href);
1354
2569
  } catch (error) {
1355
- throw new Error(`pi-tui daemon launcher: the Client entry ${entry} cannot locate its installed package root`, { cause: error });
2570
+ throw new Error(`pi-tui daemon launcher: the ${label} entry ${entry} cannot locate its installed package root`, { cause: error });
1356
2571
  }
1357
- if (entryRoot !== expectedRoot) throw new Error(`pi-tui daemon launcher: the Client entry ${entry} resolves a different installed package root`);
2572
+ if (entryRoot !== expectedRoot) throw new Error(`pi-tui daemon launcher: the ${label} entry ${entry} resolves a different installed package root`);
1358
2573
  return entry;
1359
2574
  }
2575
+ function resolveClientEntry(packageRoot) {
2576
+ return resolveProcessEntry(packageRoot, "local-client.mjs", "Client");
2577
+ }
2578
+ /** Resolve the internal ACP stdio Adapter entry with the same installed-package
2579
+ * proof as the Client entry. It is never a public bin or export. */
2580
+ function resolveAcpStdioEntry(packageRoot) {
2581
+ return resolveProcessEntry(packageRoot, "acp-stdio.mjs", "ACP stdio");
2582
+ }
1360
2583
  /**
1361
2584
  * Resolve this installed bundle's package root through the OFFICIAL profile
1362
2585
  * resolution. The launcher module itself may be reached through a symlinked
@@ -1393,17 +2616,64 @@ function buildChildEnvironment(profileContext, launchEnvelope, source = process.
1393
2616
  delete env.DSH_PI_TUI_ROLE;
1394
2617
  delete env.DSH_PI_TUI_HOST_ENTRY;
1395
2618
  delete env.DSH_PI_TUI_BACKEND;
2619
+ scrubProgramResumeEnvironment(env);
1396
2620
  env.SPLIT_PROCESS_DSH_ANCHOR = profileContext.installAnchor;
1397
2621
  env.SPLIT_PROCESS_PROFILE = profileContext.name;
1398
2622
  env.SPLIT_PROCESS_CLIENT_MODE = "surface";
1399
2623
  env[CLIENT_LAUNCH_ENVELOPE_ENV] = launchEnvelope;
1400
2624
  return env;
1401
2625
  }
2626
+ /**
2627
+ * Build the ACP stdio Adapter child environment at the ONE new-spawn boundary.
2628
+ * The adapter is a pure Node stream relay: it receives the Parent-selected
2629
+ * public UDS path and no Split Client/Host role, launch envelope, Cookie or
2630
+ * token. Every inherited internal role fact is stripped before the one
2631
+ * authoritative socket value is written.
2632
+ */
2633
+ function buildAcpStdioEnvironment(socketPath, source = process.env) {
2634
+ const env = { ...source };
2635
+ const internalExact = /* @__PURE__ */ new Set([
2636
+ "DSH_PI_TUI_ROLE",
2637
+ "DSH_PI_TUI_HOST_ENTRY",
2638
+ "DSH_PI_TUI_BACKEND",
2639
+ ACP_STDIO_SOCKET_ENV
2640
+ ]);
2641
+ for (const key of Object.keys(env)) {
2642
+ const upper = key.toUpperCase();
2643
+ if (upper.startsWith("SPLIT_PROCESS_") || internalExact.has(upper)) delete env[key];
2644
+ }
2645
+ scrubProgramResumeEnvironment(env);
2646
+ env[ACP_STDIO_SOCKET_ENV] = socketPath;
2647
+ return env;
2648
+ }
1402
2649
  /** POSIX-safe single-argument quoting for the copy-paste fatal line. */
1403
2650
  function shellQuote(value) {
1404
2651
  if (/^[A-Za-z0-9_@%+=:,./-]+$/u.test(value)) return value;
1405
2652
  return `'${value.replace(/'/gu, `'\\''`)}'`;
1406
2653
  }
2654
+ /** PowerShell single-quoted literal: every recognized single-quote class
2655
+ * (ASCII and U+2018/2019/201A/201B) is doubled; `$`, backtick and the
2656
+ * smart-double-quote classes are literal inside it. Kept local so the daemon
2657
+ * Client plugin never pulls the startup compatibility island (and its
2658
+ * `@deepseek-ai/dsh-cmdline` import) into its runtime graph. */
2659
+ function powershellQuote(value) {
2660
+ if (/^[A-Za-z0-9_@%+=:,./-]+$/u.test(value)) return value;
2661
+ return `'${value.replace(/['\u2018\u2019\u201a\u201b]/gu, (character) => character + character)}'`;
2662
+ }
2663
+ /**
2664
+ * The one copy-pasteable re-run command for a Client spawn failure. POSIX keeps
2665
+ * its environment-assignment form; Windows gets the PowerShell-equivalent form
2666
+ * because `VAR=value cmd` is not a Windows command. The profile is quoted for
2667
+ * the target shell: POSIX close-reopen quoting versus PowerShell doubled quotes.
2668
+ */
2669
+ function daemonClientRerunCommand(profile, platform = process.platform) {
2670
+ const profileArg = platform === "win32" ? powershellQuote(profile) : shellQuote(profile);
2671
+ return platform === "win32" ? `$env:DSH_PI_TUI_BACKEND='daemon'; dsh --profile ${profileArg}` : `DSH_PI_TUI_BACKEND=daemon dsh --profile ${profileArg}`;
2672
+ }
2673
+ /** The copy-paste Profile literal for the ACTUAL CLI shell. */
2674
+ function platformProfileQuote(value) {
2675
+ return process.platform === "win32" ? powershellQuote(value) : shellQuote(value);
2676
+ }
1407
2677
  /** The child-exit mapping: a real code, or 128+signal when the child was signalled. */
1408
2678
  function exitCodeFor(code, signal) {
1409
2679
  if (code !== null) return code;
@@ -1429,9 +2699,12 @@ var DaemonCoordinator = class {
1429
2699
  /** A sanitized human line for the supervisor TTY when the Client cannot be
1430
2700
  * spawned at all (never a JSON record, never a raw error/message/path). */
1431
2701
  reportFatal;
2702
+ /** Optional ACP-specific formatter; the default keeps the Client wording. */
2703
+ failureLine;
2704
+ spawnFailureExitCode;
1432
2705
  shutdownBudgetMs;
1433
2706
  child;
1434
- childExit;
2707
+ childExited;
1435
2708
  started = false;
1436
2709
  disposed = false;
1437
2710
  settled = false;
@@ -1445,6 +2718,8 @@ var DaemonCoordinator = class {
1445
2718
  this.appExit = options.appExit;
1446
2719
  this.diag = options.diag;
1447
2720
  this.reportFatal = options.reportFatal ?? (() => {});
2721
+ this.failureLine = options.failureLine;
2722
+ this.spawnFailureExitCode = options.spawnFailureExitCode ?? 1;
1448
2723
  this.shutdownBudgetMs = options.shutdownBudgetMs ?? 4e3;
1449
2724
  }
1450
2725
  /** Spawn the ONE foreground Client. No-op after a prior start or dispose. */
@@ -1460,17 +2735,21 @@ var DaemonCoordinator = class {
1460
2735
  env: this.env
1461
2736
  });
1462
2737
  } catch (error) {
1463
- this.settle(1, error instanceof Error ? error : new Error(String(error)));
2738
+ this.settle(this.spawnFailureExitCode, error instanceof Error ? error : new Error(String(error)));
1464
2739
  return;
1465
2740
  }
1466
2741
  this.child = child;
1467
2742
  this.spawnCount += 1;
1468
- this.childExit = new Promise((resolve) => {
2743
+ this.childExited = new Promise((resolve) => {
1469
2744
  child.once("exit", () => resolve());
1470
- child.once("error", () => resolve());
1471
2745
  });
2746
+ const spawned = child.pid !== void 0;
1472
2747
  child.once("error", (error) => {
1473
- this.settle(1, error);
2748
+ if (spawned) {
2749
+ this.diag.warn("pi-tui daemon: child process error after spawn", { error: error.message });
2750
+ return;
2751
+ }
2752
+ this.settle(this.spawnFailureExitCode, error);
1474
2753
  });
1475
2754
  child.once("exit", (code, signal) => {
1476
2755
  this.settle(exitCodeFor(code, signal), void 0);
@@ -1480,30 +2759,31 @@ var DaemonCoordinator = class {
1480
2759
  if (this.settled) return;
1481
2760
  this.settled = true;
1482
2761
  if (error !== void 0) {
1483
- this.diag.warn("pi-tui daemon: client process failed", { error: error.message });
2762
+ this.diag.warn("pi-tui daemon: child process failed", { error: error.message });
1484
2763
  const errno = error.code;
1485
2764
  const safeErrno = typeof errno === "string" && /^[A-Z][A-Z0-9_]{1,31}$/u.test(errno) ? ` (${errno})` : "";
1486
- this.reportFatal(`dsh-pi-tui: could not start the daemon Client process${safeErrno}; the Host was not started. Reinstall the profile and re-run: DSH_PI_TUI_BACKEND=daemon dsh --profile ${shellQuote(this.env.SPLIT_PROCESS_PROFILE)}`);
2765
+ this.reportFatal(this.failureLine !== void 0 ? this.failureLine(safeErrno) : `dsh-pi-tui: could not start the daemon Client process${safeErrno}; the Host was not started. Reinstall the profile and re-run: ${daemonClientRerunCommand(this.env.SPLIT_PROCESS_PROFILE)}`);
1487
2766
  }
1488
2767
  this.appExit(code);
1489
2768
  }
1490
2769
  /**
1491
2770
  * The SINGLE stop owner, AWAITABLE. A spawn not yet started is cancelled; a
1492
- * live child is asked to stop once (SIGTERM) and dispose() resolves only after
1493
- * the child actually exited, so the parent Fiber disposer holds the child's
1494
- * cleanup rather than the parent process exiting underneath it. The wait is
1495
- * bounded to fit the official ~5s shutdown deadline; a child that does not exit
1496
- * within it is escalated to SIGKILL and awaited briefly. Idempotent.
2771
+ * live child is asked to stop once and dispose() resolves only after the child
2772
+ * actually exited, so the parent Fiber disposer holds the child's cleanup
2773
+ * rather than the parent process exiting underneath it. On POSIX the bounded
2774
+ * SIGTERM→SIGKILL sequence fits the official ~5s shutdown deadline. Windows
2775
+ * has no catchable POSIX SIGTERM: the direct child is forcibly terminated once
2776
+ * and only its ACTUAL exit inside the same budget is success; no graceful claim
2777
+ * is made. Idempotent.
1497
2778
  */
1498
2779
  dispose() {
1499
2780
  if (this.disposePromise !== void 0) return this.disposePromise;
1500
2781
  this.disposed = true;
1501
2782
  this.disposePromise = (async () => {
1502
2783
  const child = this.child;
1503
- const exited = this.childExit;
2784
+ const exited = this.childExited;
1504
2785
  if (child === void 0 || child.exitCode !== null || child.signalCode !== null || exited === void 0) return true;
1505
2786
  const budgetEnd = Date.now() + this.shutdownBudgetMs;
1506
- const killAt = budgetEnd - Math.min(1e3, Math.max(50, Math.floor(this.shutdownBudgetMs * .25)));
1507
2787
  const disposeStartedAt = performance.now();
1508
2788
  const waitExitUntil = async (absoluteDeadline) => {
1509
2789
  let timer;
@@ -1516,6 +2796,18 @@ var DaemonCoordinator = class {
1516
2796
  if (timer !== void 0) clearTimeout(timer);
1517
2797
  }
1518
2798
  };
2799
+ if (process.platform === "win32") {
2800
+ try {
2801
+ child.kill();
2802
+ } catch {}
2803
+ if (await waitExitUntil(budgetEnd)) {
2804
+ this.diag.debug("pi-tui daemon: client exited after forced process termination", { durationMs: Math.round((performance.now() - disposeStartedAt) * 10) / 10 });
2805
+ return true;
2806
+ }
2807
+ this.reportFatal("dsh-pi-tui: the daemon Client did not exit after forced process termination within the shutdown budget; it may be left running");
2808
+ return false;
2809
+ }
2810
+ const killAt = budgetEnd - Math.min(1e3, Math.max(50, Math.floor(this.shutdownBudgetMs * .25)));
1519
2811
  try {
1520
2812
  child.kill("SIGTERM");
1521
2813
  } catch {}
@@ -1538,6 +2830,127 @@ var DaemonCoordinator = class {
1538
2830
  }
1539
2831
  };
1540
2832
  /**
2833
+ * The ONE trusted-profile ACP stdio launch lifecycle: one read-only target
2834
+ * preflight followed by at most one internal Adapter child. The launch promise
2835
+ * is created before the cold-ready callback can run, so a reentrant callback or
2836
+ * a fiber disposal can never start a second launch. Disposal aborts the
2837
+ * preflight, awaits its settlement, then disposes the one child.
2838
+ */
2839
+ var AcpStdioRunner = class {
2840
+ options;
2841
+ controller = new AbortController();
2842
+ startGate;
2843
+ releaseStartGate;
2844
+ launchPromise;
2845
+ coordinator;
2846
+ started = false;
2847
+ disposed = false;
2848
+ settled = false;
2849
+ disposePromise;
2850
+ constructor(options) {
2851
+ this.options = options;
2852
+ this.startGate = new Promise((resolve) => {
2853
+ this.releaseStartGate = resolve;
2854
+ });
2855
+ }
2856
+ /** Create the ONE launch promise now; it waits for {@link start}. */
2857
+ prepare() {
2858
+ if (this.launchPromise === void 0) this.launchPromise = this.startGate.then(() => this.launch()).catch(() => {
2859
+ if (this.disposed) return;
2860
+ this.fail("ACP_STDIO_STATUS_UNAVAILABLE", `check the Host state with dsh --profile ${platformProfileQuote(this.options.profileName)} daemon status`, 3);
2861
+ });
2862
+ return this.launchPromise;
2863
+ }
2864
+ /** Release the cold-ready gate exactly once. */
2865
+ start() {
2866
+ if (this.started || this.disposed) return;
2867
+ this.started = true;
2868
+ this.releaseStartGate();
2869
+ }
2870
+ writeStderr(line) {
2871
+ try {
2872
+ (this.options.writeStderr ?? ((text) => {
2873
+ process.stderr.write(text);
2874
+ }))(line);
2875
+ } catch {}
2876
+ }
2877
+ report(code, hint) {
2878
+ this.writeStderr(`dsh-pi-tui acp stdio: ${code}${hint === "" ? "" : `: ${hint}`}\n`);
2879
+ }
2880
+ finish(code) {
2881
+ if (this.settled || this.disposed) return;
2882
+ this.settled = true;
2883
+ this.options.appExit(code);
2884
+ }
2885
+ fail(code, hint, exitCode) {
2886
+ this.report(code, hint);
2887
+ this.finish(exitCode);
2888
+ }
2889
+ async launch() {
2890
+ if (this.disposed) return;
2891
+ let target;
2892
+ try {
2893
+ target = await this.options.preflight(this.controller.signal);
2894
+ } catch {
2895
+ if (this.disposed || this.controller.signal.aborted) return;
2896
+ this.fail("ACP_STDIO_STATUS_UNAVAILABLE", `check the Host state with dsh --profile ${platformProfileQuote(this.options.profileName)} daemon status`, 3);
2897
+ return;
2898
+ }
2899
+ if (this.disposed || this.controller.signal.aborted) return;
2900
+ switch (target.kind) {
2901
+ case "host-unavailable":
2902
+ this.fail("ACP_STDIO_HOST_NOT_READY", `start the Host explicitly with dsh --profile ${platformProfileQuote(this.options.profileName)} daemon start`, 3);
2903
+ return;
2904
+ case "acp-disabled":
2905
+ this.fail("ACP_STDIO_LISTENER_DISABLED", "enable ACP from a connected TUI with /acp", 3);
2906
+ return;
2907
+ case "acp-unavailable":
2908
+ this.fail("ACP_STDIO_LISTENER_UNAVAILABLE", `check the Host state with dsh --profile ${platformProfileQuote(this.options.profileName)} daemon status`, 3);
2909
+ return;
2910
+ }
2911
+ let entry;
2912
+ try {
2913
+ entry = this.options.resolveEntry();
2914
+ } catch {
2915
+ if (this.disposed) return;
2916
+ this.fail("ACP_STDIO_ENTRY_MISSING", "reinstall the profile and re-run the command", 4);
2917
+ return;
2918
+ }
2919
+ if (this.disposed) return;
2920
+ const coordinator = new DaemonCoordinator({
2921
+ spawnImpl: this.options.spawnImpl,
2922
+ entry,
2923
+ env: buildAcpStdioEnvironment(target.socketPath),
2924
+ appExit: (code) => {
2925
+ this.finish(code);
2926
+ },
2927
+ diag: this.options.diag,
2928
+ reportFatal: (line) => {
2929
+ this.writeStderr(`${line}\n`);
2930
+ },
2931
+ failureLine: () => "dsh-pi-tui acp stdio: ACP_STDIO_SPAWN_FAILED",
2932
+ spawnFailureExitCode: 4,
2933
+ ...this.options.shutdownBudgetMs === void 0 ? {} : { shutdownBudgetMs: this.options.shutdownBudgetMs }
2934
+ });
2935
+ this.coordinator = coordinator;
2936
+ coordinator.start();
2937
+ }
2938
+ /** Abort the preflight, await the ONE launch promise and dispose any child. */
2939
+ dispose() {
2940
+ if (this.disposePromise !== void 0) return this.disposePromise;
2941
+ this.disposed = true;
2942
+ this.controller.abort();
2943
+ this.releaseStartGate();
2944
+ const launch = this.launchPromise;
2945
+ this.disposePromise = (async () => {
2946
+ if (launch !== void 0) await launch;
2947
+ const coordinator = this.coordinator;
2948
+ return coordinator === void 0 ? true : await coordinator.dispose();
2949
+ })();
2950
+ return this.disposePromise;
2951
+ }
2952
+ };
2953
+ /**
1541
2954
  * The ONE management operation lifecycle. It runs at most once, writes its
1542
2955
  * output and requests `appExit` exactly once, and a fiber disposal before the
1543
2956
  * result settles suppresses both the output and the exit so a late result can
@@ -1690,8 +3103,37 @@ function apply(ctx) {
1690
3103
  applyWebControl(ctx, startup, profileContext, appExit);
1691
3104
  return;
1692
3105
  }
3106
+ if (startup.kind === "acp-control") {
3107
+ applyAcpControl(ctx, startup, profileContext, appExit);
3108
+ return;
3109
+ }
3110
+ if (startup.kind === "acp-stdio") {
3111
+ applyAcpStdio(ctx, startup, profileContext, appExit);
3112
+ return;
3113
+ }
1693
3114
  const entry = resolveClientEntry(resolveProfilePackageRoot(profileContext.dir));
1694
- const env = buildChildEnvironment(profileContext, encodeLaunchEnvelope(startup));
3115
+ const launchEnvironment = ctx.get("launchEnvironment");
3116
+ const programResume = admitProgramResume(process.env, () => launchEnvironment === void 0 ? void 0 : daemonProgramResumeCapability({
3117
+ profileContext: {
3118
+ name: profileContext.name,
3119
+ home: profileContext.home,
3120
+ cwd: profileContext.cwd,
3121
+ installAnchor: profileContext.installAnchor,
3122
+ overlays: profileContext.overlays ?? [],
3123
+ telemetryDisabledEnv: profileContext.telemetryDisabledEnv
3124
+ },
3125
+ launch: launchEnvironment,
3126
+ presetId: startup.presetId,
3127
+ env: process.env,
3128
+ execArgv: process.execArgv,
3129
+ argv: process.argv,
3130
+ execPath: process.execPath,
3131
+ stdinIsTTY: process.stdin.isTTY === true,
3132
+ stdoutIsTTY: process.stdout.isTTY === true,
3133
+ platform: process.platform
3134
+ }));
3135
+ const env = buildChildEnvironment(profileContext, encodeLaunchEnvelope(startup), process.env);
3136
+ if (programResume !== void 0) applyProgramResumeChildEnvironment(env, programResume);
1695
3137
  const diag = createEntryDiag("host", () => {});
1696
3138
  const reportFatal = (line) => {
1697
3139
  try {
@@ -1745,6 +3187,39 @@ function apply(ctx) {
1745
3187
  }
1746
3188
  ctx.effect(() => () => coordinator.dispose(), "pi-tui-daemon-launcher child lifecycle");
1747
3189
  }
3190
+ /** Assemble the ONE trusted-profile ACP stdio launch for this official Profile.
3191
+ * No Client artifact, TUI, Host or Session is created by the parent; the
3192
+ * preflight is a read-only authenticated `readAcpStdioTarget` call. */
3193
+ function applyAcpStdio(ctx, startup, profileContext, appExit) {
3194
+ const profile = managementProfile(profileContext);
3195
+ const runner = new AcpStdioRunner({
3196
+ profileName: profile.name,
3197
+ preflight: async (signal) => {
3198
+ const { readAcpStdioTarget } = await import("./local-daemon-control-BFJAC8Kg.mjs");
3199
+ return await readAcpStdioTarget(profile, signal);
3200
+ },
3201
+ resolveEntry: () => resolveAcpStdioEntry(profile.packageRoot),
3202
+ spawnImpl: spawn,
3203
+ appExit,
3204
+ diag: createEntryDiag("host", () => {})
3205
+ });
3206
+ runner.prepare();
3207
+ startup.markCoordinatorMounted?.();
3208
+ const ready = ctx.get("appReady");
3209
+ if (ready === void 0) runner.start();
3210
+ else {
3211
+ let registrationReturned = false;
3212
+ const cancel = ready.onReady(() => {
3213
+ if (!registrationReturned) return;
3214
+ runner.start();
3215
+ });
3216
+ registrationReturned = true;
3217
+ ctx.effect(() => () => {
3218
+ cancel();
3219
+ }, "pi-tui-acp-stdio readiness");
3220
+ }
3221
+ ctx.effect(() => () => runner.dispose(), "pi-tui-acp-stdio lifecycle");
3222
+ }
1748
3223
  /** The official Profile facts the one-shot management runners need. */
1749
3224
  function managementProfile(profileContext) {
1750
3225
  return {
@@ -1761,7 +3236,7 @@ function managementProfile(profileContext) {
1761
3236
  function mountManagementRunner(ctx, startup, runner, controller) {
1762
3237
  startup.markCoordinatorMounted?.();
1763
3238
  const ready = ctx.get("appReady");
1764
- const lifecycleName = startup.kind === "web-control" ? "pi-tui-web-control" : "pi-tui-daemon-control";
3239
+ const lifecycleName = startup.kind === "web-control" ? "pi-tui-web-control" : startup.kind === "acp-control" ? "pi-tui-acp-control" : "pi-tui-daemon-control";
1765
3240
  if (ready === void 0) runner.start();
1766
3241
  else {
1767
3242
  let registrationReturned = false;
@@ -1787,12 +3262,31 @@ function applyManagement(ctx, startup, profileContext, appExit) {
1787
3262
  const controller = new AbortController();
1788
3263
  mountManagementRunner(ctx, startup, new DaemonControlRunner({
1789
3264
  run: async () => {
1790
- const { runDaemonControl } = await import("./local-daemon-control-Cu_4FIdd.mjs");
3265
+ const { runDaemonControl } = await import("./local-daemon-control-BFJAC8Kg.mjs");
1791
3266
  return await runDaemonControl(startup.control, profile, { signal: controller.signal });
1792
3267
  },
1793
3268
  appExit
1794
3269
  }), controller);
1795
3270
  }
3271
+ /** Assemble ONE headless ACP CLI operation for this official Profile. It never
3272
+ * resolves a Client artifact, never spawns a Client or the ACP stdio adapter
3273
+ * and never opens the TUI. */
3274
+ function applyAcpControl(ctx, startup, profileContext, appExit) {
3275
+ const profile = managementProfile(profileContext);
3276
+ const controller = new AbortController();
3277
+ mountManagementRunner(ctx, startup, new DaemonControlRunner({
3278
+ run: async () => {
3279
+ const { runLocalAcpControl } = await import("./local-acp-control-CC5z4Xbq.mjs");
3280
+ return await runLocalAcpControl(startup.control, profile, { signal: controller.signal });
3281
+ },
3282
+ appExit,
3283
+ fallback: {
3284
+ code: 4,
3285
+ stdout: "",
3286
+ stderr: "dsh-pi-tui acp: ACP_CLI_UNAVAILABLE: an unexpected local ACP CLI failure occurred\n"
3287
+ }
3288
+ }), controller);
3289
+ }
1796
3290
  /** Assemble ONE headless Web CLI operation for this official Profile. It never
1797
3291
  * resolves a Client artifact, never spawns a Client and never opens the TUI. */
1798
3292
  function applyWebControl(ctx, startup, profileContext, appExit) {
@@ -1800,7 +3294,7 @@ function applyWebControl(ctx, startup, profileContext, appExit) {
1800
3294
  const controller = new AbortController();
1801
3295
  mountManagementRunner(ctx, startup, new DaemonControlRunner({
1802
3296
  run: async () => {
1803
- const { runLocalWebControl } = await import("./local-web-control-DKWtXIkr.mjs");
3297
+ const { runLocalWebControl } = await import("./local-web-control-Dny93N-r.mjs");
1804
3298
  return await runLocalWebControl(startup.control, profile, { signal: controller.signal });
1805
3299
  },
1806
3300
  appExit,
@@ -1812,4 +3306,4 @@ function applyWebControl(ctx, startup, profileContext, appExit) {
1812
3306
  }), controller);
1813
3307
  }
1814
3308
  //#endregion
1815
- export { listKernelGroupMembers as C, sameKernelProcess as D, readProcessStarttime as E, scopeFromInstalledProfile as S, readKernelProcess as T, darwinHostProfileSeatDir as _, createLoaderDumpScheduler as a, readInstalledDshVersion as b, name as c, writeQualificationDump as d, LOCAL_PROTOCOL as f, computeBuildId as g, bindProcessSeat as h, buildChildEnvironment as i, resolveClientEntry as l, bindDarwinKernelSeat as m, DaemonCoordinator as n, encodeLaunchEnvelope as o, LocalScopeError as p, apply as r, inject as s, DaemonControlRunner as t, resolveProfilePackageRoot as u, inspectInstalledProfileScope as v, parseProcessStat as w, readLinuxStarttime as x, installedPackageRootFromEntry as y };
3309
+ export { directProgramResumeCapability as A, closeWin32Handle as B, darwinHostProfileSeatDir as C, materializeBuild as D, installedPackageRootFromEntry as E, listKernelGroupMembers as F, win32PrivateFileStatus as G, openWin32StopSignal as H, parseProcessStat as I, chooseListedSession as J, win32SystemDirectory as K, readKernelProcess as L, scrubProgramResumeEnvironment as M, encodeProgramResumeClear as N, readInstalledDshVersion as O, encodeProgramResumeReport as P, shortSessionId as Q, readProcessStarttime as R, bindProfileKernelSeat as S, inspectInstalledProfileScope as T, waitWin32Handle as U, openWin32Process as V, win32CurrentTokenSid as W, sanitizeSessionSearchInput as X, findSessionMatch as Y, sessionRowMatchesQuery as Z, tspRequested as _, apply as a, bindDarwinKernelSeat as b, createLoaderDumpScheduler as c, name as d, resolveAcpStdioEntry as f, admitProgramResume as g, writeQualificationDump as h, DaemonCoordinator as i, programResumeTarget as j, readLinuxStarttime as k, encodeLaunchEnvelope as l, resolveProfilePackageRoot as m, AcpStdioRunner as n, buildAcpStdioEnvironment as o, resolveClientEntry as p, canonicalFullSessionId as q, DaemonControlRunner as r, buildChildEnvironment as s, ACP_STDIO_SOCKET_ENV as t, inject as u, LOCAL_PROTOCOL as v, ensureInstalledProfileScopeDirectory as w, bindProcessSeat as x, LocalScopeError as y, sameKernelProcess as z };