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