@xmoon76/dsh-pi-tui 0.5.6 → 0.5.8

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 (90) hide show
  1. package/LICENSE +33 -0
  2. package/README.en.md +103 -814
  3. package/README.md +102 -711
  4. package/cordis.patch.yml +186 -0
  5. package/dist/acp-preferences.d.mts +29 -0
  6. package/dist/acp-preferences.mjs +15 -0
  7. package/dist/{bootstrap-DQ4YPL-7.mjs → bootstrap-CMIjGyuk.mjs} +33515 -7587
  8. package/dist/builtins.mjs +3 -3
  9. package/dist/{client-bootstrap-Cr1JCaF5.mjs → client-bootstrap-BjGPc-DM.mjs} +4637 -492
  10. package/dist/client-extension-loader-probe-BUw7q8bJ.mjs +119 -0
  11. package/dist/command-trust-DChWUamk.mjs +406 -0
  12. package/dist/daemon-launcher-Dult7Jxv.mjs +1932 -0
  13. package/dist/daemon-launcher.d.mts +159 -0
  14. package/dist/daemon-launcher.mjs +2 -0
  15. package/dist/diagnostics-D5jwc-q1.d.mts +11 -0
  16. package/dist/{dist-CIsR7cz4.mjs → dist-BFgC-5tL.mjs} +938 -487
  17. package/dist/entry-control-DjNsE3I0.mjs +190 -0
  18. package/dist/extension/advanced.d.mts +1 -1
  19. package/dist/extension/unstable.d.mts +1 -1
  20. package/dist/extension-config-probe-BDdvutkG.mjs +95 -0
  21. package/dist/extension-config.d.mts +29 -0
  22. package/dist/extension-config.mjs +22 -0
  23. package/dist/{extensions-Bp0L37lP.mjs → extensions-B4uLpSTv.mjs} +1109 -100
  24. package/dist/{extensions-Bte3XOt5.d.mts → extensions-C8eAM0gX.d.mts} +1 -1
  25. package/dist/extensions.d.mts +2 -2
  26. package/dist/extensions.mjs +1 -1
  27. package/dist/{host-bootstrap-DilsvA6f.mjs → host-bootstrap-MVxks641.mjs} +129 -24
  28. package/dist/{host-foundation-probe--5jtvHVe.mjs → host-foundation-probe-DMNTmNrH.mjs} +2 -2
  29. package/dist/host-runtime.d.mts +11 -5
  30. package/dist/host-runtime.mjs +4171 -920
  31. package/dist/index.d.mts +86 -174
  32. package/dist/index.mjs +38087 -9967
  33. package/dist/local-acp-listener-B65J0Bx4.mjs +3115 -0
  34. package/dist/local-client.mjs +1158 -59
  35. package/dist/local-daemon-control-C14q9KnD.mjs +1588 -0
  36. package/dist/local-daemon-control-TCnERL7n.mjs +1424 -0
  37. package/dist/local-discovery-DOSsCh9q.mjs +2883 -0
  38. package/dist/local-discovery-egN4_gsQ.mjs +2 -0
  39. package/dist/local-discovery-uOBfFq5j.mjs +2764 -0
  40. package/dist/local-host.mjs +812 -89
  41. package/dist/local-profile-daemon-admin-BmQSdzT0.mjs +210 -0
  42. package/dist/local-scope-DamiMqPd.mjs +1340 -0
  43. package/dist/{local-transport-BVwFYq_Y.mjs → local-transport-Iwo0mtu3.mjs} +313 -38
  44. package/dist/local-web-control-DMrjwCkl.mjs +454 -0
  45. package/dist/local-workspace-object-D06GL0UO.mjs +248 -0
  46. package/dist/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  47. package/dist/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  48. package/dist/open-CmOBxSjN.mjs +63 -0
  49. package/dist/persisted-setting-probe-DWZLtWoB.mjs +145 -0
  50. package/dist/pi-tui-acp-access-contract-BdLwduU6.mjs +75 -0
  51. package/dist/pi-tui-remote-contribution-Do8ECrUy.mjs +1492 -0
  52. package/dist/pi-tui-terminal-progress-contract-B3RoEzjK.mjs +146 -0
  53. package/dist/preferences.d.mts +17 -0
  54. package/dist/preferences.mjs +20 -0
  55. package/dist/preset-BcWqOtY7.mjs +46 -0
  56. package/dist/profile-preferences-migration-BfUGdPZx.mjs +500 -0
  57. package/dist/profile-preferences-migration-CThz4rHH.mjs +2 -0
  58. package/dist/prompt-sections-DUKmWb8g.mjs +2232 -0
  59. package/dist/prompt-sections-DXmjB58H.mjs +634 -0
  60. package/dist/{public-types-Dgf1bDke.d.mts → public-types-C1YgFtwC.d.mts} +56 -3
  61. package/dist/row-id-DPbyt9Nn.mjs +24 -0
  62. package/dist/{runtime-status-Cj1nFOdS.mjs → runtime-status-v-FTnWcD.mjs} +49 -3
  63. package/dist/schema-BTGYn8_X.d.mts +54 -0
  64. package/dist/schema-qE_P09zJ.mjs +124 -0
  65. package/dist/{session-BKGXyh80.mjs → session-C6tSs86s.mjs} +9672 -7270
  66. package/dist/{session-CPt_U8_f.mjs → session-CstInGIA.mjs} +9674 -7273
  67. package/dist/startup-CarQxWwi.d.mts +213 -0
  68. package/dist/{startup-7BYWuvBU.mjs → startup-EG5UqIcd.mjs} +341 -26
  69. package/dist/startup.d.mts +2 -99
  70. package/dist/startup.mjs +2 -2
  71. package/dist/{terminal-progress-source-DrqQhtT8.mjs → terminal-progress-source-CpfpQO_h.mjs} +2038 -67
  72. package/dist/{pasted-path-range-CMnxuGPx.mjs → transcript-view-C1YtJ49Y.mjs} +11590 -6718
  73. package/dist/{pasted-path-range-r6qzV_tC.mjs → transcript-view-CuJYWkhp.mjs} +12296 -6923
  74. package/dist/version-B9yC7bBk.mjs +83 -0
  75. package/dist/visual-tools.d.mts +1 -1
  76. package/dist/visual-tools.mjs +1 -1
  77. package/dist/web-preferences.d.mts +1 -1
  78. package/dist/{web-roster-CjqnUXNk.mjs → web-roster-Dis7BhrA.mjs} +63 -3
  79. package/generated/dsh-presets/cordis.patch.yml +4 -2
  80. package/generated/dsh-presets/ptc.patch.yml +4 -0
  81. package/generated/dsh-presets/standard.patch.yml +7 -0
  82. package/generated/web-access/cordis.patch.yml +239 -0
  83. package/package.json +217 -170
  84. package/dist/entry-control-DnduyDiw.mjs +0 -92
  85. package/dist/local-discovery-C9VMjc0K.mjs +0 -759
  86. package/dist/local-discovery-CDaQHA_R.mjs +0 -2
  87. package/dist/pi-tui-remote-contribution-B0EQsP0N.mjs +0 -85
  88. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +0 -70
  89. package/dist/pi-tui-terminal-progress-contract-MLXZ-i3t.mjs +0 -905
  90. package/dist/version-a-eF-QER.mjs +0 -80
@@ -0,0 +1,1588 @@
1
+ import { D as sameKernelProcess, S as scopeFromInstalledProfile, T as readKernelProcess, _ as darwinHostProfileSeatDir, h as bindProcessSeat, m as bindDarwinKernelSeat, p as LocalScopeError, v as inspectInstalledProfileScope, x as readLinuxStarttime } from "./daemon-launcher-Dult7Jxv.mjs";
2
+ import { i as parsePiTuiAcpAccessStatus } from "./pi-tui-acp-access-contract-BdLwduU6.mjs";
3
+ import { C as prepareOwnedLaunchdForCurrentInstall, S as launchdServiceMatches, T as uninstallLaunchdUnit, _ as uninstallOwnedProfileUnit, a as inspectHostProcess, b as installLaunchdUnit, c as collectUnitFacts, d as prepareOwnedProfileUnitForCurrentInstall, f as profileIdentityDigest, g as stopOwnedProfileUnit, h as selectRuntimeDir, i as ensureLocalHost, l as inspectOwnedProfileUnit, m as runSystemctl, n as assertRecordedHostKernelIdentityCurrent, o as readLocalRecord, p as queryOwnedProfileUnit, r as authenticateLocalHost, t as assertClientHostCompatible, u as installProfileHostUnit, v as inspectLaunchdService, w as stopLaunchdService, x as launchdLogPaths, y as inspectOwnedLaunchdUnit } from "./local-discovery-uOBfFq5j.mjs";
4
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, readSync, realpathSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import "node:crypto";
7
+ import { spawn } from "node:child_process";
8
+ import "node:net";
9
+ import "@agentclientprotocol/sdk";
10
+ JSON.stringify(["unset"]);
11
+ //#endregion
12
+ //#region src/app/remote-process/local-acp-listener.ts
13
+ /** The logical socket file name inside the 0700 scope directory. */
14
+ const SOCKET_FILE = "acp.sock";
15
+ /** Owner-only private subdirectory (inside the 0700 scope) where the server is
16
+ * actually BOUND before its inode is hard-linked onto the contract path. Node's
17
+ * server.close() unlink always targets this private dir, so it can never delete
18
+ * a foreign inode at the contract path. */
19
+ const PRIVATE_DIR = ".acp-priv";
20
+ /** The trusted, OS-owned sticky parent of the Darwin profile-scoped endpoint. Never
21
+ * `$TMPDIR`, `DSH_HOME` or the user home: those are variable and unbounded. */
22
+ const DARWIN_SOCKET_PARENT = "/private/tmp";
23
+ /** Darwin `sockaddr_un.sun_path` capacity in bytes INCLUDING the trailing NUL. */
24
+ const DARWIN_SUN_PATH_BYTES = 104;
25
+ /** Prefix of the one deterministic Darwin endpoint root per profile scope. */
26
+ const DARWIN_ROOT_PREFIX = "dpt-";
27
+ /** Scope-id hex characters kept in the Darwin root name (the existing 160-bit
28
+ * collision budget the local seats already use). */
29
+ const DARWIN_SCOPE_PREFIX_HEX = 40;
30
+ `${JSON.stringify({
31
+ jsonrpc: "2.0",
32
+ id: null,
33
+ error: {
34
+ code: -32041,
35
+ message: "ACP connection capacity exceeded",
36
+ data: { code: "LOCAL_ACP_CAPACITY_EXCEEDED" }
37
+ }
38
+ })}`;
39
+ /** A startup failure that carries one stable local-ACP classification code. */
40
+ var LocalAcpError = class extends Error {
41
+ /** Stable classification asserted by the Host entry failure record. */
42
+ code;
43
+ constructor(code, message, cause) {
44
+ super(message, cause === void 0 ? void 0 : { cause });
45
+ this.name = "LocalAcpError";
46
+ this.code = code;
47
+ }
48
+ };
49
+ /**
50
+ * Compute the FROZEN Darwin endpoint from the real profile scope id and the
51
+ * current OS uid: `/private/tmp/dpt-<decimal-uid>-<scope40>` holds one 0700 root
52
+ * whose `acp.sock` is the public address and whose `.acp-priv/acp.sock` is the
53
+ * private bind name. No configuration, environment variable or user path can
54
+ * change it, and both names must fit `sun_path[104]` INCLUDING the NUL. The
55
+ * caller creates/admits the root; this function performs no filesystem IO.
56
+ *
57
+ * @param scope - the canonical profile scope (its `scopeId` is a 64-hex SHA-256).
58
+ * @param uid - the current process uid; the root is scoped to this exact uid.
59
+ * @returns the public, root and private bind pathnames.
60
+ * @throws {LocalAcpError} `LOCAL_ACP_SOCKET_PATH_UNSUPPORTED` when a name exceeds
61
+ * the Darwin kernel path capacity.
62
+ */
63
+ function darwinAcpSocketPaths(scope, uid) {
64
+ const privateRoot = join(DARWIN_SOCKET_PARENT, `${DARWIN_ROOT_PREFIX}${String(uid)}-${scope.scopeId.slice(0, DARWIN_SCOPE_PREFIX_HEX)}`);
65
+ const publicPath = join(privateRoot, SOCKET_FILE);
66
+ const privateBindPath = join(privateRoot, PRIVATE_DIR, SOCKET_FILE);
67
+ if (Buffer.byteLength(publicPath, "utf8") + 1 > DARWIN_SUN_PATH_BYTES || Buffer.byteLength(privateBindPath, "utf8") + 1 > DARWIN_SUN_PATH_BYTES) throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the Darwin endpoint exceeds the kernel sun_path byte limit");
68
+ return {
69
+ publicPath,
70
+ privateRoot,
71
+ privateBindPath
72
+ };
73
+ }
74
+ //#endregion
75
+ //#region src/app/remote-process/local-acp-status.ts
76
+ /** The one Owner-only authenticated route of the live ACP status observation. */
77
+ const LOCAL_ACP_STATUS_ROUTE = "/api/pi-tui.acp-status";
78
+ /** Hard cap on the status response body; the DTO is a few hundred bytes. */
79
+ const LOCAL_ACP_STATUS_MAX_BYTES = 1024;
80
+ /** Bound on the one observation request. */
81
+ const LOCAL_ACP_STATUS_TIMEOUT_MS = 3e3;
82
+ /** Drain the body within the byte cap; an oversized/unreadable body is absent. */
83
+ async function readBoundedBody(response) {
84
+ if (response.body === null) return "";
85
+ const reader = response.body.getReader();
86
+ const chunks = [];
87
+ let total = 0;
88
+ try {
89
+ for (;;) {
90
+ const { done, value } = await reader.read();
91
+ if (done) break;
92
+ total += value.byteLength;
93
+ if (total > LOCAL_ACP_STATUS_MAX_BYTES) {
94
+ await reader.cancel();
95
+ return;
96
+ }
97
+ chunks.push(value);
98
+ }
99
+ } finally {
100
+ reader.releaseLock();
101
+ }
102
+ return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8");
103
+ }
104
+ /** Cancel an unread body without observing it. */
105
+ async function discard(response) {
106
+ try {
107
+ await response.body?.cancel();
108
+ } catch {}
109
+ }
110
+ /**
111
+ * Observe the running Host's live ACP listener status through the authenticated
112
+ * read-only route. This is the ONLY headless observation; it never creates a
113
+ * controller, never calls `setEnabled`, and never caches the result.
114
+ *
115
+ * Every external-boundary failure category is `undefined` (the caller's
116
+ * `unavailable`), including an instance id that does not match the Host the
117
+ * Cookie was issued for: a response from a replaced/foreign Host can never be
118
+ * attributed to this observation.
119
+ *
120
+ * @param verified - the already authenticated Host record and in-memory cookie.
121
+ * @returns the validated live listener status, or `undefined` when unprovable.
122
+ */
123
+ async function observeAuthenticatedLocalAcpStatus(verified) {
124
+ const request = {
125
+ method: "GET",
126
+ headers: { cookie: verified.cookie },
127
+ redirect: "manual",
128
+ cache: "no-store",
129
+ signal: AbortSignal.timeout(LOCAL_ACP_STATUS_TIMEOUT_MS)
130
+ };
131
+ let response;
132
+ try {
133
+ response = await fetch(`${verified.record.origin}${LOCAL_ACP_STATUS_ROUTE}`, request);
134
+ } catch {
135
+ return;
136
+ }
137
+ if (response.status !== 200) {
138
+ await discard(response);
139
+ return;
140
+ }
141
+ const contentType = response.headers.get("content-type") ?? "";
142
+ const cacheControl = response.headers.get("cache-control") ?? "";
143
+ if (!/^application\/json\b/iu.test(contentType) || !/\bno-store\b/iu.test(cacheControl)) {
144
+ await discard(response);
145
+ return;
146
+ }
147
+ let text;
148
+ try {
149
+ const body = await readBoundedBody(response);
150
+ if (body === void 0) return void 0;
151
+ text = body;
152
+ } catch {
153
+ return;
154
+ }
155
+ let value;
156
+ try {
157
+ value = JSON.parse(text);
158
+ } catch {
159
+ return;
160
+ }
161
+ if (typeof value !== "object" || value === null) return void 0;
162
+ const record = value;
163
+ if (Object.keys(record).length !== 3 || record.schema !== 1 || typeof record.instanceId !== "string" || record.instanceId !== verified.identity.instanceId) return;
164
+ try {
165
+ return parsePiTuiAcpAccessStatus(record.status);
166
+ } catch {
167
+ return;
168
+ }
169
+ }
170
+ //#endregion
171
+ //#region src/app/remote-process/local-daemon-control.ts
172
+ /**
173
+ * The M6-2C daemon management control plane.
174
+ *
175
+ * This is the ONE module that turns a typed `DaemonControlIntent` into a real
176
+ * local OS observation or an explicit supervision transition for ONE official
177
+ * Profile. It owns no Host business object: Host readiness is always the
178
+ * existing authenticated `/connect` Cookie + identity echo + fresh kernel
179
+ * identity handshake (Linux `/proc` starttime, macOS Darwin schema 2), and a
180
+ * Host stop remains the existing `runProfile` shutdown owner reached either
181
+ * through the verified profile unit's manager SIGTERM, a verified user-level
182
+ * launchd job's `bootout`, or a single verified-PID POSIX SIGTERM when the
183
+ * authenticated Host is independent.
184
+ *
185
+ * `status` and `logs` are strictly read-only: they never create the profile run
186
+ * directory, never write a service definition, never start a Host and never
187
+ * touch a Session. The five mutating verbs (start, stop, restart, install and
188
+ * uninstall) are serialized by one short-lived profile-scoped admin seat: Linux
189
+ * holds the abstract-socket name, macOS holds the Darwin `O_EXLOCK` `admin` seat
190
+ * file beside the Host singleton seat. The kernel releases it when the command
191
+ * dies, so there is no persistent lock file or second state machine.
192
+ *
193
+ * @module app/remote-process/local-daemon-control
194
+ */
195
+ /** The fixed exit class of every stable code. */
196
+ const EXIT_CODE = {
197
+ UNSUPPORTED_PLATFORM: 3,
198
+ IDENTITY_OR_OWNERSHIP_REFUSED: 3,
199
+ MANAGER_OR_OS_FAILURE: 4,
200
+ LOG_SOURCE_UNAVAILABLE: 4,
201
+ DAEMON_CONTROL_BUSY: 5,
202
+ TRANSITION_UNCERTAIN: 5
203
+ };
204
+ /** A management failure carrying the stable code and exit class. */
205
+ var DaemonControlError = class extends Error {
206
+ code;
207
+ exitCode;
208
+ reason;
209
+ constructor(code, reason, cause) {
210
+ super(reason, cause === void 0 ? void 0 : { cause });
211
+ this.name = "DaemonControlError";
212
+ this.code = code;
213
+ this.exitCode = EXIT_CODE[code];
214
+ this.reason = reason;
215
+ }
216
+ };
217
+ /** The fixed one-line error format; never a raw Error message or argv. */
218
+ function formatDaemonControlError(error) {
219
+ return `dsh-pi-tui daemon: ${error.code}: ${sanitizeReason(error.reason)}\n`;
220
+ }
221
+ /** Visible risk reminder printed beside log output. */
222
+ const LOG_SANITIZATION_NOTICE = "dsh-pi-tui daemon: note: log output is best-effort sanitized; review it before sharing\n";
223
+ /** The fixed running-work warning every mutating verb prints on success. */
224
+ const RUNNING_WORK_NOTICE = "dsh-pi-tui daemon: note: stopping or restarting the Host may interrupt a running Session, Job or Interaction; unsettled writes are not replayed automatically\n";
225
+ /** The admin seat prefix; the kernel releases the abstract name on process death. */
226
+ const ADMIN_SEAT_PREFIX = "\0dsh-pi-tui-admin-";
227
+ /** Bound on one journalctl invocation. */
228
+ const JOURNALCTL_TIMEOUT_MS = 1e4;
229
+ /** Hard cap on captured journal output. */
230
+ const JOURNAL_MAX_OUTPUT_BYTES = 262144;
231
+ /** Bound on one scope host.log tail read (from the end of the file). */
232
+ const HOST_LOG_MAX_BYTES = 262144;
233
+ /** Bound on one displayed log line. */
234
+ const MAX_LOG_LINE_LENGTH = 2e3;
235
+ /** The fixed journal executable. */
236
+ const JOURNALCTL = "journalctl";
237
+ /** Stable truncation marker for bounded log reads. */
238
+ const LOG_TRUNCATION_MARKER = "[dsh-pi-tui daemon: earlier log output truncated]";
239
+ /** Replace absolute paths and control characters in a human reason. */
240
+ function sanitizeReason(text) {
241
+ return (text.split(/\r?\n/u).map((part) => part.trim()).find((part) => part !== "") ?? "").replace(/\/[^\s"']+/gu, "<path>").replace(/https?:\/\/[^\s"']+/giu, "<url>").replace(/[\u0000-\u001f\u007f]/gu, "").slice(0, 200);
242
+ }
243
+ /** Map a lower-level stable failure onto the management error taxonomy. */
244
+ function toDaemonControlError(error) {
245
+ if (error instanceof DaemonControlError) return error;
246
+ if (error instanceof LocalScopeError) switch (error.code) {
247
+ case "B1_PLATFORM_UNSUPPORTED": return new DaemonControlError("UNSUPPORTED_PLATFORM", "this daemon command requires Linux or macOS");
248
+ case "HOST_MANAGER_UNIT_CONFLICT":
249
+ case "HOST_IDENTITY_MISMATCH":
250
+ case "HOST_PROTOCOL_INCOMPATIBLE":
251
+ case "HOST_BUILD_INCOMPATIBLE":
252
+ case "HOST_AUTH_FAILED":
253
+ case "SCOPE_DIRECTORY_UNSAFE":
254
+ case "LOCAL_FILE_UNSAFE":
255
+ case "PROCESS_STARTTIME_UNAVAILABLE": return new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", error.message, error);
256
+ case "HOST_STOP_TIMEOUT": return new DaemonControlError("TRANSITION_UNCERTAIN", error.message, error);
257
+ case "HOST_START_TIMEOUT": return afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", error.message, error), "Host start");
258
+ case "DAEMON_CONTROL_BUSY": return new DaemonControlError("DAEMON_CONTROL_BUSY", "another daemon control operation is already running for this profile", error);
259
+ case "HOST_UNRESPONSIVE": return new DaemonControlError("MANAGER_OR_OS_FAILURE", error.message, error);
260
+ default: return new DaemonControlError("MANAGER_OR_OS_FAILURE", error.message, error);
261
+ }
262
+ return new DaemonControlError("MANAGER_OR_OS_FAILURE", "an unexpected local management failure occurred", error);
263
+ }
264
+ /** Add recovery context only to a completed operation's failed confirmation. */
265
+ function afterCommittedAction(failure, action) {
266
+ return new DaemonControlError(failure.code, `${action} may already be committed; final verification failed. Run daemon status before retrying. ${failure.reason}`, failure);
267
+ }
268
+ /** Throw when the supervisor is shutting down and the operation must settle. */
269
+ function assertNotAborted(signal) {
270
+ if (signal !== void 0 && signal.aborted) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the management operation was cancelled by supervisor shutdown");
271
+ }
272
+ /** The effective platform/uid inputs. */
273
+ function platformOf(deps) {
274
+ return deps.platform ?? process.platform;
275
+ }
276
+ function uidOf(deps) {
277
+ const uid = deps.uid ?? (typeof process.getuid === "function" ? process.getuid() : void 0);
278
+ if (uid === void 0) throw new DaemonControlError("UNSUPPORTED_PLATFORM", "this daemon command requires a local user identity");
279
+ return uid;
280
+ }
281
+ /** Compute the read-only scope; no directory is created. */
282
+ function inspectScope(profile, deps) {
283
+ const platform = platformOf(deps);
284
+ if (platform !== "linux" && platform !== "darwin") throw new DaemonControlError("UNSUPPORTED_PLATFORM", "this daemon command requires Linux or macOS");
285
+ try {
286
+ return inspectInstalledProfileScope({
287
+ dshHome: profile.home,
288
+ profileDir: profile.dir,
289
+ packageRoot: profile.packageRoot,
290
+ dshVersion: profile.dshVersion
291
+ });
292
+ } catch (error) {
293
+ throw toDaemonControlError(error);
294
+ }
295
+ }
296
+ /** Resolve the fixed runtime dir for the current user. */
297
+ function runtimeDirOf(deps) {
298
+ return selectRuntimeDir(uidOf(deps));
299
+ }
300
+ /** The narrow local-Host-manager seams this command passes through. */
301
+ function managerDepsOf(deps) {
302
+ const unitDir = deps.unitDir;
303
+ return {
304
+ ...deps.systemctl === void 0 ? {} : { systemctl: deps.systemctl },
305
+ ...unitDir === void 0 ? {} : { unitDir: () => unitDir }
306
+ };
307
+ }
308
+ /** The Darwin launchd adapter inputs; production uses the OS account home and
309
+ * the real `/bin/launchctl`. */
310
+ function launchdDepsOf(deps) {
311
+ return {
312
+ uid: uidOf(deps),
313
+ ...deps.darwinAccountHome === void 0 ? {} : { accountHome: deps.darwinAccountHome },
314
+ ...deps.launchctl === void 0 ? {} : { launchctl: deps.launchctl }
315
+ };
316
+ }
317
+ /** Collect the validated launchd facts for one installed profile. */
318
+ function launchdFactsOf(scope, profile) {
319
+ return {
320
+ ...collectUnitFacts({
321
+ scope,
322
+ hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
323
+ dshAnchor: profile.installAnchor,
324
+ profile: profile.name
325
+ }),
326
+ scopeDir: scope.dir,
327
+ profileIdentity: profileIdentityDigest(scope.profileRealpath)
328
+ };
329
+ }
330
+ /** Map one actual launchd job state onto the stable status vocabulary. */
331
+ function launchdUnitState(state) {
332
+ switch (state) {
333
+ case "running": return "running";
334
+ case "not running": return "not-running";
335
+ case "spawn scheduled": return "spawn-scheduled";
336
+ default: return "unknown";
337
+ }
338
+ }
339
+ /** The read-only migration preflight for an explicit Darwin CLI start/restart. */
340
+ function inspectDarwinLaunchdMigration(snapshot, deps) {
341
+ const { launchdUnit, launchdFacts } = snapshot;
342
+ if (launchdUnit === void 0 || launchdFacts === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd plist facts are unavailable; refusing an unverified migration");
343
+ try {
344
+ return prepareOwnedLaunchdForCurrentInstall(launchdFacts, launchdUnit, launchdDepsOf(deps), "inspect").plan;
345
+ } catch (error) {
346
+ throw toDaemonControlError(error);
347
+ }
348
+ }
349
+ /**
350
+ * Apply the ONE bounded generated-field migration after the old Host kernel
351
+ * identity and the loaded job have been proven gone. Only an explicit CLI
352
+ * start/restart reaches here; an ordinary TUI cold start never does.
353
+ */
354
+ function applyDarwinLaunchdMigration(snapshot, deps) {
355
+ const { launchdUnit, launchdFacts } = snapshot;
356
+ if (launchdUnit === void 0 || launchdFacts === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd plist facts are unavailable; refusing an unverified migration");
357
+ try {
358
+ return prepareOwnedLaunchdForCurrentInstall(launchdFacts, launchdUnit, launchdDepsOf(deps), "apply").unit;
359
+ } catch (error) {
360
+ throw afterCommittedAction(toDaemonControlError(error), "launchd plist migration");
361
+ }
362
+ }
363
+ /**
364
+ * Read-only snapshot; `status`, pre-flight checks and `logs` consume it.
365
+ *
366
+ * The installed unit fact is the ONLY manager-IO admission: with no unit file
367
+ * (or no user unit directory) no `systemctl` invocation is made at all, so a
368
+ * missing/broken user manager cannot affect an independent basic Host. With a
369
+ * unit, exactly one `systemctl show` of that unit decides `user-manager` and
370
+ * the unit state. The Host's own registry/authentication chain is always read,
371
+ * even after a unit-identity refusal, so `status` can report a real ready Host
372
+ * beside a foreign unit while still exiting nonzero.
373
+ */
374
+ async function readSnapshot(profile, deps, scope) {
375
+ const platform = platformOf(deps);
376
+ let unit;
377
+ let unitState = "not-found";
378
+ /** The manager's raw ActiveState; `unitState` is the coarse presentation. */
379
+ let unitActiveState = "";
380
+ let unitMainPid = 0;
381
+ let userManager = "not-checked";
382
+ let unitInspectionFailure;
383
+ let unitQueryFailure;
384
+ let launchdUnit;
385
+ let launchdService;
386
+ let launchdFacts;
387
+ let launchdInspectionFailure;
388
+ let launchdQueryFailure;
389
+ if (platform === "linux") {
390
+ const systemctl = deps.systemctl ?? runSystemctl;
391
+ const runtimeDir = runtimeDirOf(deps);
392
+ try {
393
+ const inspected = inspectOwnedProfileUnit(scope, profile.name, deps.unitDir);
394
+ if (inspected.kind === "owned") {
395
+ unit = inspected;
396
+ unitInspectionFailure = void 0;
397
+ try {
398
+ const state = await queryOwnedProfileUnit(inspected, runtimeDir, systemctl);
399
+ userManager = "available";
400
+ unitMainPid = state.mainPid;
401
+ unitActiveState = state.loadState === "not-found" ? "" : state.activeState;
402
+ unitState = state.loadState === "not-found" ? "not-found" : state.activeState === "active" ? "active" : state.activeState === "inactive" || state.activeState === "failed" ? "inactive" : "unknown";
403
+ } catch (error) {
404
+ userManager = "error";
405
+ unitQueryFailure = toDaemonControlError(error);
406
+ unitState = "unknown";
407
+ }
408
+ }
409
+ } catch (error) {
410
+ unitInspectionFailure = toDaemonControlError(error);
411
+ unitState = "unknown";
412
+ }
413
+ } else if (platform === "darwin") try {
414
+ launchdFacts = launchdFactsOf(scope, profile);
415
+ const launchdDeps = launchdDepsOf(deps);
416
+ const inspected = inspectOwnedLaunchdUnit(launchdFacts, launchdDeps);
417
+ if (inspected.kind === "owned") {
418
+ launchdUnit = inspected.unit;
419
+ try {
420
+ launchdService = await inspectLaunchdService(inspected.unit, launchdDeps);
421
+ userManager = "available";
422
+ if (launchdService.kind === "not-loaded") unitState = "not-found";
423
+ else if (launchdService.kind === "loaded") {
424
+ const service = launchdService.service;
425
+ unitActiveState = service.state;
426
+ unitState = launchdUnitState(service.state);
427
+ unitMainPid = service.pid ?? 0;
428
+ if (!launchdServiceMatches(launchdFacts, inspected.unit, service)) launchdQueryFailure = new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the loaded launchd job does not match the installed profile plist");
429
+ } else {
430
+ userManager = "error";
431
+ unitState = "unknown";
432
+ launchdQueryFailure = new DaemonControlError("MANAGER_OR_OS_FAILURE", "the loaded launchd job state is not recognizable");
433
+ }
434
+ } catch (error) {
435
+ userManager = "error";
436
+ unitState = "unknown";
437
+ launchdQueryFailure = toDaemonControlError(error);
438
+ }
439
+ }
440
+ } catch (error) {
441
+ launchdInspectionFailure = toDaemonControlError(error);
442
+ unitState = "unknown";
443
+ }
444
+ let failure = unitInspectionFailure ?? unitQueryFailure ?? launchdInspectionFailure ?? launchdQueryFailure;
445
+ let exitCode = failure?.exitCode ?? 0;
446
+ const readRecord = deps.readRecord ?? readLocalRecord;
447
+ const inspectProcess = deps.inspectProcess ?? inspectHostProcess;
448
+ let host = "stopped";
449
+ let manager = "unmanaged";
450
+ let compatibility = "none";
451
+ let authenticated;
452
+ let hostAuthenticationFailed = false;
453
+ let hostCompatibilityFailed = false;
454
+ let record;
455
+ try {
456
+ record = readRecord(scope);
457
+ } catch (error) {
458
+ if (failure === void 0) {
459
+ failure = toDaemonControlError(error);
460
+ exitCode = failure.exitCode;
461
+ }
462
+ }
463
+ let processAlive = false;
464
+ if (record !== void 0) try {
465
+ processAlive = inspectProcess(record) === "alive";
466
+ } catch (error) {
467
+ if (failure === void 0) {
468
+ failure = toDaemonControlError(error);
469
+ exitCode = failure.exitCode;
470
+ }
471
+ }
472
+ if (processAlive && record !== void 0) {
473
+ let compatibilityFailure;
474
+ try {
475
+ assertClientHostCompatible(record, scope);
476
+ compatibility = record.buildId === scope.buildId ? "compatible" : "other-build";
477
+ } catch (error) {
478
+ host = "incompatible";
479
+ compatibility = "incompatible";
480
+ hostCompatibilityFailed = true;
481
+ compatibilityFailure = toDaemonControlError(error);
482
+ if (failure === void 0) {
483
+ failure = compatibilityFailure;
484
+ exitCode = failure.exitCode;
485
+ }
486
+ }
487
+ if (compatibilityFailure === void 0) try {
488
+ authenticated = await (deps.authenticate ?? authenticateLocalHost)(record, scope);
489
+ host = "ready";
490
+ } catch (error) {
491
+ const mapped = toDaemonControlError(error);
492
+ host = "unresponsive";
493
+ hostAuthenticationFailed = true;
494
+ if (failure === void 0) {
495
+ failure = mapped;
496
+ exitCode = mapped.exitCode;
497
+ }
498
+ }
499
+ }
500
+ if (authenticated !== void 0 && record !== void 0) {
501
+ if (platform === "darwin") {
502
+ if (launchdUnit === void 0) manager = "process";
503
+ else if (launchdInspectionFailure !== void 0 || launchdQueryFailure !== void 0 || launchdService === void 0) manager = "unmanaged";
504
+ else if (launchdService.kind === "loaded") {
505
+ const service = launchdService.service;
506
+ if (service.state === "running") {
507
+ if (service.pid === void 0) {
508
+ manager = "unmanaged";
509
+ if (failure === void 0) {
510
+ failure = new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job reports running without a PID");
511
+ exitCode = failure.exitCode;
512
+ }
513
+ } else if (service.pid === record.hostPid) manager = "launchd";
514
+ else {
515
+ manager = "process";
516
+ if (failure === void 0) {
517
+ failure = new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the launchd job PID is not the authenticated Host; use launchctl for this custom service");
518
+ exitCode = failure.exitCode;
519
+ }
520
+ }
521
+ } else if (service.state === "spawn scheduled") {
522
+ manager = "unmanaged";
523
+ if (failure === void 0) {
524
+ failure = new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job is still starting beside a live Host");
525
+ exitCode = failure.exitCode;
526
+ }
527
+ } else if (service.state === "not running") manager = "process";
528
+ else {
529
+ manager = "unmanaged";
530
+ if (failure === void 0) {
531
+ failure = new DaemonControlError("TRANSITION_UNCERTAIN", `the launchd job is in an unconfirmed state (${service.state === "" ? "unknown" : service.state})`);
532
+ exitCode = failure.exitCode;
533
+ }
534
+ }
535
+ } else manager = "process";
536
+ } else {
537
+ const loaded = unit !== void 0 && unitState !== "not-found";
538
+ const running = unitActiveState === "active" || unitActiveState === "activating";
539
+ const ended = unitActiveState === "inactive" || unitActiveState === "failed";
540
+ if (unitInspectionFailure !== void 0 || unitQueryFailure !== void 0) manager = "unmanaged";
541
+ else if (loaded && running) {
542
+ if (unitMainPid === record.hostPid) manager = "systemd";
543
+ else {
544
+ manager = "process";
545
+ if (failure === void 0) {
546
+ failure = new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the unit MainPID is not the authenticated Host; use systemctl --user for this custom service");
547
+ exitCode = failure.exitCode;
548
+ }
549
+ }
550
+ } else if (loaded && !ended) {
551
+ manager = "unmanaged";
552
+ if (failure === void 0) {
553
+ failure = new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState})`);
554
+ exitCode = failure.exitCode;
555
+ }
556
+ } else manager = "process";
557
+ }
558
+ } else if (record === void 0 || !processAlive) {
559
+ if (platform === "darwin") {
560
+ if (launchdUnit !== void 0 && launchdService?.kind === "loaded") {
561
+ const state = launchdService.service.state;
562
+ if (state === "running" || state === "spawn scheduled") host = "starting";
563
+ else if (state === "not running") host = "stopped";
564
+ else {
565
+ host = "unknown";
566
+ if (failure === void 0) {
567
+ failure = new DaemonControlError("TRANSITION_UNCERTAIN", `the launchd job is in an unconfirmed state (${state === "" ? "unknown" : state})`);
568
+ exitCode = failure.exitCode;
569
+ }
570
+ }
571
+ }
572
+ } else {
573
+ const loaded = unit !== void 0 && unitState !== "not-found";
574
+ if (loaded && (unitActiveState === "active" || unitActiveState === "activating")) host = "starting";
575
+ else if (loaded && unitActiveState !== "inactive" && unitActiveState !== "failed") {
576
+ host = "unknown";
577
+ if (failure === void 0) {
578
+ failure = new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState})`);
579
+ exitCode = failure.exitCode;
580
+ }
581
+ }
582
+ }
583
+ }
584
+ if (failure !== void 0 && host === "stopped") host = "unknown";
585
+ if (failure === void 0 && authenticated !== void 0 && record !== void 0) compatibility = record.buildId === scope.buildId ? "compatible" : "other-build";
586
+ else if (failure === void 0 && unit !== void 0 && unitState !== "not-found" && unit.installBuild !== scope.buildId) compatibility = "other-build";
587
+ else if (failure === void 0 && launchdUnit !== void 0 && launchdUnit.installBuild !== scope.buildId) compatibility = "other-build";
588
+ if ((unitQueryFailure !== void 0 || launchdQueryFailure !== void 0) && compatibility === "none") compatibility = "unknown";
589
+ return {
590
+ scope,
591
+ unit,
592
+ launchdUnit,
593
+ launchdService,
594
+ launchdFacts,
595
+ launchdInspectionFailure,
596
+ launchdQueryFailure,
597
+ userManager,
598
+ unitInspectionFailure,
599
+ unitQueryFailure,
600
+ unitState,
601
+ unitActiveState,
602
+ unitMainPid,
603
+ record,
604
+ processAlive,
605
+ authenticated,
606
+ hostAuthenticationFailed,
607
+ hostCompatibilityFailed,
608
+ status: {
609
+ profile: profile.name,
610
+ manager,
611
+ userManager,
612
+ host,
613
+ unit: platform === "darwin" ? launchdUnit === void 0 ? "none" : launchdUnit.label : unit === void 0 ? "none" : unit.unitName,
614
+ unitState,
615
+ compatibility,
616
+ ...processAlive && record !== void 0 ? { pid: record.hostPid } : {},
617
+ ...processAlive && record !== void 0 ? { instance: record.instanceId.slice(0, 8) } : {}
618
+ },
619
+ exitCode,
620
+ failure
621
+ };
622
+ }
623
+ /** The stable `key=value` status block (no secret or private path). */
624
+ function formatDaemonStatus(status) {
625
+ const lines = [
626
+ `profile=${status.profile.replace(/[\u0000-\u001f\u007f]/gu, "")}`,
627
+ `manager=${status.manager}`,
628
+ `user-manager=${status.userManager}`,
629
+ `host=${status.host}`,
630
+ `unit=${status.unit}`,
631
+ `unit-state=${status.unitState}`,
632
+ `compatibility=${status.compatibility}`
633
+ ];
634
+ if (status.pid !== void 0) lines.push(`pid=${String(status.pid)}`);
635
+ if (status.instance !== void 0) lines.push(`instance=${status.instance}`);
636
+ if (status.acp !== void 0) lines.push(`acp=${status.acp}`);
637
+ if (status.acpSocket !== void 0) lines.push(`acp-socket=${status.acpSocket}`);
638
+ return `${lines.join("\n")}\n`;
639
+ }
640
+ /**
641
+ * Acquire the ONE profile-scoped admin seat for a mutating verb. The seat is
642
+ * held for exactly the lifetime of THIS command's operation: two concurrently
643
+ * running management commands of the same Profile cannot interleave, and the
644
+ * kernel releases the claim when the process exits. Linux keeps its abstract
645
+ * socket name; Darwin claims the existing `admin` `O_EXLOCK` file beside the
646
+ * Host singleton seat. There is no persistent lock file and no in-memory shadow
647
+ * of OS operations — a command that dies with the process releases the seat,
648
+ * and the next command re-reads the real systemd/Host state.
649
+ */
650
+ async function withAdminSeat(scope, deps, operation) {
651
+ let seat;
652
+ try {
653
+ seat = platformOf(deps) === "linux" ? await bindProcessSeat(`${ADMIN_SEAT_PREFIX}${scope.scopeId.slice(0, 40)}`, "DAEMON_CONTROL_BUSY") : await bindDarwinKernelSeat(darwinHostProfileSeatDir(scope.scopeId, deps.darwinAccountHome), scope.scopeId, "admin", "DAEMON_CONTROL_BUSY");
654
+ } catch (error) {
655
+ throw toDaemonControlError(error);
656
+ }
657
+ try {
658
+ return await operation();
659
+ } finally {
660
+ await seat.close();
661
+ }
662
+ }
663
+ /** A live Host authentication or compatibility failure is a diagnosis, not a
664
+ * unit-ownership verdict. A verified current-Profile service remains
665
+ * manageable through the manager; every other snapshot failure keeps its
666
+ * normal admission. The product never auto-recovers — this only permits an
667
+ * explicit user command. */
668
+ function verifiedUnitManagementAdmitted(snapshot) {
669
+ return (snapshot.hostAuthenticationFailed || snapshot.hostCompatibilityFailed) && snapshot.unit !== void 0 && snapshot.userManager === "available";
670
+ }
671
+ /** The same admission for a verified launchd job whose real PID is the live
672
+ * Host record (or whose job state proves no process is running). */
673
+ function verifiedLaunchdManagementAdmitted(snapshot) {
674
+ const { launchdUnit, launchdFacts, launchdService, record, processAlive } = snapshot;
675
+ if (launchdUnit === void 0 || launchdFacts === void 0 || launchdService?.kind !== "loaded") return false;
676
+ if (!launchdServiceMatches(launchdFacts, launchdUnit, launchdService.service)) return false;
677
+ if (!processAlive || record === void 0) return true;
678
+ return launchdService.service.pid !== void 0 && launchdService.service.pid === record.hostPid;
679
+ }
680
+ /** A stable local error for an unknown Host state. */
681
+ function refuseHostState(status) {
682
+ if (status.host === "incompatible") return new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the live Host uses an incompatible protocol or DSH runtime");
683
+ if (status.host === "unresponsive") return new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the live Host could not prove its authenticated identity");
684
+ return new DaemonControlError("TRANSITION_UNCERTAIN", `the Host is ${status.host}; refusing to change supervision`);
685
+ }
686
+ /** The bounded post-stop wait: the old process identity must actually
687
+ * disappear. Linux keeps its frozen `/proc` starttime proof; Darwin requires
688
+ * the recorded schema-2 kernel identity to become `gone`/`different`. An
689
+ * `unknown` kernel read is uncertainty and never proves a stop. */
690
+ async function waitForHostStopped(record, mainPid, deps) {
691
+ const now = deps.now ?? Date.now;
692
+ const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
693
+ const deadline = now() + (deps.stopTimeoutMs ?? 2e4);
694
+ if (platformOf(deps) === "darwin") {
695
+ if (record === void 0 || record.schema !== 2) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host kernel identity is unavailable for the stop proof");
696
+ const readKernel = deps.readKernel ?? readKernelProcess;
697
+ for (;;) {
698
+ const classification = sameKernelProcess(record.hostKernelIdentity, readKernel(record.hostPid));
699
+ if (classification === "gone" || classification === "different") return;
700
+ if (now() >= deadline) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the old Host process did not exit within the bounded window");
701
+ await sleep(100);
702
+ }
703
+ }
704
+ const readStarttime = deps.readStarttime ?? ((pid) => {
705
+ try {
706
+ return readLinuxStarttime(pid);
707
+ } catch {
708
+ return;
709
+ }
710
+ });
711
+ for (;;) {
712
+ const targetPid = record?.hostPid ?? mainPid;
713
+ const observed = targetPid === 0 ? void 0 : readStarttime(targetPid);
714
+ const starttimeGone = targetPid === 0 || observed === void 0 || record !== void 0 && (record.schema !== 1 || observed !== record.hostStarttime);
715
+ const recordGone = record === void 0 || inspectHostProcess(record) === "dead";
716
+ if (starttimeGone && recordGone) return;
717
+ if (now() >= deadline) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the old Host process did not exit within the bounded window");
718
+ await sleep(100);
719
+ }
720
+ }
721
+ /** Verify a live independent Host process really is this product Host entry. */
722
+ function assertProcessHostOwnership(record, deps) {
723
+ const cmdline = (deps.readCmdline ?? ((pid) => {
724
+ try {
725
+ return readFileString(`/proc/${String(pid)}/cmdline`);
726
+ } catch {
727
+ return;
728
+ }
729
+ }))(record.hostPid);
730
+ if (cmdline === void 0 || cmdline === "") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host process command line is unavailable");
731
+ const entry = cmdline.split("\0").filter((part) => part !== "")[1];
732
+ if (entry === void 0 || !entry.endsWith("/dist/local-host.mjs")) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the live process is not the product Host entry");
733
+ let realEntry;
734
+ try {
735
+ realEntry = realpathSync(entry);
736
+ } catch {
737
+ throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the live Host entry is not readable");
738
+ }
739
+ if (!lstatSync(realEntry).isFile()) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the live Host entry is not a product file");
740
+ let manifest;
741
+ try {
742
+ manifest = JSON.parse(readFileSync(join(dirname(dirname(entry)), "package.json"), "utf8"));
743
+ } catch {
744
+ throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the live Host entry has no readable package identity");
745
+ }
746
+ if (manifest === null || typeof manifest !== "object" || manifest.name !== "@xmoon76/dsh-pi-tui") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the live Host entry is not @xmoon76/dsh-pi-tui");
747
+ }
748
+ /**
749
+ * Verify a live independent Darwin Host really is the recorded kernel process
750
+ * before one SIGTERM. The registry schema, the authenticated instance and a
751
+ * FRESH kernel read must all agree; the read is repeated immediately before the
752
+ * signal so a pid that exited/was reused between the handshake and the signal
753
+ * is refused with zero signal. `unknown` is never a kill permit.
754
+ */
755
+ function assertDarwinHostOwnership(record, authenticated, deps) {
756
+ if (record.schema !== 2) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host registry is not a macOS kernel identity");
757
+ if (authenticated.record.instanceId !== record.instanceId || authenticated.record.hostPid !== record.hostPid) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the authenticated Host is not the recorded instance");
758
+ const readKernel = deps.readKernel ?? readKernelProcess;
759
+ try {
760
+ assertRecordedHostKernelIdentityCurrent(record, readKernel);
761
+ } catch (error) {
762
+ throw toDaemonControlError(error);
763
+ }
764
+ if (sameKernelProcess(record.hostKernelIdentity, readKernel(record.hostPid)) !== "same") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host kernel identity changed before the signal");
765
+ }
766
+ /** Bounded read-to-EOF for procfs text files: `/proc` entries report
767
+ * `st_size = 0` even when the content is readable, so the length must come
768
+ * from reading until EOF under an explicit byte cap, never from `fstat.size`. */
769
+ function readFileString(path) {
770
+ const fd = openSync(path, constants.O_RDONLY);
771
+ try {
772
+ const chunks = [];
773
+ let total = 0;
774
+ for (;;) {
775
+ const chunk = Buffer.alloc(4096);
776
+ const read = readSync(fd, chunk, 0, chunk.length, null);
777
+ if (read <= 0) break;
778
+ total += read;
779
+ if (total > 65536) throw new Error("unexpected process command line size");
780
+ chunks.push(read === chunk.length ? chunk : chunk.subarray(0, read));
781
+ }
782
+ return Buffer.concat(chunks).toString("utf8");
783
+ } finally {
784
+ closeSync(fd);
785
+ }
786
+ }
787
+ /** Stop one live independent authenticated Host through exactly one verified
788
+ * POSIX SIGTERM (Linux procfs identity or Darwin schema-2 kernel identity). */
789
+ async function stopIndependentHost(snapshot, deps) {
790
+ const record = snapshot.record;
791
+ if (record === void 0) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host registry disappeared before the stop");
792
+ const authenticate = deps.authenticate ?? authenticateLocalHost;
793
+ let authenticated;
794
+ try {
795
+ authenticated = await authenticate(record, snapshot.scope);
796
+ } catch (error) {
797
+ throw toDaemonControlError(error);
798
+ }
799
+ if (platformOf(deps) === "darwin") assertDarwinHostOwnership(record, authenticated, deps);
800
+ else {
801
+ assertProcessHostOwnership(record, deps);
802
+ const readStarttime = deps.readStarttime ?? ((pid) => {
803
+ try {
804
+ return readLinuxStarttime(pid);
805
+ } catch {
806
+ return;
807
+ }
808
+ });
809
+ if (record.schema !== 1 || readStarttime(record.hostPid) !== record.hostStarttime) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host process start identity changed before the signal");
810
+ }
811
+ assertNotAborted(deps.signal);
812
+ const kill = deps.kill ?? process.kill;
813
+ try {
814
+ kill(record.hostPid, "SIGTERM");
815
+ } catch (error) {
816
+ throw new DaemonControlError("MANAGER_OR_OS_FAILURE", "the verified Host process could not be signalled", error);
817
+ }
818
+ try {
819
+ await waitForHostStopped(record, record.hostPid, deps);
820
+ } catch (error) {
821
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop");
822
+ }
823
+ }
824
+ /**
825
+ * Stop the snapshot's Host and prove the original instance is gone.
826
+ *
827
+ * Linux routing follows the authenticated attribution, never the mere presence
828
+ * of a systemd user bus:
829
+ * - a loaded active/activating unit whose MainPID IS the authenticated Host is
830
+ * stopped through that unit and its exit is awaited;
831
+ * - an independent authenticated Host (no unit, or a loaded unit that systemd
832
+ * reports as inactive/failed/not-found) is re-authenticated, its platform
833
+ * ownership proof (Linux procfs starttime + exact product Host entry, Darwin
834
+ * schema-2 kernel identity) is re-checked, and exactly that PID receives one
835
+ * SIGTERM;
836
+ * - a live Host beside an active unit with a different MainPID, a unit in flux,
837
+ * or an unreadable manager is refused WITHOUT trying the other stop method.
838
+ *
839
+ * Darwin routing uses the verified LaunchAgent instead of a systemd unit: a
840
+ * loaded job whose fixed launch facts match this profile and whose real PID is
841
+ * the authenticated Host is stopped only through `bootout`; a job that is
842
+ * loaded but not running is booted out without a signal; anything transitional,
843
+ * foreign or unreadable is refused.
844
+ */
845
+ async function stopFromSnapshot(snapshot, deps) {
846
+ if (platformOf(deps) === "darwin") return await stopDarwinFromSnapshot(snapshot, deps);
847
+ const { unit, unitState, unitActiveState, unitMainPid, record, processAlive } = snapshot;
848
+ const systemctl = deps.systemctl ?? runSystemctl;
849
+ const liveHost = processAlive && record !== void 0;
850
+ const loaded = unit !== void 0 && unitState !== "not-found";
851
+ const running = loaded && (unitActiveState === "active" || unitActiveState === "activating");
852
+ const ended = loaded && (unitActiveState === "inactive" || unitActiveState === "failed");
853
+ if (snapshot.userManager === "error") throw snapshot.unitQueryFailure ?? new DaemonControlError("MANAGER_OR_OS_FAILURE", "the user manager cannot verify the profile unit");
854
+ if (liveHost) {
855
+ if (running) {
856
+ if (unit === void 0 || unitMainPid !== record.hostPid) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the unit MainPID is not the authenticated Host; refusing to signal an unknown process");
857
+ assertNotAborted(deps.signal);
858
+ await stopOwnedProfileUnit(unit, runtimeDirOf(deps), systemctl, deps.stopTimeoutMs);
859
+ try {
860
+ await waitForHostStopped(record, unitMainPid, deps);
861
+ } catch (error) {
862
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop");
863
+ }
864
+ return;
865
+ }
866
+ if (loaded && !ended) throw new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState}); refusing to signal the Host`);
867
+ if (!running) {
868
+ await stopIndependentHost(snapshot, deps);
869
+ return;
870
+ }
871
+ }
872
+ if (loaded) {
873
+ if (!ended && !running) throw new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState}); refusing to change supervision`);
874
+ if (unit === void 0) return;
875
+ assertNotAborted(deps.signal);
876
+ await stopOwnedProfileUnit(unit, runtimeDirOf(deps), systemctl, deps.stopTimeoutMs);
877
+ try {
878
+ await waitForHostStopped(void 0, unitMainPid, deps);
879
+ } catch (error) {
880
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop");
881
+ }
882
+ }
883
+ }
884
+ /** The Darwin stop route: verified LaunchAgent bootout or one verified SIGTERM. */
885
+ async function stopDarwinFromSnapshot(snapshot, deps) {
886
+ const { launchdUnit, launchdFacts, launchdService, record, processAlive } = snapshot;
887
+ if (snapshot.launchdInspectionFailure !== void 0) throw snapshot.launchdInspectionFailure;
888
+ if (snapshot.launchdQueryFailure !== void 0) throw snapshot.launchdQueryFailure;
889
+ const loaded = launchdService?.kind === "loaded" ? launchdService.service : void 0;
890
+ if (launchdService?.kind === "unknown") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job state is not recognizable; refusing to change supervision");
891
+ if (launchdUnit !== void 0 && launchdFacts === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job facts are unavailable; refusing to change supervision");
892
+ if (launchdUnit !== void 0 && loaded !== void 0 && launchdFacts !== void 0 && !launchdServiceMatches(launchdFacts, launchdUnit, loaded)) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the loaded launchd job does not match the profile plist; refusing to signal an unknown process");
893
+ const liveHost = processAlive && record !== void 0;
894
+ if (liveHost && launchdUnit !== void 0 && launchdFacts !== void 0 && loaded !== void 0) {
895
+ if (loaded.state === "running") {
896
+ if (loaded.pid === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job reports running without a PID; refusing to signal the Host");
897
+ if (loaded.pid !== record.hostPid) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the launchd job PID is not the authenticated Host; refusing to signal an unknown process");
898
+ assertNotAborted(deps.signal);
899
+ await stopLaunchdService(launchdFacts, launchdUnit, launchdDepsOf(deps), record.hostPid);
900
+ try {
901
+ await waitForHostStopped(record, loaded.pid, deps);
902
+ } catch (error) {
903
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop");
904
+ }
905
+ return;
906
+ }
907
+ if (loaded.state === "spawn scheduled") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job is still starting beside the live Host; refusing to signal the Host");
908
+ if (loaded.state !== "not running") throw new DaemonControlError("TRANSITION_UNCERTAIN", `the launchd job is in an unconfirmed state (${loaded.state === "" ? "unknown" : loaded.state}); refusing to signal the Host`);
909
+ }
910
+ if (liveHost) {
911
+ await stopIndependentHost(snapshot, deps);
912
+ return;
913
+ }
914
+ if (loaded !== void 0) {
915
+ if (launchdUnit === void 0 || launchdFacts === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job facts are unavailable; refusing to change supervision");
916
+ if (loaded.pid !== void 0 || loaded.state === "running" || loaded.state === "spawn scheduled") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the launchd job has a process but no authenticated Host record proves its identity; refusing to change supervision");
917
+ if (loaded.state === "not running") {
918
+ assertNotAborted(deps.signal);
919
+ await stopLaunchdService(launchdFacts, launchdUnit, launchdDepsOf(deps));
920
+ return;
921
+ }
922
+ throw new DaemonControlError("TRANSITION_UNCERTAIN", `the launchd job is in an unconfirmed state (${loaded.state === "" ? "unknown" : loaded.state}); refusing to change supervision`);
923
+ }
924
+ if (snapshot.launchdQueryFailure !== void 0) throw snapshot.launchdQueryFailure;
925
+ }
926
+ /**
927
+ * The public logical UDS endpoint of this profile scope (never the macOS private
928
+ * bind name). The value is a single safe `key=value` line or it is omitted: a
929
+ * malformed path is never sanitized into a fake connectable address.
930
+ */
931
+ function acpSocketPathOf(scope, deps) {
932
+ const path = platformOf(deps) === "darwin" ? darwinAcpSocketPaths(scope, uidOf(deps)).publicPath : join(scope.dir, "acp.sock");
933
+ if (!path.startsWith("/") || /[\u0000-\u001f\u007f]/u.test(path)) return void 0;
934
+ return path;
935
+ }
936
+ /**
937
+ * Derive the `acp` field from the ONE authenticated read-only observation. Only
938
+ * an authenticated `host=ready` snapshot is read at all; every unprovable
939
+ * outcome is `unavailable` and NEVER a guessed `disabled`. The ACP facts never
940
+ * change the original exit code, stderr or manager/Host classification.
941
+ */
942
+ async function observeAcpFacts(snapshot, deps) {
943
+ if (snapshot.authenticated === void 0 || snapshot.status.host !== "ready") return { acp: "unavailable" };
944
+ const status = await (deps.observeAcpStatus ?? observeAuthenticatedLocalAcpStatus)(snapshot.authenticated);
945
+ if (status === void 0) return { acp: "unavailable" };
946
+ switch (status.state) {
947
+ case "enabled": {
948
+ const socket = acpSocketPathOf(snapshot.scope, deps);
949
+ return socket === void 0 ? { acp: "enabled" } : {
950
+ acp: "enabled",
951
+ acpSocket: socket
952
+ };
953
+ }
954
+ case "disabled": return { acp: "disabled" };
955
+ case "changing":
956
+ case "unavailable": return { acp: "unavailable" };
957
+ }
958
+ }
959
+ /** The `status` handler. */
960
+ async function runStatus(profile, deps) {
961
+ const snapshot = await readSnapshot(profile, deps, inspectScope(profile, deps));
962
+ const stderr = snapshot.failure === void 0 ? "" : formatDaemonControlError(snapshot.failure);
963
+ const acp = await observeAcpFacts(snapshot, deps);
964
+ return {
965
+ code: snapshot.exitCode,
966
+ stdout: formatDaemonStatus({
967
+ ...snapshot.status,
968
+ ...acp
969
+ }),
970
+ stderr
971
+ };
972
+ }
973
+ /** The `start` handler. */
974
+ async function runStart(profile, deps) {
975
+ const inspected = inspectScope(profile, deps);
976
+ return await withAdminSeat(inspected, deps, async () => {
977
+ const pre = await readSnapshot(profile, deps, inspected);
978
+ if (pre.status.host === "ready") {
979
+ if (pre.failure !== void 0 && pre.failure.code !== "MANAGER_OR_OS_FAILURE") throw pre.failure;
980
+ return {
981
+ code: 0,
982
+ stdout: formatDaemonStatus(pre.status),
983
+ stderr: ""
984
+ };
985
+ }
986
+ if (pre.failure !== void 0) throw pre.failure;
987
+ if (pre.status.host !== "stopped" && pre.status.host !== "starting") throw refuseHostState(pre.status);
988
+ if (platformOf(deps) === "darwin" && pre.launchdUnit !== void 0) {
989
+ if (inspectDarwinLaunchdMigration(pre, deps).kind === "migrate") {
990
+ if (pre.launchdService?.kind === "unknown") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job state is not recognizable; refusing to migrate the profile plist");
991
+ if (pre.launchdService?.kind === "loaded" && (pre.launchdService.service.pid !== void 0 || pre.launchdService.service.state !== "not running")) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job is not idle; refusing to migrate the profile plist during a cold start");
992
+ assertNotAborted(deps.signal);
993
+ if (pre.launchdService?.kind === "loaded") await stopLaunchdService(pre.launchdFacts, pre.launchdUnit, launchdDepsOf(deps));
994
+ applyDarwinLaunchdMigration(pre, deps);
995
+ }
996
+ }
997
+ assertNotAborted(deps.signal);
998
+ const scope = scopeFromInstalledProfile({
999
+ dshHome: profile.home,
1000
+ profileDir: profile.dir,
1001
+ packageRoot: profile.packageRoot,
1002
+ dshVersion: profile.dshVersion
1003
+ });
1004
+ assertNotAborted(deps.signal);
1005
+ const managerDeps = managerDepsOf(deps);
1006
+ const unitStopped = pre.unitState === "not-found" || pre.unitActiveState === "inactive" || pre.unitActiveState === "failed";
1007
+ if (pre.unit !== void 0 && unitStopped) try {
1008
+ await prepareOwnedProfileUnitForCurrentInstall({
1009
+ scope: inspected,
1010
+ profile: profile.name,
1011
+ hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
1012
+ mode: "apply"
1013
+ }, managerDeps);
1014
+ } catch (error) {
1015
+ throw toDaemonControlError(error);
1016
+ }
1017
+ const ensureHost = deps.ensureHost ?? ensureLocalHost;
1018
+ try {
1019
+ await ensureHost({
1020
+ scope,
1021
+ hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
1022
+ dshAnchor: profile.installAnchor,
1023
+ profile: profile.name,
1024
+ hostStartPolicy: "public"
1025
+ });
1026
+ } catch (error) {
1027
+ throw toDaemonControlError(error);
1028
+ }
1029
+ try {
1030
+ const post = await readSnapshot(profile, deps, scope);
1031
+ if (post.failure !== void 0) throw post.failure;
1032
+ if (post.status.host !== "ready") throw refuseHostState(post.status);
1033
+ return {
1034
+ code: 0,
1035
+ stdout: formatDaemonStatus(post.status),
1036
+ stderr: ""
1037
+ };
1038
+ } catch (error) {
1039
+ throw afterCommittedAction(toDaemonControlError(error), "Host start");
1040
+ }
1041
+ });
1042
+ }
1043
+ /** The `stop` handler. */
1044
+ async function runStop(profile, deps) {
1045
+ const inspected = inspectScope(profile, deps);
1046
+ return await withAdminSeat(inspected, deps, async () => {
1047
+ const pre = await readSnapshot(profile, deps, inspected);
1048
+ if (pre.failure !== void 0 && !verifiedUnitManagementAdmitted(pre) && !verifiedLaunchdManagementAdmitted(pre)) throw pre.failure;
1049
+ assertNotAborted(deps.signal);
1050
+ await stopFromSnapshot(pre, deps);
1051
+ try {
1052
+ const post = await readSnapshot(profile, deps, inspected);
1053
+ if (post.failure !== void 0) throw post.failure;
1054
+ if (post.status.host !== "stopped") throw refuseHostState(post.status);
1055
+ return {
1056
+ code: 0,
1057
+ stdout: formatDaemonStatus(post.status),
1058
+ stderr: RUNNING_WORK_NOTICE
1059
+ };
1060
+ } catch (error) {
1061
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop");
1062
+ }
1063
+ });
1064
+ }
1065
+ /** The `restart` handler: stop -> confirmed exit -> controlled unit refresh -> start. */
1066
+ async function runRestart(profile, deps) {
1067
+ const inspected = inspectScope(profile, deps);
1068
+ return await withAdminSeat(inspected, deps, async () => {
1069
+ const pre = await readSnapshot(profile, deps, inspected);
1070
+ const launchdLoaded = pre.launchdService?.kind === "loaded" ? pre.launchdService.service : void 0;
1071
+ const launchdVerified = pre.launchdUnit !== void 0 && pre.launchdFacts !== void 0 && launchdLoaded !== void 0 && launchdServiceMatches(pre.launchdFacts, pre.launchdUnit, launchdLoaded);
1072
+ const unitFailureRecovery = verifiedUnitManagementAdmitted(pre) && (pre.record === void 0 || !pre.processAlive || pre.unitMainPid === pre.record.hostPid);
1073
+ const launchdFailureRecovery = launchdVerified && (pre.hostAuthenticationFailed || pre.hostCompatibilityFailed) && (pre.record === void 0 || !pre.processAlive || launchdLoaded?.pid === pre.record.hostPid);
1074
+ const verifiedUnitRestart = pre.unit !== void 0 && pre.userManager === "available" && (pre.unitActiveState === "active" || pre.unitActiveState === "activating") && (pre.record === void 0 || !pre.processAlive || pre.unitMainPid === pre.record.hostPid);
1075
+ const verifiedLaunchdRestart = launchdVerified && launchdLoaded !== void 0 && (launchdLoaded.state === "running" || launchdLoaded.state === "spawn scheduled" || launchdLoaded.state === "not running") && (pre.record === void 0 || !pre.processAlive || launchdLoaded.pid === pre.record.hostPid);
1076
+ const serviceFailureRecovery = unitFailureRecovery || launchdFailureRecovery;
1077
+ if (pre.failure !== void 0 && !serviceFailureRecovery) throw pre.failure;
1078
+ if (pre.status.host !== "ready" && pre.status.host !== "stopped" && !serviceFailureRecovery && !verifiedUnitRestart && !verifiedLaunchdRestart) throw refuseHostState(pre.status);
1079
+ const oldInstance = pre.record?.instanceId;
1080
+ const managerDeps = managerDepsOf(deps);
1081
+ if (platformOf(deps) === "linux" && pre.unit !== void 0) try {
1082
+ await prepareOwnedProfileUnitForCurrentInstall({
1083
+ scope: inspected,
1084
+ profile: profile.name,
1085
+ hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
1086
+ mode: "inspect"
1087
+ }, managerDeps);
1088
+ } catch (error) {
1089
+ throw toDaemonControlError(error);
1090
+ }
1091
+ const launchdMigration = platformOf(deps) === "darwin" && pre.launchdUnit !== void 0 ? inspectDarwinLaunchdMigration(pre, deps) : void 0;
1092
+ assertNotAborted(deps.signal);
1093
+ await stopFromSnapshot(pre, deps);
1094
+ if (launchdMigration?.kind === "migrate") {
1095
+ assertNotAborted(deps.signal);
1096
+ applyDarwinLaunchdMigration(pre, deps);
1097
+ }
1098
+ try {
1099
+ assertNotAborted(deps.signal);
1100
+ const scope = scopeFromInstalledProfile({
1101
+ dshHome: profile.home,
1102
+ profileDir: profile.dir,
1103
+ packageRoot: profile.packageRoot,
1104
+ dshVersion: profile.dshVersion
1105
+ });
1106
+ assertNotAborted(deps.signal);
1107
+ if (platformOf(deps) === "linux" && pre.unit !== void 0) await prepareOwnedProfileUnitForCurrentInstall({
1108
+ scope: inspected,
1109
+ profile: profile.name,
1110
+ hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
1111
+ mode: "apply"
1112
+ }, managerDeps);
1113
+ await (deps.ensureHost ?? ensureLocalHost)({
1114
+ scope,
1115
+ hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
1116
+ dshAnchor: profile.installAnchor,
1117
+ profile: profile.name,
1118
+ hostStartPolicy: "public"
1119
+ });
1120
+ const post = await readSnapshot(profile, deps, scope);
1121
+ if (post.failure !== void 0) throw post.failure;
1122
+ if (post.status.host !== "ready") throw refuseHostState(post.status);
1123
+ if (pre.unit !== void 0 && post.status.manager !== "systemd") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the restarted Host is not supervised by the verified profile unit");
1124
+ if (oldInstance !== void 0 && post.record?.instanceId === oldInstance) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the restart did not produce a new Host instance");
1125
+ const buildNotice = platformOf(deps) === "darwin" && post.status.compatibility === "other-build" ? "dsh-pi-tui daemon: warning: Host restarted, but the running build differs from the installed profile; inspect the custom LaunchAgent ProgramArguments\n" : "";
1126
+ return {
1127
+ code: 0,
1128
+ stdout: `previous=${oldInstance === void 0 ? "none" : oldInstance.slice(0, 8)}\n${formatDaemonStatus(post.status)}`,
1129
+ stderr: `${RUNNING_WORK_NOTICE}${buildNotice}`
1130
+ };
1131
+ } catch (error) {
1132
+ throw afterCommittedAction(toDaemonControlError(error), "Host restart");
1133
+ }
1134
+ });
1135
+ }
1136
+ /** The `install` handler: explicit unit installation only, never host control. */
1137
+ async function runInstall(profile, deps) {
1138
+ if (platformOf(deps) === "darwin") return await runDarwinInstall(profile, deps);
1139
+ const inspected = inspectScope(profile, deps);
1140
+ return await withAdminSeat(inspected, deps, async () => {
1141
+ const pre = await readSnapshot(profile, deps, inspected);
1142
+ if (pre.unitInspectionFailure !== void 0) throw pre.unitInspectionFailure;
1143
+ if (pre.unitQueryFailure !== void 0) throw pre.unitQueryFailure;
1144
+ assertNotAborted(deps.signal);
1145
+ try {
1146
+ await installProfileHostUnit({
1147
+ scope: inspected,
1148
+ hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
1149
+ dshAnchor: profile.installAnchor,
1150
+ profile: profile.name
1151
+ }, managerDepsOf(deps));
1152
+ } catch (error) {
1153
+ throw toDaemonControlError(error);
1154
+ }
1155
+ try {
1156
+ const post = await readSnapshot(profile, deps, inspected);
1157
+ if (post.unitInspectionFailure !== void 0) throw post.unitInspectionFailure;
1158
+ if (post.unitQueryFailure !== void 0) throw post.unitQueryFailure;
1159
+ if (post.unit === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the installed profile unit could not be confirmed");
1160
+ if (post.unitState === "not-found") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the installed profile unit is not loaded by the manager");
1161
+ if (pre.processAlive && pre.record !== void 0 && (!post.processAlive || post.record === void 0 || post.record.instanceId !== pre.record.instanceId)) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the running Host instance changed during the unit install");
1162
+ return {
1163
+ code: 0,
1164
+ stdout: formatDaemonStatus(post.status),
1165
+ stderr: ""
1166
+ };
1167
+ } catch (error) {
1168
+ throw afterCommittedAction(toDaemonControlError(error), "profile unit install");
1169
+ }
1170
+ });
1171
+ }
1172
+ /** The `uninstall` handler: remove this Profile's service definition only. */
1173
+ async function runUninstall(profile, deps) {
1174
+ if (platformOf(deps) === "darwin") return await runDarwinUninstall(profile, deps);
1175
+ const inspected = inspectScope(profile, deps);
1176
+ return await withAdminSeat(inspected, deps, async () => {
1177
+ const pre = await readSnapshot(profile, deps, inspected);
1178
+ if (pre.unitInspectionFailure !== void 0) throw pre.unitInspectionFailure;
1179
+ if (pre.unit === void 0) return {
1180
+ code: 0,
1181
+ stdout: formatDaemonStatus(pre.status),
1182
+ stderr: ""
1183
+ };
1184
+ if (pre.failure !== void 0 && !verifiedUnitManagementAdmitted(pre)) throw pre.failure;
1185
+ if (pre.userManager !== "available") throw new DaemonControlError("MANAGER_OR_OS_FAILURE", "the user manager cannot verify the profile unit");
1186
+ const loaded = pre.unitState !== "not-found";
1187
+ const running = loaded && (pre.unitActiveState === "active" || pre.unitActiveState === "activating");
1188
+ const ended = loaded && (pre.unitActiveState === "inactive" || pre.unitActiveState === "failed");
1189
+ const liveHost = pre.processAlive && pre.record !== void 0;
1190
+ if (loaded && !running && !ended) throw new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${pre.unitActiveState === "" ? "unknown" : pre.unitActiveState}); refusing to uninstall`);
1191
+ if (running) {
1192
+ if (liveHost && pre.unitMainPid !== pre.record.hostPid) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the profile unit MainPID is not the live Host; refusing to uninstall");
1193
+ const systemctl = deps.systemctl ?? runSystemctl;
1194
+ assertNotAborted(deps.signal);
1195
+ await stopOwnedProfileUnit(pre.unit, runtimeDirOf(deps), systemctl, deps.stopTimeoutMs);
1196
+ const ownHost = liveHost && pre.record !== void 0 && pre.record.hostPid === pre.unitMainPid ? pre.record : void 0;
1197
+ try {
1198
+ await waitForHostStopped(ownHost, pre.unitMainPid, deps);
1199
+ } catch (error) {
1200
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop for uninstall");
1201
+ }
1202
+ }
1203
+ const systemctl = deps.systemctl ?? runSystemctl;
1204
+ assertNotAborted(deps.signal);
1205
+ uninstallOwnedProfileUnit(pre.unit, pre.scope, profile.name);
1206
+ try {
1207
+ const reload = await systemctl([
1208
+ "--user",
1209
+ "--no-pager",
1210
+ "--no-ask-password",
1211
+ "daemon-reload"
1212
+ ], runtimeDirOf(deps));
1213
+ if (reload.kind !== "exited" || reload.code !== 0) throw new DaemonControlError("MANAGER_OR_OS_FAILURE", "daemon-reload failed after removing the profile unit");
1214
+ const post = await readSnapshot(profile, deps, inspected);
1215
+ if (post.unitInspectionFailure !== void 0) throw post.unitInspectionFailure;
1216
+ if (post.unitQueryFailure !== void 0) throw post.unitQueryFailure;
1217
+ if (existsSync(pre.unit.filePath)) throw new DaemonControlError("MANAGER_OR_OS_FAILURE", "the profile unit could not be confirmed removed");
1218
+ return {
1219
+ code: 0,
1220
+ stdout: formatDaemonStatus(post.status),
1221
+ stderr: running ? RUNNING_WORK_NOTICE : ""
1222
+ };
1223
+ } catch (error) {
1224
+ throw afterCommittedAction(toDaemonControlError(error), "profile unit removal");
1225
+ }
1226
+ });
1227
+ }
1228
+ /** The Darwin `install` handler: explicit LaunchAgent plist only, never host control. */
1229
+ async function runDarwinInstall(profile, deps) {
1230
+ const inspected = inspectScope(profile, deps);
1231
+ return await withAdminSeat(inspected, deps, async () => {
1232
+ const pre = await readSnapshot(profile, deps, inspected);
1233
+ if (pre.launchdInspectionFailure !== void 0) throw pre.launchdInspectionFailure;
1234
+ if (pre.launchdQueryFailure !== void 0) throw pre.launchdQueryFailure;
1235
+ assertNotAborted(deps.signal);
1236
+ try {
1237
+ const facts = pre.launchdFacts ?? launchdFactsOf(inspected, profile);
1238
+ await installLaunchdUnit(facts, launchdDepsOf(deps));
1239
+ } catch (error) {
1240
+ throw toDaemonControlError(error);
1241
+ }
1242
+ try {
1243
+ const post = await readSnapshot(profile, deps, inspected);
1244
+ if (post.launchdInspectionFailure !== void 0) throw post.launchdInspectionFailure;
1245
+ if (post.launchdQueryFailure !== void 0) throw post.launchdQueryFailure;
1246
+ if (post.launchdUnit === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the installed launchd plist could not be confirmed");
1247
+ if (pre.processAlive && pre.record !== void 0 && (!post.processAlive || post.record === void 0 || post.record.instanceId !== pre.record.instanceId)) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the running Host instance changed during the plist install");
1248
+ return {
1249
+ code: 0,
1250
+ stdout: formatDaemonStatus(post.status),
1251
+ stderr: ""
1252
+ };
1253
+ } catch (error) {
1254
+ throw afterCommittedAction(toDaemonControlError(error), "launchd plist install");
1255
+ }
1256
+ });
1257
+ }
1258
+ /** The Darwin `uninstall` handler: remove this Profile's LaunchAgent only. */
1259
+ async function runDarwinUninstall(profile, deps) {
1260
+ const inspected = inspectScope(profile, deps);
1261
+ return await withAdminSeat(inspected, deps, async () => {
1262
+ const pre = await readSnapshot(profile, deps, inspected);
1263
+ if (pre.launchdInspectionFailure !== void 0) throw pre.launchdInspectionFailure;
1264
+ if (pre.launchdUnit === void 0) return {
1265
+ code: 0,
1266
+ stdout: formatDaemonStatus(pre.status),
1267
+ stderr: ""
1268
+ };
1269
+ if (pre.launchdQueryFailure !== void 0) throw pre.launchdQueryFailure;
1270
+ if (pre.launchdFacts === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd plist facts are unavailable; refusing to uninstall");
1271
+ const service = pre.launchdService;
1272
+ if (service?.kind === "unknown") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job state is not recognizable; refusing to uninstall");
1273
+ const loadedService = service?.kind === "loaded" ? service.service : void 0;
1274
+ const liveHost = pre.processAlive && pre.record !== void 0;
1275
+ const running = loadedService !== void 0 && (loadedService.pid !== void 0 || loadedService.state === "running" || loadedService.state === "spawn scheduled");
1276
+ if (running && liveHost && pre.record !== void 0 && loadedService?.pid !== pre.record.hostPid) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the launchd job PID is not the live Host; refusing to uninstall");
1277
+ if (running && !liveHost) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the launchd job has a process but no authenticated Host record proves its identity; refusing to uninstall");
1278
+ assertNotAborted(deps.signal);
1279
+ try {
1280
+ const expectedPid = liveHost && pre.record !== void 0 ? pre.record.hostPid : void 0;
1281
+ await uninstallLaunchdUnit(pre.launchdFacts, pre.launchdUnit, launchdDepsOf(deps), expectedPid);
1282
+ if (running && liveHost && pre.record !== void 0) await waitForHostStopped(pre.record, loadedService?.pid ?? pre.record.hostPid, deps);
1283
+ } catch (error) {
1284
+ throw afterCommittedAction(toDaemonControlError(error), "launchd plist removal");
1285
+ }
1286
+ try {
1287
+ const post = await readSnapshot(profile, deps, inspected);
1288
+ if (post.launchdInspectionFailure !== void 0) throw post.launchdInspectionFailure;
1289
+ if (post.launchdUnit !== void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the profile LaunchAgent could not be confirmed removed");
1290
+ return {
1291
+ code: 0,
1292
+ stdout: formatDaemonStatus(post.status),
1293
+ stderr: running ? RUNNING_WORK_NOTICE : ""
1294
+ };
1295
+ } catch (error) {
1296
+ throw afterCommittedAction(toDaemonControlError(error), "launchd plist removal");
1297
+ }
1298
+ });
1299
+ }
1300
+ /**
1301
+ * Run one fixed `journalctl --user-unit <verified-name>` invocation.
1302
+ *
1303
+ * `--unit` filters the SYSTEM unit field (`_SYSTEMD_UNIT`), so with `--user` it
1304
+ * never matches a user unit's entries — it silently prints nothing. The user
1305
+ * unit field is selected by `--user-unit` (`_SYSTEMD_USER_UNIT`), which is the
1306
+ * only form that returns the managed unit's journal.
1307
+ */
1308
+ function journalctlArgs(unit, lines) {
1309
+ return [
1310
+ "--user-unit",
1311
+ unit,
1312
+ "--no-pager",
1313
+ "-o",
1314
+ "cat",
1315
+ "-n",
1316
+ String(lines)
1317
+ ];
1318
+ }
1319
+ function runJournalctl(unit, lines) {
1320
+ return new Promise((resolve) => {
1321
+ let settled = false;
1322
+ let stdout = "";
1323
+ let stderr = "";
1324
+ let overflow = false;
1325
+ const settle = (result) => {
1326
+ if (settled) return;
1327
+ settled = true;
1328
+ clearTimeout(timer);
1329
+ resolve(result);
1330
+ };
1331
+ let child;
1332
+ try {
1333
+ child = spawn(JOURNALCTL, journalctlArgs(unit, lines), {
1334
+ shell: false,
1335
+ stdio: [
1336
+ "ignore",
1337
+ "pipe",
1338
+ "pipe"
1339
+ ],
1340
+ env: process.env
1341
+ });
1342
+ } catch {
1343
+ settle({
1344
+ code: 1,
1345
+ stdout: "",
1346
+ stderr: "journalctl could not be spawned"
1347
+ });
1348
+ return;
1349
+ }
1350
+ const timer = setTimeout(() => {
1351
+ child.kill("SIGKILL");
1352
+ settle({
1353
+ code: 1,
1354
+ stdout: "",
1355
+ stderr: "journalctl timed out"
1356
+ });
1357
+ }, JOURNALCTL_TIMEOUT_MS);
1358
+ const collect = (current, chunk) => {
1359
+ if (overflow) return current;
1360
+ const next = current + chunk.toString("utf8");
1361
+ if (Buffer.byteLength(next, "utf8") > JOURNAL_MAX_OUTPUT_BYTES) {
1362
+ overflow = true;
1363
+ child.kill("SIGKILL");
1364
+ return current;
1365
+ }
1366
+ return next;
1367
+ };
1368
+ child.stdout?.on("data", (chunk) => {
1369
+ stdout = collect(stdout, chunk);
1370
+ });
1371
+ child.stderr?.on("data", (chunk) => {
1372
+ stderr = collect(stderr, chunk);
1373
+ });
1374
+ child.once("error", () => {
1375
+ settle({
1376
+ code: 1,
1377
+ stdout: "",
1378
+ stderr: "journalctl could not be spawned"
1379
+ });
1380
+ });
1381
+ child.once("close", (code) => {
1382
+ if (overflow) {
1383
+ settle({
1384
+ code: 0,
1385
+ stdout: `${stdout}\n${LOG_TRUNCATION_MARKER}\n`,
1386
+ stderr
1387
+ });
1388
+ return;
1389
+ }
1390
+ settle({
1391
+ code: code ?? 1,
1392
+ stdout,
1393
+ stderr
1394
+ });
1395
+ });
1396
+ });
1397
+ }
1398
+ /**
1399
+ * Read the tail of the scope `host.log`. The read is bounded and never follows
1400
+ * a final symlink, but it does not judge the user's existing owner/mode: an
1401
+ * existing 0644 log chosen by the user is readable. New logs are still created
1402
+ * 0600 by `spawnHostCandidate`.
1403
+ */
1404
+ async function tailHostLog(path, lines) {
1405
+ let fd;
1406
+ try {
1407
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
1408
+ } catch (error) {
1409
+ const code = error.code;
1410
+ if (code === "ENOENT" || code === "ELOOP") return void 0;
1411
+ throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log could not be opened");
1412
+ }
1413
+ try {
1414
+ const info = fstatSync(fd);
1415
+ if (!info.isFile()) return void 0;
1416
+ const length = Math.min(info.size, HOST_LOG_MAX_BYTES);
1417
+ const start = info.size - length;
1418
+ const buffer = Buffer.alloc(length);
1419
+ let offset = 0;
1420
+ while (offset < buffer.length) {
1421
+ const read = readSync(fd, buffer, offset, buffer.length - offset, start + offset);
1422
+ if (read <= 0) break;
1423
+ offset += read;
1424
+ }
1425
+ const all = buffer.toString("utf8", 0, offset).split("\n");
1426
+ if (all.length > 0 && all[all.length - 1] === "") all.pop();
1427
+ const tail = all.slice(Math.max(0, all.length - lines));
1428
+ return `${start > 0 ? `${LOG_TRUNCATION_MARKER}\n` : ""}${tail.join("\n")}${tail.length === 0 ? "" : "\n"}`;
1429
+ } finally {
1430
+ closeSync(fd);
1431
+ }
1432
+ }
1433
+ /** Remove terminal control sequences and best-effort secret material. */
1434
+ function sanitizeLogText(text) {
1435
+ return text.replace(/\u001b\[[0-?]*[ -/]*[@-~]/gu, "").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, "").split("\n").map((line) => line.replace(/\b((?:proxy-)?authorization|x-api-key|x-auth-token|cookie|set-cookie|secret|password)\s*[:=]\s*.*$/gimu, "$1=[redacted]").replace(/\b(token|access_token|refresh_token|api[_-]?key)\s*[:=]\s*[^\s&]+/gimu, "$1=[redacted]").replace(/([?&](?:token|key|secret|password)=)[^&\s]+/gimu, "$1[redacted]").replace(/https?:\/\/[^\s"']*(?:token=|key=|secret=|password=)[^\s"']*/giu, "[redacted-url]").replace(/\bconnectUrl\b[^\s]*/giu, "connectUrl=[redacted]").slice(0, MAX_LOG_LINE_LENGTH)).join("\n");
1436
+ }
1437
+ /**
1438
+ * Darwin log source: a verified loaded LaunchAgent governs the profile, and the
1439
+ * stdout/stderr sinks THAT JOB DECLARES in `launchctl print` are read as two
1440
+ * separately bounded, separately labelled streams (never presented as one
1441
+ * time-merged log). A verified loaded job that declares no sink makes the
1442
+ * command return `LOG_SOURCE_UNAVAILABLE`; the product's default private file
1443
+ * names are never substituted for a user configuration. A job that is
1444
+ * installed but NOT loaded does not govern an independent Host, so that Host
1445
+ * keeps reading `host.log`. After the launchd job has stopped there is no live
1446
+ * authority proving whether the retained launchd streams or an earlier
1447
+ * `host.log` is the most recent Host; the source is unprovable and the command
1448
+ * fails closed instead of guessing a file.
1449
+ */
1450
+ async function runDarwinLogs(scope, intent, deps, snapshot) {
1451
+ if (snapshot.launchdInspectionFailure !== void 0) throw snapshot.launchdInspectionFailure;
1452
+ if (snapshot.launchdQueryFailure !== void 0) {
1453
+ if (snapshot.launchdQueryFailure.code === "IDENTITY_OR_OWNERSHIP_REFUSED") throw snapshot.launchdQueryFailure;
1454
+ throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", `the launchd job cannot be verified: ${snapshot.launchdQueryFailure.reason}`);
1455
+ }
1456
+ const lines = intent.lines ?? 100;
1457
+ const { launchdUnit, launchdFacts, launchdService, record, processAlive, authenticated } = snapshot;
1458
+ const liveHost = processAlive && record !== void 0;
1459
+ const loadedService = launchdService?.kind === "loaded" ? launchdService.service : void 0;
1460
+ let launchdSource;
1461
+ if (liveHost) {
1462
+ if (authenticated === void 0) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the authenticated Host is unavailable; refusing to guess a log source");
1463
+ if (snapshot.status.manager === "launchd") {
1464
+ if (launchdUnit === void 0 || launchdFacts === void 0 || loadedService === void 0) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the launchd-managed Host facts are unavailable; refusing to guess a log source");
1465
+ if (!launchdServiceMatches(launchdFacts, launchdUnit, loadedService)) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the launchd job does not match the profile plist; refusing to guess a log source");
1466
+ if (loadedService.pid !== record?.hostPid) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the launchd job PID is not the authenticated Host; refusing to guess a log source");
1467
+ launchdSource = loadedService;
1468
+ } else if (snapshot.status.manager === "process") {
1469
+ if (launchdUnit !== void 0 && launchdFacts === void 0) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the launchd job facts are unavailable; refusing to guess a log source");
1470
+ if (launchdService?.kind === "unknown") throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the launchd job state is not recognizable; refusing to guess a log source");
1471
+ if (launchdUnit !== void 0 && launchdFacts !== void 0 && loadedService !== void 0) {
1472
+ if (!launchdServiceMatches(launchdFacts, launchdUnit, loadedService)) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the launchd job does not match the profile plist; refusing to guess a log source");
1473
+ if (loadedService.pid !== void 0 || loadedService.state === "running" || loadedService.state === "spawn scheduled") throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the loaded launchd job does not supervise the authenticated Host; refusing to guess a log source");
1474
+ }
1475
+ } else throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", `the Host supervision is ${snapshot.status.manager}; refusing to guess a log source`);
1476
+ } else if (launchdUnit !== void 0) {
1477
+ if (launchdFacts === void 0) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the launchd job facts are unavailable; refusing to guess a log source");
1478
+ if (launchdService?.kind === "unknown") throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the launchd job state is not recognizable; refusing to guess a log source");
1479
+ if (loadedService !== void 0) {
1480
+ if (!launchdServiceMatches(launchdFacts, launchdUnit, loadedService)) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the launchd job does not match the profile plist; refusing to guess a log source");
1481
+ launchdSource = loadedService;
1482
+ } else if (launchdService?.kind === "not-loaded") throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the last Host log source cannot be proven after the launchd job stopped; read the retained launchd logs or host.log directly");
1483
+ }
1484
+ if (launchdSource !== void 0) {
1485
+ if (launchdSource.stdoutPath === void 0 && launchdSource.stderrPath === void 0) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the verified launchd job declares no log sink for this profile");
1486
+ const tail = deps.hostLogTail ?? tailHostLog;
1487
+ const stdout = launchdSource.stdoutPath === void 0 ? void 0 : await tail(launchdSource.stdoutPath, lines);
1488
+ const stderr = launchdSource.stderrPath === void 0 ? void 0 : await tail(launchdSource.stderrPath, lines);
1489
+ const sections = [];
1490
+ if (stdout !== void 0 && stdout.trim() !== "") sections.push(`[dsh-pi-tui daemon: launchd stdout]\n${sanitizeLogText(stdout).replace(/\n*$/u, "\n")}`);
1491
+ if (stderr !== void 0 && stderr.trim() !== "") sections.push(`[dsh-pi-tui daemon: launchd stderr]\n${sanitizeLogText(stderr).replace(/\n*$/u, "\n")}`);
1492
+ if (sections.length === 0) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "no launchd Host log output is available for this profile");
1493
+ return {
1494
+ code: 0,
1495
+ stdout: sections.join(""),
1496
+ stderr: LOG_SANITIZATION_NOTICE
1497
+ };
1498
+ }
1499
+ if (!liveHost && launchdUnit === void 0) {
1500
+ const logs = launchdLogPaths(scope.dir);
1501
+ if (existsSync(logs.stdout) || existsSync(logs.stderr)) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the last Host log source cannot be proven after the launchd plist was removed; read the retained launchd logs or host.log directly");
1502
+ }
1503
+ const path = join(scope.dir, "host.log");
1504
+ const value = await (deps.hostLogTail ?? tailHostLog)(path, lines);
1505
+ if (value === void 0 || value.trim() === "") throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "no Host log is available for this profile");
1506
+ return {
1507
+ code: 0,
1508
+ stdout: `${sanitizeLogText(value)}`,
1509
+ stderr: LOG_SANITIZATION_NOTICE
1510
+ };
1511
+ }
1512
+ /**
1513
+ * The `logs` handler. The source follows the SAME verified attribution as
1514
+ * `status`: an installed, manager-loaded unit that actually supervises the
1515
+ * current Host (or governs a stopped/starting profile) reads its
1516
+ * `journalctl --user-unit` journal; a genuinely independent Host, or a profile
1517
+ * with no loaded unit, reads the scope `host.log`. An unreadable manager or a
1518
+ * unit whose ownership is in flux is an explicit failure — the command never
1519
+ * guesses a source.
1520
+ */
1521
+ async function runLogs(profile, intent, deps) {
1522
+ const scope = inspectScope(profile, deps);
1523
+ const snapshot = await readSnapshot(profile, deps, scope);
1524
+ if (platformOf(deps) === "darwin") return await runDarwinLogs(scope, intent, deps, snapshot);
1525
+ if (snapshot.unitInspectionFailure !== void 0) throw snapshot.unitInspectionFailure;
1526
+ if (snapshot.unitQueryFailure !== void 0) {
1527
+ if (snapshot.unitQueryFailure.code === "IDENTITY_OR_OWNERSHIP_REFUSED") throw snapshot.unitQueryFailure;
1528
+ throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", `the user manager cannot verify the profile unit: ${snapshot.unitQueryFailure.reason}`);
1529
+ }
1530
+ const lines = intent.lines ?? 100;
1531
+ const { unit, unitState, unitActiveState, unitMainPid, record, processAlive, authenticated } = snapshot;
1532
+ const liveHost = processAlive && record !== void 0;
1533
+ const loaded = unit !== void 0 && unitState !== "not-found";
1534
+ const running = loaded && (unitActiveState === "active" || unitActiveState === "activating");
1535
+ const ended = loaded && (unitActiveState === "inactive" || unitActiveState === "failed");
1536
+ let source;
1537
+ if (running) {
1538
+ if (liveHost) {
1539
+ if (authenticated === void 0 || record === void 0 || unitMainPid !== record.hostPid) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the unit MainPID is not the authenticated Host; refusing to guess a log source");
1540
+ }
1541
+ source = "journal";
1542
+ } else if (loaded && !ended) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState}); refusing to guess a log source`);
1543
+ else source = ended && !liveHost ? "journal" : "host-log";
1544
+ let text;
1545
+ if (source === "journal" && unit !== void 0) {
1546
+ const result = await (deps.journal ?? runJournalctl)(unit.unitName, lines);
1547
+ if (result.code !== 0 || result.stdout.trim() === "") throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "no journal entries are available for the owned profile unit");
1548
+ text = result.stdout;
1549
+ } else {
1550
+ const path = join(scope.dir, "host.log");
1551
+ const value = await (deps.hostLogTail ?? tailHostLog)(path, lines);
1552
+ if (value === void 0 || value.trim() === "") throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "no Host log is available for this profile");
1553
+ text = value;
1554
+ }
1555
+ return {
1556
+ code: 0,
1557
+ stdout: `${sanitizeLogText(text)}`,
1558
+ stderr: LOG_SANITIZATION_NOTICE
1559
+ };
1560
+ }
1561
+ /**
1562
+ * Run ONE daemon management command for ONE official Profile. Every failure is
1563
+ * mapped to the fixed stable code/exit taxonomy; no raw Error message, command
1564
+ * argv, Host URL, Cookie or private path reaches stdout/stderr.
1565
+ */
1566
+ async function runDaemonControl(intent, profile, deps = {}) {
1567
+ try {
1568
+ switch (intent.verb) {
1569
+ case "status": return await runStatus(profile, deps);
1570
+ case "start": return await runStart(profile, deps);
1571
+ case "stop": return await runStop(profile, deps);
1572
+ case "restart": return await runRestart(profile, deps);
1573
+ case "logs": return await runLogs(profile, intent, deps);
1574
+ case "install": return await runInstall(profile, deps);
1575
+ case "uninstall": return await runUninstall(profile, deps);
1576
+ }
1577
+ } catch (error) {
1578
+ const failure = toDaemonControlError(error);
1579
+ const notice = intent.verb === "stop" || intent.verb === "restart" ? RUNNING_WORK_NOTICE : "";
1580
+ return {
1581
+ code: failure.exitCode,
1582
+ stdout: "",
1583
+ stderr: `${formatDaemonControlError(failure)}${notice}`
1584
+ };
1585
+ }
1586
+ }
1587
+ //#endregion
1588
+ export { runDaemonControl };