@xmoon76/dsh-pi-tui 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.en.md +64 -26
  2. package/README.md +64 -26
  3. package/cordis.patch.yml +13 -0
  4. package/dist/acp-stdio.mjs +151 -0
  5. package/dist/{bootstrap-C9nl6e13.mjs → bootstrap-CVyHGQDX.mjs} +22330 -6888
  6. package/dist/browser-CDUSHIIr.mjs +76 -0
  7. package/dist/builtins.mjs +2 -2
  8. package/dist/{client-bootstrap-CGezi85O.mjs → client-bootstrap-4UoeVIHE.mjs} +2407 -1830
  9. package/dist/client-runtime-BHBlVUf5.mjs +1376 -0
  10. package/dist/{daemon-launcher-H_1r5Cqs.mjs → daemon-launcher-DxIgjBHW.mjs} +1551 -57
  11. package/dist/daemon-launcher.d.mts +85 -14
  12. package/dist/daemon-launcher.mjs +2 -2
  13. package/dist/diagnostics-Db5iVcuJ.mjs +123 -0
  14. package/dist/{entry-control-jBfKn1qO.mjs → entry-control-BDLZgg4m.mjs} +1 -1
  15. package/dist/{extensions-6a5vvJUT.mjs → extensions-Dx7ncPNA.mjs} +1 -4
  16. package/dist/extensions.mjs +1 -1
  17. package/dist/handoff-BjoEy3f8.mjs +106 -0
  18. package/dist/history-search-limits-Cx2UvRC2.mjs +16 -0
  19. package/dist/history-search-remote-BHuoellG.mjs +113 -0
  20. package/dist/history-search-remote-BzXdvrxk.mjs +26 -0
  21. package/dist/history-search-seat-BcHJTpeB.mjs +639 -0
  22. package/dist/history-search-seat-rZcq0XV6.mjs +639 -0
  23. package/dist/{host-bootstrap-MVxks641.mjs → host-bootstrap-BfnufpnW.mjs} +37 -72
  24. package/dist/{host-foundation-probe-DK7n5jDu.mjs → host-foundation-probe-DlD8-N_Q.mjs} +2 -2
  25. package/dist/host-runtime.mjs +5611 -290
  26. package/dist/index.d.mts +13 -6
  27. package/dist/index.mjs +22766 -6893
  28. package/dist/installed-dsh-BjUiJSwR.mjs +142 -0
  29. package/dist/interaction-port-D1Yv9zgu.mjs +45 -0
  30. package/dist/local-acp-control-CC5z4Xbq.mjs +304 -0
  31. package/dist/local-acp-endpoint-D1jYdJdv.mjs +41 -0
  32. package/dist/local-acp-listener-Cmgb5M0H.mjs +9493 -0
  33. package/dist/local-acp-status-B_25Q6kU.mjs +101 -0
  34. package/dist/local-client.mjs +719 -93
  35. package/dist/local-daemon-control-BFJAC8Kg.mjs +2199 -0
  36. package/dist/local-daemon-control-Bm3imctD.mjs +2101 -0
  37. package/dist/{local-discovery-BPZw1wEd.mjs → local-discovery-BMhaGIiJ.mjs} +254 -544
  38. package/dist/{local-discovery-BMoNXZjJ.mjs → local-discovery-Ba7_-NNC.mjs} +1 -1
  39. package/dist/{local-discovery-Bq3jLAn1.mjs → local-discovery-QSbFpjK2.mjs} +301 -544
  40. package/dist/local-host.mjs +970 -501
  41. package/dist/local-profile-daemon-admin-otpm69R6.mjs +469 -0
  42. package/dist/{local-scope-DEuGAy8l.mjs → local-scope-5DEKA_lW.mjs} +1075 -31
  43. package/dist/{local-transport-X4ZCe2uE.mjs → local-transport-DeWmdZ5E.mjs} +14 -3
  44. package/dist/{local-web-control-DKWtXIkr.mjs → local-web-control-Dny93N-r.mjs} +10 -7
  45. package/dist/{local-workspace-object-D06GL0UO.mjs → local-workspace-object-D0RVQt8U.mjs} +33 -9
  46. package/dist/model-selection-CYlqg2DV.mjs +83 -0
  47. package/dist/native-client-domains-Dg4srzYt.mjs +2 -0
  48. package/dist/native-client.d.mts +735 -0
  49. package/dist/native-client.mjs +3534 -0
  50. package/dist/{open-CmOBxSjN.mjs → open-QQva8-ar.mjs} +24 -20
  51. package/dist/{pi-tui-remote-contribution-Do8ECrUy.mjs → pi-tui-remote-contribution-565wiLWp.mjs} +741 -150
  52. package/dist/preferences.mjs +1 -1
  53. package/dist/{profile-preferences-migration-CThz4rHH.mjs → profile-preferences-migration-CNOWIdnr.mjs} +1 -1
  54. package/dist/{profile-preferences-migration-BfUGdPZx.mjs → profile-preferences-migration-IrnXcJWK.mjs} +10 -8
  55. package/dist/{prompt-sections-DXmjB58H.mjs → prompt-sections-Bi-9_Gr_.mjs} +28 -10
  56. package/dist/{prompt-sections-DUKmWb8g.mjs → prompt-sections-DFS1dqsY.mjs} +342 -56
  57. package/dist/{dist-BFgC-5tL.mjs → recall-scope-9Nuoto_i.mjs} +353 -1
  58. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  59. package/dist/schema-CCLvDa7Q.mjs +177 -0
  60. package/dist/{schema-qE_P09zJ.mjs → schema-t97l3aK8.mjs} +56 -3
  61. package/dist/{session-DC0XQr5O.mjs → session-Cs8iLCEx.mjs} +784 -342
  62. package/dist/{session-Cihe8PPS.mjs → session-EBRZF6Ow.mjs} +783 -341
  63. package/dist/session-create-facts-CkfG5DpQ.mjs +20 -0
  64. package/dist/{startup-CarQxWwi.d.mts → startup-Dti3Udne.d.mts} +30 -3
  65. package/dist/{startup-CARqn3kV.mjs → startup-UtFQSDe_.mjs} +90 -15
  66. package/dist/startup.d.mts +2 -2
  67. package/dist/startup.mjs +1 -1
  68. package/dist/task-read-remote-DRtkXDrZ.mjs +1083 -0
  69. package/dist/{terminal-progress-source-D4DHyXDo.mjs → terminal-progress-source-VsczdXA-.mjs} +610 -335
  70. package/dist/{transcript-view-a7cROAaI.mjs → transcript-view-B6vCnukn.mjs} +2284 -1166
  71. package/dist/{transcript-view-hvNVkPtv.mjs → transcript-view-DSSdE2vK.mjs} +2191 -765
  72. package/dist/write-failure-xNKczXH7.mjs +189 -0
  73. package/package.json +25 -8
  74. package/dist/local-acp-listener-CNkguN5-.mjs +0 -2566
  75. package/dist/local-daemon-control-Bg9s2aYi.mjs +0 -1424
  76. package/dist/local-daemon-control-Cu_4FIdd.mjs +0 -1585
  77. package/dist/local-profile-daemon-admin-AXgVH-6y.mjs +0 -91
  78. package/dist/preset-BcWqOtY7.mjs +0 -46
@@ -0,0 +1,2101 @@
1
+ import { B as installedDshManifest, C as sameKernelProcess, F as win32SystemDirectory, M as win32CurrentTokenSid, O as openWin32Process, V as readManifestObject, a as bindProcessSeat, c as darwinHostProfileSeatDir, f as materializeBuild, i as bindDarwinKernelSeat, j as waitWin32Handle, k as openWin32StopSignal, l as ensureInstalledProfileScopeDirectory, m as readLinuxStarttime, n as LocalScopeError, o as bindProfileKernelSeat, u as inspectInstalledProfileScope, w as closeWin32Handle, x as readKernelProcess } from "./local-scope-5DEKA_lW.mjs";
2
+ import { b as observeAuthenticatedLocalAcpStatus, n as darwinAcpSocketPaths } from "./local-acp-listener-Cmgb5M0H.mjs";
3
+ import { A as installLaunchdUnit, C as runSystemctl, D as uninstallOwnedProfileUnit, E as stopOwnedProfileUnit, M as launchdServiceMatches, N as stopLaunchdService, O as inspectLaunchdService, P as uninstallLaunchdUnit, S as queryOwnedProfileUnit, T as setOwnedProfileUnitEnablement, _ as buildUnitName, b as inspectOwnedProfileUnit, c as ensureLocalHost, i as authenticateLocalHost, j as launchdLogPaths, k as inspectOwnedLaunchdUnit, l as inspectHostProcess, m as sameLocalInstanceRecord, p as readLocalRecord, r as assertRecordedHostKernelIdentityCurrent, t as assertClientHostCompatible, v as collectLaunchdProfileFacts, w as selectRuntimeDir, x as installProfileHostUnit, y as collectLaunchdUnitFacts } from "./local-discovery-QSbFpjK2.mjs";
4
+ import { t as acpPipeAddress } from "./local-acp-endpoint-D1jYdJdv.mjs";
5
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
6
+ import { dirname, isAbsolute, join, posix, sep } from "node:path";
7
+ import { execFile } from "node:child_process";
8
+ import { stripVTControlCharacters } from "node:util";
9
+ //#region src/app/remote-process/local-host-windows-login.ts
10
+ /**
11
+ * Windows login-only Task Scheduler adapter (DS-08).
12
+ *
13
+ * This module owns exactly ONE Windows login-startup route: one native
14
+ * Scheduled Task in the root `\` folder that starts the existing public
15
+ * `daemon start` CLI at the current user's logon. It is NOT Host supervision:
16
+ * it never observes readiness, never restarts after an abnormal exit, and it
17
+ * never becomes a second Host/Session/Agent/Writer authority. The Host remains
18
+ * the only business owner and the existing Event/held-handle stop path is
19
+ * unchanged.
20
+ *
21
+ * The task definition is the ONLY persistent authority. There is no marker
22
+ * file, receipt, registry or shadow state: the exact task name, description
23
+ * and current-user principal SID are the ownership metadata of the one native
24
+ * task, and a fresh task is created with COM `TASK_CREATE` (create-only, no
25
+ * overwrite). The adapter talks to the same system Task Scheduler service
26
+ * through system Windows PowerShell; no schtasks/cmdlet fallback, no WMI, no
27
+ * admin and no stored password.
28
+ *
29
+ * @module app/remote-process/local-host-windows-login
30
+ */
31
+ /** The deterministic task-name prefix; the full scope id is the suffix. */
32
+ const WINDOWS_LOGIN_TASK_PREFIX = "dsh-pi-tui-login-";
33
+ /** The exact description metadata; the full scope id is the suffix. */
34
+ const WINDOWS_LOGIN_DESCRIPTION_PREFIX = "dsh-pi-tui login-only scope=";
35
+ /** Bound on one system-PowerShell invocation. */
36
+ const WINDOWS_LOGIN_TIMEOUT_MS = 15e3;
37
+ /** Hard cap on captured PowerShell output. */
38
+ const WINDOWS_LOGIN_MAX_OUTPUT_BYTES = 65536;
39
+ /** The fixed COM state values used by the idle-unregister admission. */
40
+ const TASK_STATE_DISABLED = 1;
41
+ const TASK_STATE_READY = 3;
42
+ /** The exact Task Scheduler COM not-found HRESULT. */
43
+ const TASK_NOT_FOUND_HRESULT = "0x80070002";
44
+ /** The only supported official DSH CLI entry inside the installed package. */
45
+ const OFFICIAL_DSH_BIN = "lib/bin.js";
46
+ /** Safe operator hint for a possibly-committed uninstall. */
47
+ const WINDOWS_UNINSTALL_UNCERTAIN = "the Task Scheduler uninstall may already be committed; inspect the native Task Scheduler task before deciding";
48
+ /** The deterministic task name for one canonical profile scope. */
49
+ function buildWindowsLoginTaskName(scopeId) {
50
+ return `${WINDOWS_LOGIN_TASK_PREFIX}${scopeId}`;
51
+ }
52
+ /** The deterministic native description for one canonical profile scope. */
53
+ function buildWindowsLoginDescription(scopeId) {
54
+ return `${WINDOWS_LOGIN_DESCRIPTION_PREFIX}${scopeId}`;
55
+ }
56
+ /** Build the inner action script data (UTF-16LE command payload). */
57
+ function buildWindowsLoginActionArgument(data) {
58
+ const script = [
59
+ "$ErrorActionPreference = 'Continue'",
60
+ `$f = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(JSON.stringify(data), "utf8").toString("base64")}')) | ConvertFrom-Json`,
61
+ "$env:DSH_HOME = [string]$f.home",
62
+ "$LASTEXITCODE = $null",
63
+ "& ([string]$f.node) ([string]$f.cli) --profile ([string]$f.profile) daemon start",
64
+ "$code = $LASTEXITCODE",
65
+ "if ($null -eq $code) { exit 1 }",
66
+ "exit $code"
67
+ ].join("\n");
68
+ return `-NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ${Buffer.from(script, "utf16le").toString("base64")}`;
69
+ }
70
+ /** The fixed outer native-script prefix; the operation payload is data only. */
71
+ const NATIVE_SCRIPT_PREFIX = String.raw`$ErrorActionPreference = 'Stop'
72
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
73
+ function Hex([int32]$value) { return ('0x{0:X8}' -f ([BitConverter]::ToUInt32([BitConverter]::GetBytes($value), 0))) }
74
+ function ActualHResult($exception) {
75
+ $outer = $null
76
+ if ($exception.HResult) { $outer = Hex $exception.HResult }
77
+ $inner = $exception.InnerException
78
+ $innerHr = $null
79
+ if ($inner -and $inner.HResult) { $innerHr = Hex $inner.HResult }
80
+ if ($innerHr) { return [ordered]@{ hresult = $innerHr; outerHresult = $outer; innerHresult = $innerHr } }
81
+ return [ordered]@{ hresult = $outer; outerHresult = $outer; innerHresult = $null }
82
+ }
83
+ function Exact([string]$left, [string]$right) { return [string]::Equals($left, $right, [StringComparison]::Ordinal) }
84
+ function Emit($value) { [Console]::Out.Write(($value | ConvertTo-Json -Compress -Depth 8)) }
85
+ function Get-ExactTask([string]$name) {
86
+ try {
87
+ $task = $folder.GetTask($name)
88
+ return [ordered]@{ present = $true; task = $task; hresult = $null }
89
+ } catch {
90
+ $hr = ActualHResult $_.Exception
91
+ return [ordered]@{ present = $false; task = $null; hresult = $hr.hresult; outerHresult = $hr.outerHresult; innerHresult = $hr.innerHresult }
92
+ }
93
+ }
94
+ function Get-Identity($task) {
95
+ $principalUserId = [string]$task.Definition.Principal.UserId
96
+ $principalSid = $null
97
+ try { $principalSid = ([Security.Principal.NTAccount]::new($principalUserId)).Translate([Security.Principal.SecurityIdentifier]).Value } catch { $principalSid = $null }
98
+ return [ordered]@{
99
+ name = [string]$task.Name
100
+ path = [string]$task.Path
101
+ description = [string]$task.Definition.RegistrationInfo.Description
102
+ principalUserId = $principalUserId
103
+ principalSid = $principalSid
104
+ state = [int]$task.State
105
+ }
106
+ }
107
+ $committed = $false
108
+ $payload = $null
109
+ try {
110
+ $payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PAYLOAD__')) | ConvertFrom-Json
111
+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
112
+ $account = $identity.Name
113
+ $sid = $identity.User.Value
114
+ $elevated = (New-Object Security.Principal.WindowsPrincipal($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
115
+ if ($elevated) { Emit ([ordered]@{ kind = 'refused'; reason = 'elevated' }); exit 0 }
116
+ $service = New-Object -ComObject 'Schedule.Service'
117
+ $service.Connect()
118
+ $folder = $service.GetFolder('\')
119
+ switch ([string]$payload.op) {
120
+ 'inspect' {
121
+ $observed = Get-ExactTask ([string]$payload.taskName)
122
+ if (-not $observed.present) {
123
+ if ($observed.hresult -eq '0x80070002') { Emit ([ordered]@{ kind = 'absent'; hresult = $observed.hresult; outerHresult = $observed.outerHresult; innerHresult = $observed.innerHresult }) }
124
+ else { Emit ([ordered]@{ kind = 'error'; phase = 'get-task'; hresult = $observed.hresult }) }
125
+ } else {
126
+ Emit ([ordered]@{ kind = 'existing'; identity = (Get-Identity $observed.task) })
127
+ }
128
+ }
129
+ 'install' {
130
+ $observed = Get-ExactTask ([string]$payload.taskName)
131
+ if (-not $observed.present -and $observed.hresult -ne '0x80070002') {
132
+ Emit ([ordered]@{ kind = 'error'; phase = 'get-task'; hresult = $observed.hresult })
133
+ exit 0
134
+ }
135
+ if ($observed.present) {
136
+ Emit ([ordered]@{ kind = 'exists'; identity = (Get-Identity $observed.task) })
137
+ exit 0
138
+ }
139
+ $definition = $service.NewTask(0)
140
+ $definition.RegistrationInfo.Description = [string]$payload.description
141
+ $definition.Principal.UserId = $account
142
+ $definition.Principal.LogonType = 3
143
+ $definition.Principal.RunLevel = 0
144
+ $trigger = $definition.Triggers.Create(9)
145
+ $trigger.UserId = $account
146
+ $trigger.Enabled = $true
147
+ $action = $definition.Actions.Create(0)
148
+ $action.Path = [string]$payload.action.path
149
+ $action.Arguments = [string]$payload.action.arguments
150
+ $action.WorkingDirectory = [string]$payload.action.workingDirectory
151
+ $definition.Settings.Enabled = $true
152
+ $definition.Settings.MultipleInstances = 2
153
+ $definition.Settings.ExecutionTimeLimit = 'PT5M'
154
+ $definition.Settings.DisallowStartIfOnBatteries = $false
155
+ $definition.Settings.StopIfGoingOnBatteries = $false
156
+ $definition.Settings.RunOnlyIfIdle = $false
157
+ $definition.Settings.RunOnlyIfNetworkAvailable = $false
158
+ $definition.Settings.AllowDemandStart = $true
159
+ $definition.Settings.RestartCount = 0
160
+ $definition.Settings.StartWhenAvailable = $false
161
+ $committed = $true
162
+ try {
163
+ $registered = $folder.RegisterTaskDefinition([string]$payload.taskName, $definition, 2, $account, $null, 3, $null)
164
+ } catch {
165
+ $hr = ActualHResult $_.Exception
166
+ $hresult = $hr.hresult
167
+ $afterRegister = Get-ExactTask ([string]$payload.taskName)
168
+ if ($afterRegister.present) {
169
+ Emit ([ordered]@{ kind = 'collision'; hresult = $hresult; identity = (Get-Identity $afterRegister.task) })
170
+ } elseif ($afterRegister.hresult -eq '0x80070002') {
171
+ Emit ([ordered]@{ kind = 'error'; phase = 'register'; hresult = $hresult })
172
+ } else {
173
+ Emit ([ordered]@{ kind = 'uncertain'; phase = 'register-readback'; hresult = $afterRegister.hresult })
174
+ }
175
+ exit 0
176
+ }
177
+ Emit ([ordered]@{ kind = 'created'; identity = (Get-Identity $registered) })
178
+ }
179
+ 'uninstall' {
180
+ $observed = Get-ExactTask ([string]$payload.taskName)
181
+ if (-not $observed.present) {
182
+ if ($observed.hresult -eq '0x80070002') { Emit ([ordered]@{ kind = 'absent'; hresult = $observed.hresult; outerHresult = $observed.outerHresult; innerHresult = $observed.innerHresult }) }
183
+ else { Emit ([ordered]@{ kind = 'error'; phase = 'get-task'; hresult = $observed.hresult }) }
184
+ exit 0
185
+ }
186
+ $before = Get-Identity $observed.task
187
+ $owned = (Exact $before.name ([string]$payload.taskName)) -and (Exact $before.path ('\' + [string]$payload.taskName)) -and (Exact $before.description ([string]$payload.description)) -and (Exact $before.principalSid $sid)
188
+ if (-not $owned) { Emit ([ordered]@{ kind = 'refused'; identity = $before }); exit 0 }
189
+ if ($before.state -ne 1 -and $before.state -ne 3) { Emit ([ordered]@{ kind = 'busy'; identity = $before }); exit 0 }
190
+ $recheck = Get-ExactTask ([string]$payload.taskName)
191
+ if (-not $recheck.present) {
192
+ if ($recheck.hresult -eq '0x80070002') { Emit ([ordered]@{ kind = 'absent'; hresult = $recheck.hresult; outerHresult = $recheck.outerHresult; innerHresult = $recheck.innerHresult }) }
193
+ else { Emit ([ordered]@{ kind = 'error'; phase = 'recheck'; hresult = $recheck.hresult }) }
194
+ exit 0
195
+ }
196
+ $current = Get-Identity $recheck.task
197
+ $same = (Exact $current.name $before.name) -and (Exact $current.path $before.path) -and (Exact $current.description $before.description) -and (Exact $current.principalSid $before.principalSid) -and ($current.state -eq $before.state)
198
+ if (-not $same) { Emit ([ordered]@{ kind = 'uncertain'; reason = 'changed' }); exit 0 }
199
+ $committed = $true
200
+ try {
201
+ $folder.DeleteTask([string]$payload.taskName, 0)
202
+ } catch {
203
+ $hr = ActualHResult $_.Exception
204
+ $hresult = $hr.hresult
205
+ $afterDelete = Get-ExactTask ([string]$payload.taskName)
206
+ Emit ([ordered]@{ kind = 'delete-error'; hresult = $hresult; after = [ordered]@{ present = $afterDelete.present; hresult = $afterDelete.hresult; identity = $(if ($afterDelete.present) { Get-Identity $afterDelete.task } else { $null }) } })
207
+ exit 0
208
+ }
209
+ $after = Get-ExactTask ([string]$payload.taskName)
210
+ if (-not $after.present -and $after.hresult -eq '0x80070002') {
211
+ Emit ([ordered]@{ kind = 'deleted'; identity = $before })
212
+ } else {
213
+ Emit ([ordered]@{ kind = 'uncertain'; phase = 'post-delete'; hresult = $after.hresult })
214
+ }
215
+ }
216
+ default {
217
+ Emit ([ordered]@{ kind = 'error'; phase = 'payload'; hresult = $null })
218
+ }
219
+ }
220
+ } catch {
221
+ $hr = ActualHResult $_.Exception
222
+ $hresult = $hr.hresult
223
+ if ($committed) { Emit ([ordered]@{ kind = 'uncertain'; phase = 'exception'; hresult = $hresult; outerHresult = $hr.outerHresult; innerHresult = $hr.innerHresult }) }
224
+ else { Emit ([ordered]@{ kind = 'error'; phase = 'exception'; hresult = $hresult }) }
225
+ }
226
+ exit 0`;
227
+ /** Build one outer native script; the payload is base64 UTF-8 JSON data. */
228
+ function buildNativeScript(payload) {
229
+ const encoded = Buffer.from(JSON.stringify(payload), "utf8").toString("base64");
230
+ return NATIVE_SCRIPT_PREFIX.replace("__PAYLOAD__", encoded);
231
+ }
232
+ /** The production system Windows PowerShell path from kernel32, never the environment. */
233
+ function defaultSystemPowerShell() {
234
+ const systemDirectory = win32SystemDirectory();
235
+ if (systemDirectory === void 0) throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the Windows system directory is unavailable");
236
+ return join(systemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe");
237
+ }
238
+ /** The production system-PowerShell runner, with a bounded process. */
239
+ const runWindowsPowerShell = async (executable, args) => {
240
+ try {
241
+ if (!lstatSync(executable).isFile()) return {
242
+ kind: "spawn-error",
243
+ error: Object.assign(/* @__PURE__ */ new Error("system Windows PowerShell is not a regular file"), { code: "ENOENT" })
244
+ };
245
+ } catch (error) {
246
+ return {
247
+ kind: "spawn-error",
248
+ error
249
+ };
250
+ }
251
+ return await new Promise((resolve) => {
252
+ let child;
253
+ child = execFile(executable, [...args], {
254
+ timeout: WINDOWS_LOGIN_TIMEOUT_MS,
255
+ maxBuffer: WINDOWS_LOGIN_MAX_OUTPUT_BYTES,
256
+ encoding: "utf8",
257
+ windowsHide: true
258
+ }, (error, stdout, stderr) => {
259
+ if (error !== null && error !== void 0) {
260
+ const failure = error;
261
+ if (failure.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
262
+ resolve({ kind: "output-overflow" });
263
+ return;
264
+ }
265
+ if (failure.killed === true || failure.signal === "SIGTERM") {
266
+ resolve({ kind: "timeout" });
267
+ return;
268
+ }
269
+ if (typeof failure.code === "number") {
270
+ resolve({
271
+ kind: "exited",
272
+ code: failure.code,
273
+ stdout: String(stdout),
274
+ stderr: String(stderr)
275
+ });
276
+ return;
277
+ }
278
+ if (child?.pid === void 0) {
279
+ resolve({
280
+ kind: "spawn-error",
281
+ error: failure
282
+ });
283
+ return;
284
+ }
285
+ resolve({
286
+ kind: "runner-error",
287
+ error: failure
288
+ });
289
+ return;
290
+ }
291
+ resolve({
292
+ kind: "exited",
293
+ code: 0,
294
+ stdout: String(stdout),
295
+ stderr: String(stderr)
296
+ });
297
+ });
298
+ });
299
+ };
300
+ /** Prove one absolute regular file, returning its canonical target. */
301
+ function absoluteRegularFile(pathValue, label) {
302
+ if (!isAbsolute(pathValue)) throw new LocalScopeError("HOST_MANAGER_ERROR", `windows login: the ${label} must be an absolute path`);
303
+ try {
304
+ const real = realpathSync.native(pathValue);
305
+ if (!lstatSync(real).isFile()) throw new LocalScopeError("HOST_MANAGER_ERROR", `windows login: the ${label} must be a regular file`);
306
+ return real;
307
+ } catch (error) {
308
+ if (error instanceof LocalScopeError) throw error;
309
+ throw new LocalScopeError("HOST_MANAGER_ERROR", `windows login: the ${label} is not readable`, error);
310
+ }
311
+ }
312
+ /** Validate the current installed Node/official-CLI/Profile facts for a FRESH task. */
313
+ function freshFacts(profile, scope, deps) {
314
+ const node = absoluteRegularFile(deps.nodePath ?? process.execPath, "Node executable");
315
+ const anchor = installedDshManifest(profile.installAnchor);
316
+ if (anchor === void 0) throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the installed DSH anchor is not an @deepseek-ai/dsh manifest");
317
+ const manifest = readManifestObject(anchor);
318
+ if (manifest === void 0 || manifest.version !== profile.dshVersion) throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the installed DSH version does not match the profile");
319
+ const binField = manifest.bin;
320
+ const declaredBin = typeof binField === "string" ? binField : binField !== null && typeof binField === "object" && !Array.isArray(binField) && typeof binField.dsh === "string" ? binField.dsh : void 0;
321
+ if (declaredBin === void 0 || posix.normalize(declaredBin) !== OFFICIAL_DSH_BIN) throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the installed DSH manifest does not declare the supported official dsh bin");
322
+ let packageDir;
323
+ try {
324
+ packageDir = realpathSync.native(dirname(anchor));
325
+ } catch (error) {
326
+ throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the installed DSH package directory is unavailable", error);
327
+ }
328
+ const cli = absoluteRegularFile(join(packageDir, OFFICIAL_DSH_BIN), "official dsh bin");
329
+ if (!cli.startsWith(`${packageDir}${sep}`)) throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the official dsh bin escapes its package");
330
+ const systemPowerShell = absoluteRegularFile(deps.systemPowerShell ?? defaultSystemPowerShell(), "system Windows PowerShell");
331
+ return {
332
+ action: {
333
+ path: systemPowerShell,
334
+ arguments: buildWindowsLoginActionArgument({
335
+ node,
336
+ cli,
337
+ home: scope.dshHome,
338
+ profile: profile.name
339
+ }),
340
+ workingDirectory: scope.profileRealpath
341
+ },
342
+ systemPowerShell
343
+ };
344
+ }
345
+ /** Resolve the current token SID or fail closed. */
346
+ function currentSidOf(deps) {
347
+ const sid = deps.currentSid ?? win32CurrentTokenSid();
348
+ if (sid === void 0 || sid === "") throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the current token SID is unavailable");
349
+ return sid;
350
+ }
351
+ /** Run one native script with the injected/production runner. */
352
+ async function invokeNative(deps, script, executable) {
353
+ return await (deps.runPowerShell ?? runWindowsPowerShell)(executable, [
354
+ "-NoProfile",
355
+ "-NonInteractive",
356
+ "-EncodedCommand",
357
+ Buffer.from(script, "utf16le").toString("base64")
358
+ ]);
359
+ }
360
+ /** Strictly parse one native JSON result; any extra/malformed output is undefined. */
361
+ function parseNativeOutput(result) {
362
+ if (result.kind !== "exited" || result.code !== 0) return void 0;
363
+ return parseJsonRecord(result.stdout);
364
+ }
365
+ function parseJsonRecord(text) {
366
+ const trimmed = text.replace(/^\uFEFF/u, "").trim();
367
+ if (trimmed === "") return void 0;
368
+ try {
369
+ const value = JSON.parse(trimmed);
370
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
371
+ } catch {
372
+ return;
373
+ }
374
+ }
375
+ /** Parse one identity object; a missing SID is a foreign/unresolved fact. */
376
+ function parseIdentity(value) {
377
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
378
+ const record = value;
379
+ const name = typeof record.name === "string" ? record.name : void 0;
380
+ const path = typeof record.path === "string" ? record.path : void 0;
381
+ const description = typeof record.description === "string" ? record.description : void 0;
382
+ const principalUserId = typeof record.principalUserId === "string" ? record.principalUserId : void 0;
383
+ const principalSid = typeof record.principalSid === "string" ? record.principalSid : void 0;
384
+ const state = typeof record.state === "number" && Number.isInteger(record.state) ? record.state : void 0;
385
+ if (name === void 0 || path === void 0 || description === void 0 || principalUserId === void 0 || state === void 0) return void 0;
386
+ return {
387
+ name,
388
+ path,
389
+ description,
390
+ principalUserId,
391
+ principalSid,
392
+ state
393
+ };
394
+ }
395
+ /** The identity predicate: exact task path/name/description/current-user SID. */
396
+ function isOwnedIdentity(identity, taskName, description, currentSid) {
397
+ return identity.name === taskName && identity.path === `\\${taskName}` && identity.description === description && identity.principalSid === currentSid;
398
+ }
399
+ /** The safe reason for an elevated/unknown native refusal. */
400
+ function safeReason(value, fallback) {
401
+ return typeof value === "string" && /^[a-z0-9-]{1,64}$/u.test(value) ? value : fallback;
402
+ }
403
+ /** Inspect the exact login task for one profile. */
404
+ async function inspectWindowsLoginTask(scope, deps = {}) {
405
+ const taskName = buildWindowsLoginTaskName(scope.scopeId);
406
+ const description = buildWindowsLoginDescription(scope.scopeId);
407
+ const sid = currentSidOf(deps);
408
+ let executable;
409
+ try {
410
+ executable = absoluteRegularFile(deps.systemPowerShell ?? defaultSystemPowerShell(), "system Windows PowerShell");
411
+ } catch {
412
+ return {
413
+ kind: "os-failure",
414
+ reason: "the system Windows PowerShell is unavailable"
415
+ };
416
+ }
417
+ try {
418
+ const output = parseNativeOutput(await invokeNative(deps, buildNativeScript({
419
+ op: "inspect",
420
+ taskName
421
+ }), executable));
422
+ if (output === void 0) return {
423
+ kind: "os-failure",
424
+ reason: "the Task Scheduler inspection did not return a valid result"
425
+ };
426
+ switch (output.kind) {
427
+ case "absent":
428
+ if (output.hresult !== TASK_NOT_FOUND_HRESULT) return {
429
+ kind: "os-failure",
430
+ reason: "the Task Scheduler inspection returned an unconfirmed missing task"
431
+ };
432
+ return {
433
+ kind: "absent",
434
+ hresult: TASK_NOT_FOUND_HRESULT
435
+ };
436
+ case "existing": {
437
+ const identity = parseIdentity(output.identity);
438
+ if (identity === void 0) return {
439
+ kind: "os-failure",
440
+ reason: "the existing Task Scheduler identity is malformed"
441
+ };
442
+ return isOwnedIdentity(identity, taskName, description, sid) ? {
443
+ kind: "owned",
444
+ taskName,
445
+ identity
446
+ } : {
447
+ kind: "foreign",
448
+ taskName,
449
+ identity
450
+ };
451
+ }
452
+ case "refused": return {
453
+ kind: "refused",
454
+ reason: safeReason(output.reason, "the Task Scheduler refused the operation")
455
+ };
456
+ default: return {
457
+ kind: "os-failure",
458
+ reason: "the Task Scheduler inspection failed"
459
+ };
460
+ }
461
+ } catch (error) {
462
+ if (error instanceof LocalScopeError) return {
463
+ kind: "os-failure",
464
+ reason: error.message
465
+ };
466
+ return {
467
+ kind: "os-failure",
468
+ reason: "the Task Scheduler inspection could not be completed"
469
+ };
470
+ }
471
+ }
472
+ /** Create one FRESH login task with COM TASK_CREATE (never overwrite). */
473
+ async function createWindowsLoginTask(scope, profile, deps = {}) {
474
+ const taskName = buildWindowsLoginTaskName(scope.scopeId);
475
+ const description = buildWindowsLoginDescription(scope.scopeId);
476
+ const sid = currentSidOf(deps);
477
+ let facts;
478
+ try {
479
+ facts = freshFacts(profile, scope, deps);
480
+ } catch (error) {
481
+ if (error instanceof LocalScopeError) return {
482
+ kind: "os-failure",
483
+ reason: error.message
484
+ };
485
+ return {
486
+ kind: "os-failure",
487
+ reason: "the current installed Node/DSH facts are unavailable"
488
+ };
489
+ }
490
+ let result;
491
+ try {
492
+ result = await invokeNative(deps, buildNativeScript({
493
+ op: "install",
494
+ taskName,
495
+ description,
496
+ action: facts.action
497
+ }), facts.systemPowerShell);
498
+ } catch {
499
+ return {
500
+ kind: "uncertain",
501
+ reason: "the Task Scheduler create request could not be confirmed"
502
+ };
503
+ }
504
+ if (result.kind === "spawn-error") return {
505
+ kind: "os-failure",
506
+ reason: "the Task Scheduler create PowerShell could not be started"
507
+ };
508
+ const output = parseNativeOutput(result);
509
+ if (output === void 0) return {
510
+ kind: "uncertain",
511
+ reason: "the Task Scheduler create request could not be confirmed"
512
+ };
513
+ switch (output.kind) {
514
+ case "created": {
515
+ const identity = parseIdentity(output.identity);
516
+ if (identity === void 0 || !isOwnedIdentity(identity, taskName, description, sid)) return {
517
+ kind: "uncertain",
518
+ reason: "the created Task Scheduler identity could not be confirmed"
519
+ };
520
+ return {
521
+ kind: "created",
522
+ taskName,
523
+ identity
524
+ };
525
+ }
526
+ case "exists":
527
+ case "collision": {
528
+ const identity = parseIdentity(output.identity);
529
+ if (identity === void 0) return {
530
+ kind: "uncertain",
531
+ reason: "the competing Task Scheduler identity is malformed"
532
+ };
533
+ return isOwnedIdentity(identity, taskName, description, sid) ? {
534
+ kind: "reused",
535
+ taskName,
536
+ identity
537
+ } : {
538
+ kind: "foreign",
539
+ taskName,
540
+ identity
541
+ };
542
+ }
543
+ case "refused": return {
544
+ kind: "refused",
545
+ reason: safeReason(output.reason, "the Task Scheduler refused the operation")
546
+ };
547
+ case "uncertain": return {
548
+ kind: "uncertain",
549
+ reason: "the Task Scheduler create request may already be committed"
550
+ };
551
+ default: return {
552
+ kind: "os-failure",
553
+ reason: "the Task Scheduler create request failed"
554
+ };
555
+ }
556
+ }
557
+ /** Uninstall the exact login task; missing is an idempotent absence. */
558
+ async function uninstallWindowsLoginTask(scope, profile, deps = {}) {
559
+ const taskName = buildWindowsLoginTaskName(scope.scopeId);
560
+ const description = buildWindowsLoginDescription(scope.scopeId);
561
+ const sid = currentSidOf(deps);
562
+ let executable;
563
+ try {
564
+ executable = absoluteRegularFile(deps.systemPowerShell ?? defaultSystemPowerShell(), "system Windows PowerShell");
565
+ } catch {
566
+ return {
567
+ kind: "os-failure",
568
+ reason: "the system Windows PowerShell is unavailable"
569
+ };
570
+ }
571
+ let result;
572
+ try {
573
+ result = await invokeNative(deps, buildNativeScript({
574
+ op: "uninstall",
575
+ taskName,
576
+ description
577
+ }), executable);
578
+ } catch {
579
+ return {
580
+ kind: "uncertain",
581
+ reason: WINDOWS_UNINSTALL_UNCERTAIN
582
+ };
583
+ }
584
+ if (result.kind === "spawn-error") return {
585
+ kind: "os-failure",
586
+ reason: "the Task Scheduler uninstall PowerShell could not be started"
587
+ };
588
+ const output = parseNativeOutput(result);
589
+ if (output === void 0) return {
590
+ kind: "uncertain",
591
+ reason: WINDOWS_UNINSTALL_UNCERTAIN
592
+ };
593
+ switch (output.kind) {
594
+ case "absent":
595
+ if (output.hresult !== TASK_NOT_FOUND_HRESULT) return {
596
+ kind: "os-failure",
597
+ reason: "the Task Scheduler uninstall absence was not confirmed"
598
+ };
599
+ return { kind: "absent" };
600
+ case "deleted": {
601
+ const identity = parseIdentity(output.identity);
602
+ if (identity === void 0 || !isOwnedIdentity(identity, taskName, description, sid)) return {
603
+ kind: "uncertain",
604
+ reason: WINDOWS_UNINSTALL_UNCERTAIN
605
+ };
606
+ return { kind: "deleted" };
607
+ }
608
+ case "refused": return {
609
+ kind: "refused",
610
+ reason: safeReason(output.reason, "the Task Scheduler refused the operation")
611
+ };
612
+ case "busy": {
613
+ const state = parseIdentity(output.identity)?.state;
614
+ if (state === void 0) return {
615
+ kind: "uncertain",
616
+ reason: WINDOWS_UNINSTALL_UNCERTAIN
617
+ };
618
+ return {
619
+ kind: "busy",
620
+ state,
621
+ reason: "the login task is running or queued; wait for the short action to settle and retry"
622
+ };
623
+ }
624
+ case "delete-error": {
625
+ const after = output.after !== null && typeof output.after === "object" && !Array.isArray(output.after) ? output.after : void 0;
626
+ if (after !== void 0 && after.present === true) {
627
+ const identity = parseIdentity(after.identity);
628
+ if (identity !== void 0 && isOwnedIdentity(identity, taskName, description, sid) && (identity.state === TASK_STATE_READY || identity.state === TASK_STATE_DISABLED)) return {
629
+ kind: "os-failure",
630
+ reason: "the Task Scheduler delete failed and the owned task remains"
631
+ };
632
+ return {
633
+ kind: "uncertain",
634
+ reason: WINDOWS_UNINSTALL_UNCERTAIN
635
+ };
636
+ }
637
+ if (after !== void 0 && after.present === false && after.hresult === TASK_NOT_FOUND_HRESULT) return { kind: "deleted" };
638
+ return {
639
+ kind: "uncertain",
640
+ reason: WINDOWS_UNINSTALL_UNCERTAIN
641
+ };
642
+ }
643
+ case "error": return {
644
+ kind: "os-failure",
645
+ reason: "the Task Scheduler uninstall failed"
646
+ };
647
+ default: return {
648
+ kind: "uncertain",
649
+ reason: WINDOWS_UNINSTALL_UNCERTAIN
650
+ };
651
+ }
652
+ }
653
+ //#endregion
654
+ //#region src/app/remote-process/local-daemon-control.ts
655
+ /**
656
+ * The M6-2C daemon management control plane.
657
+ *
658
+ * This is the ONE module that turns a typed `DaemonControlIntent` into a real
659
+ * local OS observation or an explicit supervision transition for ONE official
660
+ * Profile. It owns no Host business object: Host readiness is always the
661
+ * existing authenticated `/connect` Cookie + identity echo + fresh kernel
662
+ * identity handshake (Linux `/proc` starttime, macOS Darwin schema 2), and a
663
+ * Host stop remains the existing `runProfile` shutdown owner reached either
664
+ * through the verified profile unit's manager SIGTERM, a verified user-level
665
+ * launchd job's `bootout`, or a single verified-PID POSIX SIGTERM when the
666
+ * authenticated Host is independent.
667
+ *
668
+ * `status` and `logs` are strictly read-only: they never create the profile run
669
+ * directory, never write a service definition, never start a Host and never
670
+ * touch a Session. The mutating verbs (start, stop, restart, install, uninstall,
671
+ * enable and disable) are serialized by one short-lived profile-scoped admin
672
+ * seat: Linux holds the abstract-socket name, macOS holds the Darwin `O_EXLOCK` `admin` seat
673
+ * file beside the Host singleton seat. The kernel releases it when the command
674
+ * dies, so there is no persistent lock file or second state machine.
675
+ *
676
+ * @module app/remote-process/local-daemon-control
677
+ */
678
+ /** The fixed exit class of every stable code. */
679
+ const EXIT_CODE = {
680
+ UNSUPPORTED_PLATFORM: 3,
681
+ IDENTITY_OR_OWNERSHIP_REFUSED: 3,
682
+ MANAGER_OR_OS_FAILURE: 4,
683
+ LOG_SOURCE_UNAVAILABLE: 4,
684
+ DAEMON_CONTROL_BUSY: 5,
685
+ TRANSITION_UNCERTAIN: 5
686
+ };
687
+ /** A management failure carrying the stable code and exit class. */
688
+ var DaemonControlError = class extends Error {
689
+ code;
690
+ exitCode;
691
+ reason;
692
+ constructor(code, reason, cause) {
693
+ super(reason, cause === void 0 ? void 0 : { cause });
694
+ this.name = "DaemonControlError";
695
+ this.code = code;
696
+ this.exitCode = EXIT_CODE[code];
697
+ this.reason = reason;
698
+ }
699
+ };
700
+ /** The fixed one-line error format; never a raw Error message or argv. */
701
+ function formatDaemonControlError(error) {
702
+ return `dsh-pi-tui daemon: ${error.code}: ${sanitizeReason(error.reason)}\n`;
703
+ }
704
+ /** Visible risk reminder printed beside log output. */
705
+ const LOG_SANITIZATION_NOTICE = "dsh-pi-tui daemon: note: log output is best-effort sanitized; review it before sharing\n";
706
+ /** The fixed running-work warning every mutating verb prints on success. */
707
+ 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";
708
+ /** The fixed note for an existing Windows login task that was preserved. */
709
+ const WINDOWS_EXISTING_DEFINITION_NOTE = "dsh-pi-tui daemon: note: existing definition preserved; --autostart applies only to a new installation\n";
710
+ /** The admin seat prefix; the kernel releases the abstract name on process death. */
711
+ const ADMIN_SEAT_PREFIX = "\0dsh-pi-tui-admin-";
712
+ /** Bound on one journalctl invocation. */
713
+ const JOURNALCTL_TIMEOUT_MS = 1e4;
714
+ /** Hard cap on captured journal output. */
715
+ const JOURNAL_MAX_OUTPUT_BYTES = 262144;
716
+ /** Bound on one scope host.log tail read (from the end of the file). */
717
+ const HOST_LOG_MAX_BYTES = 262144;
718
+ /** Bound on one displayed log line. */
719
+ const MAX_LOG_LINE_LENGTH = 2e3;
720
+ /** The fixed journal executable. */
721
+ const JOURNALCTL = "journalctl";
722
+ /** Stable truncation marker for bounded log reads. */
723
+ const LOG_TRUNCATION_MARKER = "[dsh-pi-tui daemon: log output truncated]";
724
+ /** Replace absolute paths and control characters in a human reason. */
725
+ function sanitizeReason(text) {
726
+ 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);
727
+ }
728
+ /** Map a lower-level stable failure onto the management error taxonomy. */
729
+ function toDaemonControlError(error) {
730
+ if (error instanceof DaemonControlError) return error;
731
+ if (error instanceof LocalScopeError) switch (error.code) {
732
+ case "B1_PLATFORM_UNSUPPORTED": return new DaemonControlError("UNSUPPORTED_PLATFORM", "this daemon command requires Linux, macOS or Windows");
733
+ case "HOST_MANAGER_UNIT_CONFLICT":
734
+ case "HOST_IDENTITY_MISMATCH":
735
+ case "HOST_PROTOCOL_INCOMPATIBLE":
736
+ case "HOST_BUILD_INCOMPATIBLE":
737
+ case "HOST_AUTH_FAILED":
738
+ case "SCOPE_DIRECTORY_UNSAFE":
739
+ case "LOCAL_FILE_UNSAFE":
740
+ case "PROCESS_STARTTIME_UNAVAILABLE": return new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", error.message, error);
741
+ case "HOST_STOP_TIMEOUT": return new DaemonControlError("TRANSITION_UNCERTAIN", error.message, error);
742
+ case "HOST_START_TIMEOUT": return afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", error.message, error), "Host start");
743
+ case "DAEMON_CONTROL_BUSY": return new DaemonControlError("DAEMON_CONTROL_BUSY", "another daemon control operation is already running for this profile", error);
744
+ case "HOST_UNRESPONSIVE": return new DaemonControlError("MANAGER_OR_OS_FAILURE", error.message, error);
745
+ default: return new DaemonControlError("MANAGER_OR_OS_FAILURE", error.message, error);
746
+ }
747
+ return new DaemonControlError("MANAGER_OR_OS_FAILURE", "an unexpected local management failure occurred", error);
748
+ }
749
+ /** Add recovery context only to a completed operation's failed confirmation. */
750
+ function afterCommittedAction(failure, action) {
751
+ return new DaemonControlError(failure.code, `${action} may already be committed; final verification failed. Run daemon status before retrying. ${failure.reason}`, failure);
752
+ }
753
+ /** Throw when the supervisor is shutting down and the operation must settle. */
754
+ function assertNotAborted(signal) {
755
+ if (signal !== void 0 && signal.aborted) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the management operation was cancelled by supervisor shutdown");
756
+ }
757
+ /** The effective platform/uid inputs. */
758
+ function platformOf(deps) {
759
+ return deps.platform ?? process.platform;
760
+ }
761
+ function uidOf(deps) {
762
+ const uid = deps.uid ?? (typeof process.getuid === "function" ? process.getuid() : void 0);
763
+ if (uid === void 0) throw new DaemonControlError("UNSUPPORTED_PLATFORM", "this daemon command requires a local user identity");
764
+ return uid;
765
+ }
766
+ /** Compute the read-only scope; no directory is created. */
767
+ function inspectScope(profile, deps) {
768
+ const platform = platformOf(deps);
769
+ if (platform !== "linux" && platform !== "darwin" && platform !== "win32") throw new DaemonControlError("UNSUPPORTED_PLATFORM", "this daemon command requires Linux, macOS or Windows");
770
+ try {
771
+ return inspectInstalledProfileScope({
772
+ dshHome: profile.home,
773
+ profileDir: profile.dir,
774
+ packageRoot: profile.packageRoot,
775
+ dshVersion: profile.dshVersion
776
+ });
777
+ } catch (error) {
778
+ throw toDaemonControlError(error);
779
+ }
780
+ }
781
+ /** Resolve the fixed runtime dir for the current user. */
782
+ function runtimeDirOf(deps) {
783
+ return selectRuntimeDir(uidOf(deps));
784
+ }
785
+ /** The narrow local-Host-manager seams this command passes through. */
786
+ function managerDepsOf(deps) {
787
+ const unitDir = deps.unitDir;
788
+ return {
789
+ ...deps.systemctl === void 0 ? {} : { systemctl: deps.systemctl },
790
+ ...unitDir === void 0 ? {} : { unitDir: () => unitDir }
791
+ };
792
+ }
793
+ /** The Darwin launchd adapter inputs; production uses the OS account home and
794
+ * the real `/bin/launchctl`. */
795
+ function launchdDepsOf(deps) {
796
+ return {
797
+ uid: uidOf(deps),
798
+ ...deps.darwinAccountHome === void 0 ? {} : { accountHome: deps.darwinAccountHome },
799
+ ...deps.launchctl === void 0 ? {} : { launchctl: deps.launchctl }
800
+ };
801
+ }
802
+ /** Collect the validated launchd facts for one installed profile. */
803
+ function launchdFactsOf(scope, profile) {
804
+ return collectLaunchdProfileFacts(scope, profile.name, profile.installAnchor);
805
+ }
806
+ /** Map one actual launchd job state onto the stable status vocabulary. */
807
+ function launchdUnitState(state) {
808
+ switch (state) {
809
+ case "running": return "running";
810
+ case "not running": return "not-running";
811
+ case "spawn scheduled": return "spawn-scheduled";
812
+ default: return "unknown";
813
+ }
814
+ }
815
+ /**
816
+ * Read the authenticated Host facts once. No manager query, service definition,
817
+ * current-package walk or Host mutation belongs to this observation.
818
+ */
819
+ async function readHostFacts(scope, deps) {
820
+ const readRecord = deps.readRecord ?? readLocalRecord;
821
+ const inspectProcess = deps.inspectProcess ?? inspectHostProcess;
822
+ let failure;
823
+ let exitCode = 0;
824
+ let host = "stopped";
825
+ let authenticated;
826
+ let hostAuthenticationFailed = false;
827
+ let hostCompatibilityFailed = false;
828
+ let record;
829
+ try {
830
+ record = readRecord(scope);
831
+ } catch (error) {
832
+ if (failure === void 0) {
833
+ failure = toDaemonControlError(error);
834
+ exitCode = failure.exitCode;
835
+ }
836
+ }
837
+ let processAlive = false;
838
+ if (record !== void 0) try {
839
+ processAlive = inspectProcess(record) === "alive";
840
+ } catch (error) {
841
+ if (failure === void 0) {
842
+ failure = toDaemonControlError(error);
843
+ exitCode = failure.exitCode;
844
+ }
845
+ }
846
+ if (processAlive && record !== void 0) {
847
+ let compatibilityFailure;
848
+ try {
849
+ assertClientHostCompatible(record, scope);
850
+ } catch (error) {
851
+ host = "incompatible";
852
+ hostCompatibilityFailed = true;
853
+ compatibilityFailure = toDaemonControlError(error);
854
+ if (failure === void 0) {
855
+ failure = compatibilityFailure;
856
+ exitCode = failure.exitCode;
857
+ }
858
+ }
859
+ if (compatibilityFailure === void 0) try {
860
+ authenticated = await (deps.authenticate ?? authenticateLocalHost)(record, scope);
861
+ host = "ready";
862
+ } catch (error) {
863
+ const mapped = toDaemonControlError(error);
864
+ host = "unresponsive";
865
+ hostAuthenticationFailed = true;
866
+ if (failure === void 0) {
867
+ failure = mapped;
868
+ exitCode = mapped.exitCode;
869
+ }
870
+ }
871
+ }
872
+ return {
873
+ scope,
874
+ record,
875
+ processAlive,
876
+ authenticated,
877
+ hostAuthenticationFailed,
878
+ hostCompatibilityFailed,
879
+ host,
880
+ failure,
881
+ exitCode
882
+ };
883
+ }
884
+ /**
885
+ * Read-only snapshot; `status` and mutating-command pre-flight checks consume it.
886
+ *
887
+ * The installed unit fact is the ONLY manager-IO admission: with no unit file
888
+ * (or no user unit directory) no `systemctl` invocation is made at all, so a
889
+ * missing/broken user manager cannot affect an independent basic Host. With a
890
+ * unit, exactly one `systemctl show` of that unit decides `user-manager` and
891
+ * the unit state. The Host's own registry/authentication chain is always read,
892
+ * even after a unit-identity refusal, so `status` can report a real ready Host
893
+ * beside a foreign unit while still exiting nonzero.
894
+ */
895
+ async function readSnapshot(profile, deps, scope, preadHostFacts) {
896
+ const platform = platformOf(deps);
897
+ let unit;
898
+ let unitState = "not-found";
899
+ /** The manager's raw ActiveState; `unitState` is the coarse presentation. */
900
+ let unitActiveState = "";
901
+ let unitMainPid = 0;
902
+ /** No owned name means no installed definition; other platforms never project this fact. */
903
+ let unitFileState = platform === "linux" ? "not-found" : void 0;
904
+ let userManager = "not-checked";
905
+ let unitInspectionFailure;
906
+ let unitQueryFailure;
907
+ let launchdUnit;
908
+ let launchdService;
909
+ let launchdFacts;
910
+ let launchdInspectionFailure;
911
+ let launchdQueryFailure;
912
+ if (platform === "linux") {
913
+ const systemctl = deps.systemctl ?? runSystemctl;
914
+ const runtimeDir = runtimeDirOf(deps);
915
+ try {
916
+ const inspected = inspectOwnedProfileUnit(scope, profile.name, deps.unitDir);
917
+ if (inspected.kind === "owned") {
918
+ unit = inspected;
919
+ unitInspectionFailure = void 0;
920
+ try {
921
+ const state = await queryOwnedProfileUnit(inspected, runtimeDir, systemctl);
922
+ userManager = "available";
923
+ unitMainPid = state.mainPid;
924
+ unitFileState = state.unitFileState === "" ? "unknown" : state.unitFileState;
925
+ unitActiveState = state.loadState === "not-found" ? "" : state.activeState;
926
+ unitState = state.loadState === "not-found" ? "not-found" : state.activeState === "active" ? "active" : state.activeState === "inactive" || state.activeState === "failed" ? "inactive" : "unknown";
927
+ } catch (error) {
928
+ userManager = "error";
929
+ unitQueryFailure = toDaemonControlError(error);
930
+ unitState = "unknown";
931
+ unitFileState = "unknown";
932
+ }
933
+ }
934
+ } catch (error) {
935
+ unitInspectionFailure = toDaemonControlError(error);
936
+ unitState = "unknown";
937
+ unitFileState = "unknown";
938
+ }
939
+ } else if (platform === "darwin") try {
940
+ launchdFacts = launchdFactsOf(scope, profile);
941
+ const launchdDeps = launchdDepsOf(deps);
942
+ const inspected = inspectOwnedLaunchdUnit(launchdFacts, launchdDeps);
943
+ if (inspected.kind === "owned") {
944
+ launchdUnit = inspected.unit;
945
+ try {
946
+ launchdService = await inspectLaunchdService(inspected.unit, launchdDeps);
947
+ userManager = "available";
948
+ if (launchdService.kind === "not-loaded") unitState = "not-found";
949
+ else if (launchdService.kind === "loaded") {
950
+ const service = launchdService.service;
951
+ unitActiveState = service.state;
952
+ unitState = launchdUnitState(service.state);
953
+ unitMainPid = service.pid ?? 0;
954
+ if (!launchdServiceMatches(launchdFacts, inspected.unit, service)) launchdQueryFailure = new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the loaded launchd job does not match the installed profile plist");
955
+ } else {
956
+ userManager = "error";
957
+ unitState = "unknown";
958
+ launchdQueryFailure = new DaemonControlError("MANAGER_OR_OS_FAILURE", "the loaded launchd job state is not recognizable");
959
+ }
960
+ } catch (error) {
961
+ userManager = "error";
962
+ unitState = "unknown";
963
+ launchdQueryFailure = toDaemonControlError(error);
964
+ }
965
+ }
966
+ } catch (error) {
967
+ launchdInspectionFailure = toDaemonControlError(error);
968
+ unitState = "unknown";
969
+ }
970
+ const managerFailure = unitInspectionFailure ?? unitQueryFailure ?? launchdInspectionFailure ?? launchdQueryFailure;
971
+ const hostFacts = preadHostFacts ?? await readHostFacts(scope, deps);
972
+ let failure = managerFailure ?? hostFacts.failure;
973
+ let exitCode = managerFailure?.exitCode ?? hostFacts.exitCode;
974
+ let host = hostFacts.host;
975
+ const { record, processAlive, authenticated, hostAuthenticationFailed, hostCompatibilityFailed } = hostFacts;
976
+ let manager = "unmanaged";
977
+ if (authenticated !== void 0 && record !== void 0) {
978
+ if (platform === "darwin") {
979
+ if (launchdUnit === void 0) manager = "process";
980
+ else if (launchdInspectionFailure !== void 0 || launchdQueryFailure !== void 0 || launchdService === void 0) manager = "unmanaged";
981
+ else if (launchdService.kind === "loaded") {
982
+ const service = launchdService.service;
983
+ if (service.state === "running") {
984
+ if (service.pid === void 0) {
985
+ manager = "unmanaged";
986
+ if (failure === void 0) {
987
+ failure = new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job reports running without a PID");
988
+ exitCode = failure.exitCode;
989
+ }
990
+ } else if (service.pid === record.hostPid) manager = "launchd";
991
+ else {
992
+ manager = "process";
993
+ if (failure === void 0) {
994
+ failure = new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the launchd job PID is not the authenticated Host; use launchctl for this custom service");
995
+ exitCode = failure.exitCode;
996
+ }
997
+ }
998
+ } else if (service.state === "spawn scheduled") {
999
+ manager = "unmanaged";
1000
+ if (failure === void 0) {
1001
+ failure = new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job is still starting beside a live Host");
1002
+ exitCode = failure.exitCode;
1003
+ }
1004
+ } else if (service.state === "not running") manager = "process";
1005
+ else {
1006
+ manager = "unmanaged";
1007
+ if (failure === void 0) {
1008
+ failure = new DaemonControlError("TRANSITION_UNCERTAIN", `the launchd job is in an unconfirmed state (${service.state === "" ? "unknown" : service.state})`);
1009
+ exitCode = failure.exitCode;
1010
+ }
1011
+ }
1012
+ } else manager = "process";
1013
+ } else {
1014
+ const loaded = unit !== void 0 && unitState !== "not-found";
1015
+ const running = unitActiveState === "active" || unitActiveState === "activating";
1016
+ const ended = unitActiveState === "inactive" || unitActiveState === "failed";
1017
+ if (unitInspectionFailure !== void 0 || unitQueryFailure !== void 0) manager = "unmanaged";
1018
+ else if (loaded && running) {
1019
+ if (unitMainPid === record.hostPid) manager = "systemd";
1020
+ else {
1021
+ manager = "process";
1022
+ if (failure === void 0) {
1023
+ failure = new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the unit MainPID is not the authenticated Host; use systemctl --user for this custom service");
1024
+ exitCode = failure.exitCode;
1025
+ }
1026
+ }
1027
+ } else if (loaded && !ended) {
1028
+ manager = "unmanaged";
1029
+ if (failure === void 0) {
1030
+ failure = new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState})`);
1031
+ exitCode = failure.exitCode;
1032
+ }
1033
+ } else manager = "process";
1034
+ }
1035
+ } else if (record === void 0 || !processAlive) {
1036
+ if (platform === "darwin") {
1037
+ if (launchdUnit !== void 0 && launchdService?.kind === "loaded") {
1038
+ const state = launchdService.service.state;
1039
+ if (state === "running" || state === "spawn scheduled") host = "starting";
1040
+ else if (state === "not running") host = "stopped";
1041
+ else {
1042
+ host = "unknown";
1043
+ if (failure === void 0) {
1044
+ failure = new DaemonControlError("TRANSITION_UNCERTAIN", `the launchd job is in an unconfirmed state (${state === "" ? "unknown" : state})`);
1045
+ exitCode = failure.exitCode;
1046
+ }
1047
+ }
1048
+ }
1049
+ } else {
1050
+ const loaded = unit !== void 0 && unitState !== "not-found";
1051
+ if (loaded && (unitActiveState === "active" || unitActiveState === "activating")) host = "starting";
1052
+ else if (loaded && unitActiveState !== "inactive" && unitActiveState !== "failed") {
1053
+ host = "unknown";
1054
+ if (failure === void 0) {
1055
+ failure = new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState})`);
1056
+ exitCode = failure.exitCode;
1057
+ }
1058
+ }
1059
+ }
1060
+ }
1061
+ if (failure !== void 0 && host === "stopped") host = "unknown";
1062
+ return {
1063
+ unit,
1064
+ launchdUnit,
1065
+ launchdService,
1066
+ launchdFacts,
1067
+ launchdInspectionFailure,
1068
+ launchdQueryFailure,
1069
+ userManager,
1070
+ unitInspectionFailure,
1071
+ unitQueryFailure,
1072
+ unitState,
1073
+ unitActiveState,
1074
+ unitMainPid,
1075
+ ...hostFacts,
1076
+ host,
1077
+ status: {
1078
+ profile: profile.name,
1079
+ manager,
1080
+ userManager,
1081
+ host,
1082
+ unit: platform === "darwin" ? launchdUnit === void 0 ? "none" : launchdUnit.label : unit === void 0 ? "none" : unit.unitName,
1083
+ unitState,
1084
+ ...unitFileState === void 0 ? {} : { unitFileState },
1085
+ compatibility: host === "ready" ? "compatible" : host === "incompatible" ? "incompatible" : host === "stopped" || host === "starting" ? "none" : "unknown",
1086
+ ...processAlive && record !== void 0 ? { pid: record.hostPid } : {},
1087
+ ...processAlive && record !== void 0 ? { instance: record.instanceId.slice(0, 8) } : {}
1088
+ },
1089
+ exitCode,
1090
+ failure
1091
+ };
1092
+ }
1093
+ /** The stable `key=value` status block (no secret or private path). */
1094
+ function formatDaemonStatus(status) {
1095
+ const lines = [
1096
+ `profile=${status.profile.replace(/[\u0000-\u001f\u007f]/gu, "")}`,
1097
+ `manager=${status.manager}`,
1098
+ `user-manager=${status.userManager}`,
1099
+ `host=${status.host}`,
1100
+ `unit=${status.unit}`,
1101
+ `unit-state=${status.unitState}`,
1102
+ ...status.unitFileState === void 0 ? [] : [`unit-file-state=${status.unitFileState.replace(/[\u0000-\u001f\u007f]/gu, "")}`],
1103
+ `compatibility=${status.compatibility}`
1104
+ ];
1105
+ if (status.pid !== void 0) lines.push(`pid=${String(status.pid)}`);
1106
+ if (status.instance !== void 0) lines.push(`instance=${status.instance}`);
1107
+ if (status.acp !== void 0) lines.push(`acp=${status.acp}`);
1108
+ if (status.acpSocket !== void 0) lines.push(`acp-socket=${status.acpSocket}`);
1109
+ return `${lines.join("\n")}\n`;
1110
+ }
1111
+ /** Format one status result without changing the command's success semantics. */
1112
+ function statusResult(snapshot, extras = {}, options = {}) {
1113
+ const failure = options.commandSuccess === true || snapshot.failure === void 0 ? "" : formatDaemonControlError(snapshot.failure);
1114
+ return {
1115
+ code: options.commandSuccess === true ? 0 : snapshot.exitCode,
1116
+ stdout: formatDaemonStatus({
1117
+ ...snapshot.status,
1118
+ ...extras
1119
+ }),
1120
+ stderr: `${failure}${options.extraStderr ?? ""}`
1121
+ };
1122
+ }
1123
+ /**
1124
+ * Acquire the ONE profile-scoped admin seat for a mutating verb. The seat is
1125
+ * held for exactly the lifetime of THIS command's operation: two concurrently
1126
+ * running management commands of the same Profile cannot interleave, and the
1127
+ * kernel releases the claim when the process exits. Linux keeps its abstract
1128
+ * socket name; Darwin claims the existing `admin` `O_EXLOCK` file beside the
1129
+ * Host singleton seat. There is no persistent lock file and no in-memory shadow
1130
+ * of OS operations — a command that dies with the process releases the seat,
1131
+ * and the next command re-reads the real systemd/Host state.
1132
+ */
1133
+ async function withAdminSeat(scope, deps, operation) {
1134
+ let seat;
1135
+ try {
1136
+ if (platformOf(deps) === "linux") seat = await bindProcessSeat(`${ADMIN_SEAT_PREFIX}${scope.scopeId.slice(0, 40)}`, "DAEMON_CONTROL_BUSY");
1137
+ else if (platformOf(deps) === "win32") seat = await bindProfileKernelSeat(scope, "admin", "DAEMON_CONTROL_BUSY");
1138
+ else seat = await bindDarwinKernelSeat(darwinHostProfileSeatDir(scope.scopeId, deps.darwinAccountHome), scope.scopeId, "admin", "DAEMON_CONTROL_BUSY");
1139
+ } catch (error) {
1140
+ throw toDaemonControlError(error);
1141
+ }
1142
+ try {
1143
+ return await operation();
1144
+ } finally {
1145
+ await seat.close();
1146
+ }
1147
+ }
1148
+ /** A live Host authentication or compatibility failure is a diagnosis, not a
1149
+ * unit-ownership verdict. A verified current-Profile service remains
1150
+ * manageable through the manager; every other snapshot failure keeps its
1151
+ * normal admission. The product never auto-recovers — this only permits an
1152
+ * explicit user command. */
1153
+ function verifiedUnitManagementAdmitted(snapshot) {
1154
+ return (snapshot.hostAuthenticationFailed || snapshot.hostCompatibilityFailed) && snapshot.unit !== void 0 && snapshot.userManager === "available";
1155
+ }
1156
+ /** The same admission for a verified launchd job whose real PID is the live
1157
+ * Host record (or whose job state proves no process is running). */
1158
+ function verifiedLaunchdManagementAdmitted(snapshot) {
1159
+ const { launchdUnit, launchdFacts, launchdService, record, processAlive } = snapshot;
1160
+ if (launchdUnit === void 0 || launchdFacts === void 0 || launchdService?.kind !== "loaded") return false;
1161
+ if (!launchdServiceMatches(launchdFacts, launchdUnit, launchdService.service)) return false;
1162
+ if (!processAlive || record === void 0) return true;
1163
+ return launchdService.service.pid !== void 0 && launchdService.service.pid === record.hostPid;
1164
+ }
1165
+ /** A stable local error for an unknown Host state. */
1166
+ function refuseHostState(status) {
1167
+ if (status.host === "incompatible") return new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the live Host uses an incompatible protocol or DSH runtime");
1168
+ if (status.host === "unresponsive") return new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the live Host could not prove its authenticated identity");
1169
+ return new DaemonControlError("TRANSITION_UNCERTAIN", `the Host is ${status.host}; refusing to change supervision`);
1170
+ }
1171
+ /** The bounded post-stop wait for the original Host's terminal state. Linux
1172
+ * uses the discovery classifier's gone/different-birth/terminal-state verdict;
1173
+ * Darwin requires the recorded schema-2 identity to become `gone`/`different`.
1174
+ * An `unknown` kernel read is uncertainty and never proves a stop. */
1175
+ async function waitForHostStopped(record, mainPid, deps) {
1176
+ const now = deps.now ?? Date.now;
1177
+ const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1178
+ const deadline = now() + (deps.stopTimeoutMs ?? 2e4);
1179
+ if (platformOf(deps) === "darwin") {
1180
+ if (record === void 0 || record.schema !== 2) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host kernel identity is unavailable for the stop proof");
1181
+ const readKernel = deps.readKernel ?? readKernelProcess;
1182
+ for (;;) {
1183
+ const classification = sameKernelProcess(record.hostKernelIdentity, readKernel(record.hostPid));
1184
+ if (classification === "gone" || classification === "different") return;
1185
+ if (now() >= deadline) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the old Host process did not exit within the bounded window");
1186
+ await sleep(100);
1187
+ }
1188
+ }
1189
+ const readStarttime = deps.readStarttime ?? ((pid) => {
1190
+ try {
1191
+ return readLinuxStarttime(pid);
1192
+ } catch {
1193
+ return;
1194
+ }
1195
+ });
1196
+ const inspectProcess = deps.inspectProcess ?? inspectHostProcess;
1197
+ for (;;) {
1198
+ if (record !== void 0 ? inspectProcess(record) === "dead" : mainPid === 0 || readStarttime(mainPid) === void 0) return;
1199
+ if (now() >= deadline) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the old Host process did not exit within the bounded window");
1200
+ await sleep(100);
1201
+ }
1202
+ }
1203
+ /** Reject an obviously non-Host command before signalling the authenticated PID. */
1204
+ function assertProcessHostOwnership(record, deps) {
1205
+ const cmdline = (deps.readCmdline ?? ((pid) => {
1206
+ try {
1207
+ return readFileString(`/proc/${String(pid)}/cmdline`);
1208
+ } catch {
1209
+ return;
1210
+ }
1211
+ }))(record.hostPid);
1212
+ if (cmdline === void 0 || cmdline === "") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host process command line is unavailable");
1213
+ const entry = cmdline.split("\0").filter((part) => part !== "")[1];
1214
+ 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");
1215
+ }
1216
+ /** Bounded read-to-EOF for procfs text files: `/proc` entries report
1217
+ * `st_size = 0` even when the content is readable, so the length must come
1218
+ * from reading until EOF under an explicit byte cap, never from `fstat.size`. */
1219
+ function readFileString(path) {
1220
+ const fd = openSync(path, constants.O_RDONLY);
1221
+ try {
1222
+ const chunks = [];
1223
+ let total = 0;
1224
+ for (;;) {
1225
+ const chunk = Buffer.alloc(4096);
1226
+ const read = readSync(fd, chunk, 0, chunk.length, null);
1227
+ if (read <= 0) break;
1228
+ total += read;
1229
+ if (total > 65536) throw new Error("unexpected process command line size");
1230
+ chunks.push(read === chunk.length ? chunk : chunk.subarray(0, read));
1231
+ }
1232
+ return Buffer.concat(chunks).toString("utf8");
1233
+ } finally {
1234
+ closeSync(fd);
1235
+ }
1236
+ }
1237
+ /** Stop one live independent authenticated Host through exactly one verified
1238
+ * POSIX SIGTERM (Linux procfs identity or Darwin schema-2 kernel identity). */
1239
+ async function stopIndependentHost(snapshot, deps) {
1240
+ const record = snapshot.record;
1241
+ if (record === void 0) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host registry disappeared before the stop");
1242
+ const authenticate = deps.authenticate ?? authenticateLocalHost;
1243
+ try {
1244
+ await authenticate(record, snapshot.scope);
1245
+ } catch (error) {
1246
+ throw toDaemonControlError(error);
1247
+ }
1248
+ if (platformOf(deps) === "darwin") try {
1249
+ assertRecordedHostKernelIdentityCurrent(record, deps.readKernel ?? readKernelProcess, "darwin");
1250
+ } catch (error) {
1251
+ throw toDaemonControlError(error);
1252
+ }
1253
+ else {
1254
+ assertProcessHostOwnership(record, deps);
1255
+ const readStarttime = deps.readStarttime ?? ((pid) => {
1256
+ try {
1257
+ return readLinuxStarttime(pid);
1258
+ } catch {
1259
+ return;
1260
+ }
1261
+ });
1262
+ 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");
1263
+ }
1264
+ assertNotAborted(deps.signal);
1265
+ const kill = deps.kill ?? process.kill;
1266
+ try {
1267
+ kill(record.hostPid, "SIGTERM");
1268
+ } catch (error) {
1269
+ throw new DaemonControlError("MANAGER_OR_OS_FAILURE", "the verified Host process could not be signalled", error);
1270
+ }
1271
+ try {
1272
+ await waitForHostStopped(record, record.hostPid, deps);
1273
+ } catch (error) {
1274
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop");
1275
+ }
1276
+ }
1277
+ /**
1278
+ * Stop the snapshot's Host and prove the original instance is gone.
1279
+ *
1280
+ * Linux routing follows the authenticated attribution, never the mere presence
1281
+ * of a systemd user bus:
1282
+ * - a loaded active/activating unit whose MainPID IS the authenticated Host is
1283
+ * stopped through that unit and its exit is awaited;
1284
+ * - an independent authenticated Host (no unit, or a loaded unit that systemd
1285
+ * reports as inactive/failed/not-found) is re-authenticated, its platform
1286
+ * ownership proof (Linux procfs starttime + Host entry command shape, Darwin
1287
+ * schema-2 kernel identity) is re-checked, and exactly that PID receives one
1288
+ * SIGTERM;
1289
+ * - a live Host beside an active unit with a different MainPID, a unit in flux,
1290
+ * or an unreadable manager is refused WITHOUT trying the other stop method.
1291
+ *
1292
+ * Darwin routing uses the verified LaunchAgent instead of a systemd unit: a
1293
+ * loaded job whose fixed launch facts match this profile and whose real PID is
1294
+ * the authenticated Host is stopped only through `bootout`; a job that is
1295
+ * loaded but not running is booted out without a signal; anything transitional,
1296
+ * foreign or unreadable is refused.
1297
+ */
1298
+ async function stopFromSnapshot(snapshot, deps) {
1299
+ if (platformOf(deps) === "win32") return await stopWin32FromSnapshot(snapshot, deps);
1300
+ if (platformOf(deps) === "darwin") return await stopDarwinFromSnapshot(snapshot, deps);
1301
+ const { unit, unitState, unitActiveState, unitMainPid, record, processAlive } = snapshot;
1302
+ const systemctl = deps.systemctl ?? runSystemctl;
1303
+ const liveHost = processAlive && record !== void 0;
1304
+ const loaded = unit !== void 0 && unitState !== "not-found";
1305
+ const running = loaded && (unitActiveState === "active" || unitActiveState === "activating");
1306
+ const ended = loaded && (unitActiveState === "inactive" || unitActiveState === "failed");
1307
+ if (snapshot.userManager === "error") throw snapshot.unitQueryFailure ?? new DaemonControlError("MANAGER_OR_OS_FAILURE", "the user manager cannot verify the profile unit");
1308
+ if (liveHost) {
1309
+ if (running) {
1310
+ 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");
1311
+ assertNotAborted(deps.signal);
1312
+ await stopOwnedProfileUnit(unit, runtimeDirOf(deps), systemctl, deps.stopTimeoutMs);
1313
+ try {
1314
+ await waitForHostStopped(record, unitMainPid, deps);
1315
+ } catch (error) {
1316
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop");
1317
+ }
1318
+ return;
1319
+ }
1320
+ if (loaded && !ended) throw new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState}); refusing to signal the Host`);
1321
+ if (!running) {
1322
+ await stopIndependentHost(snapshot, deps);
1323
+ return;
1324
+ }
1325
+ }
1326
+ if (loaded) {
1327
+ if (!ended && !running) throw new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState}); refusing to change supervision`);
1328
+ if (unit === void 0) return;
1329
+ assertNotAborted(deps.signal);
1330
+ await stopOwnedProfileUnit(unit, runtimeDirOf(deps), systemctl, deps.stopTimeoutMs);
1331
+ try {
1332
+ await waitForHostStopped(void 0, unitMainPid, deps);
1333
+ } catch (error) {
1334
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop");
1335
+ }
1336
+ }
1337
+ }
1338
+ /**
1339
+ * The Windows stop route: one exact held process handle and one exact
1340
+ * per-instance Event. The original handle is the terminal authority; the
1341
+ * Event only delivers the existing stop(0) request to the Host entry.
1342
+ */
1343
+ async function stopWin32FromSnapshot(snapshot, deps) {
1344
+ const record = snapshot.record;
1345
+ if (!snapshot.processAlive || record === void 0) return;
1346
+ if (record.schema !== 3) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host registry is not a Windows kernel identity");
1347
+ const authenticated = snapshot.authenticated;
1348
+ if (authenticated === void 0 || authenticated.identity.instanceId !== record.instanceId || authenticated.identity.hostPid !== record.hostPid) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the authenticated Host is not the recorded instance");
1349
+ const opened = openWin32Process(record.hostPid);
1350
+ if (opened.kind === "gone") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the recorded Host process is no longer alive");
1351
+ if (opened.kind === "unknown") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the recorded Host process identity cannot be verified");
1352
+ const capture = opened.capture;
1353
+ try {
1354
+ if (capture.identity.ownerSid !== record.hostKernelIdentity.ownerSid || capture.identity.creationFiletime !== record.hostKernelIdentity.creationFiletime) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the opened process is not the recorded Host instance");
1355
+ const currentRecord = (deps.readRecord ?? readLocalRecord)(snapshot.scope);
1356
+ if (currentRecord === void 0 || !sameLocalInstanceRecord(currentRecord, record)) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host registry changed before the stop dispatch");
1357
+ if ((await waitWin32Handle(capture.handle, 0)).kind !== "timeout") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the recorded Host process is not alive for the stop dispatch");
1358
+ assertNotAborted(deps.signal);
1359
+ let event;
1360
+ try {
1361
+ event = openWin32StopSignal(snapshot.scope.scopeId, record.instanceId);
1362
+ } catch (error) {
1363
+ throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the per-instance stop event is unavailable", error);
1364
+ }
1365
+ try {
1366
+ event.setOnce();
1367
+ } finally {
1368
+ event.close();
1369
+ }
1370
+ if ((await waitWin32Handle(capture.handle, deps.stopTimeoutMs ?? 2e4)).kind !== "terminal") throw afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", "the old Host process did not reach its original handle terminal within the bounded window"), "Host stop");
1371
+ try {
1372
+ const postRecord = (deps.readRecord ?? readLocalRecord)(snapshot.scope);
1373
+ if (postRecord !== void 0 && (deps.inspectProcess ?? inspectHostProcess)(postRecord) === "alive") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the Host registry still reports a live process after stop");
1374
+ } catch (error) {
1375
+ if (error instanceof DaemonControlError) throw afterCommittedAction(error, "Host stop");
1376
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop");
1377
+ }
1378
+ } finally {
1379
+ closeWin32Handle(capture.handle);
1380
+ }
1381
+ }
1382
+ /** The Darwin stop route: verified LaunchAgent bootout or one verified SIGTERM. */
1383
+ async function stopDarwinFromSnapshot(snapshot, deps) {
1384
+ const { launchdUnit, launchdFacts, launchdService, record, processAlive } = snapshot;
1385
+ if (snapshot.launchdInspectionFailure !== void 0) throw snapshot.launchdInspectionFailure;
1386
+ if (snapshot.launchdQueryFailure !== void 0) throw snapshot.launchdQueryFailure;
1387
+ const loaded = launchdService?.kind === "loaded" ? launchdService.service : void 0;
1388
+ if (launchdService?.kind === "unknown") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job state is not recognizable; refusing to change supervision");
1389
+ if (launchdUnit !== void 0 && launchdFacts === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job facts are unavailable; refusing to change supervision");
1390
+ 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");
1391
+ const liveHost = processAlive && record !== void 0;
1392
+ if (liveHost && launchdUnit !== void 0 && launchdFacts !== void 0 && loaded !== void 0) {
1393
+ if (loaded.state === "running") {
1394
+ if (loaded.pid === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job reports running without a PID; refusing to signal the Host");
1395
+ 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");
1396
+ assertNotAborted(deps.signal);
1397
+ await stopLaunchdService(launchdFacts, launchdUnit, launchdDepsOf(deps), record.hostPid);
1398
+ try {
1399
+ await waitForHostStopped(record, loaded.pid, deps);
1400
+ } catch (error) {
1401
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop");
1402
+ }
1403
+ return;
1404
+ }
1405
+ 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");
1406
+ 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`);
1407
+ }
1408
+ if (liveHost) {
1409
+ await stopIndependentHost(snapshot, deps);
1410
+ return;
1411
+ }
1412
+ if (loaded !== void 0) {
1413
+ if (launchdUnit === void 0 || launchdFacts === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job facts are unavailable; refusing to change supervision");
1414
+ 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");
1415
+ if (loaded.state === "not running") {
1416
+ assertNotAborted(deps.signal);
1417
+ await stopLaunchdService(launchdFacts, launchdUnit, launchdDepsOf(deps));
1418
+ return;
1419
+ }
1420
+ throw new DaemonControlError("TRANSITION_UNCERTAIN", `the launchd job is in an unconfirmed state (${loaded.state === "" ? "unknown" : loaded.state}); refusing to change supervision`);
1421
+ }
1422
+ if (snapshot.launchdQueryFailure !== void 0) throw snapshot.launchdQueryFailure;
1423
+ }
1424
+ /**
1425
+ * The public local endpoint of this profile scope: the POSIX UDS logical path or
1426
+ * the Windows Named Pipe (never the macOS private bind name). The value is a
1427
+ * single safe `key=value` line or it is omitted: a malformed path is never
1428
+ * sanitized into a fake connectable address.
1429
+ */
1430
+ function acpSocketPathOf(scope, deps) {
1431
+ const platform = platformOf(deps);
1432
+ if (platform === "win32") return acpPipeAddress(scope.scopeId);
1433
+ const path = platform === "darwin" ? darwinAcpSocketPaths(scope, uidOf(deps)).publicPath : join(scope.dir, "acp.sock");
1434
+ if (!path.startsWith("/") || /[\u0000-\u001f\u007f]/u.test(path)) return void 0;
1435
+ return path;
1436
+ }
1437
+ /**
1438
+ * Derive the `acp` field from the ONE authenticated read-only observation. Only
1439
+ * an authenticated `host=ready` snapshot is read at all; every unprovable
1440
+ * outcome is `unavailable` and NEVER a guessed `disabled`. The ACP facts never
1441
+ * change the original exit code, stderr or manager/Host classification.
1442
+ */
1443
+ async function observeAcpFacts(host, scope, deps) {
1444
+ if (host.authenticated === void 0 || host.host !== "ready") return { acp: "unavailable" };
1445
+ const status = await (deps.observeAcpStatus ?? observeAuthenticatedLocalAcpStatus)(host.authenticated);
1446
+ if (status === void 0) return { acp: "unavailable" };
1447
+ switch (status.state) {
1448
+ case "enabled": {
1449
+ const socket = acpSocketPathOf(scope, deps);
1450
+ return socket === void 0 ? { acp: "enabled" } : {
1451
+ acp: "enabled",
1452
+ acpSocket: socket
1453
+ };
1454
+ }
1455
+ case "disabled": return { acp: "disabled" };
1456
+ case "changing":
1457
+ case "unavailable": return { acp: "unavailable" };
1458
+ }
1459
+ }
1460
+ /**
1461
+ * The ONE read-only target seam for the trusted-profile ACP stdio bridge. It
1462
+ * runs the same scope inspection, authenticated Host observation and ACP
1463
+ * listener observation as `daemon status` without querying the service manager,
1464
+ * then returns either the public local endpoint
1465
+ * (POSIX UDS path or Windows Named Pipe) plus the exact authenticated Host
1466
+ * instance identity, or one fixed rejection category. It never starts a Host, changes listener state or
1467
+ * persists a target.
1468
+ */
1469
+ async function readAcpStdioTarget(profile, signal, deps = {}) {
1470
+ signal?.throwIfAborted();
1471
+ const effectiveDeps = signal === void 0 ? deps : {
1472
+ ...deps,
1473
+ signal
1474
+ };
1475
+ const scope = inspectScope(profile, effectiveDeps);
1476
+ signal?.throwIfAborted();
1477
+ const host = await readHostFacts(scope, effectiveDeps);
1478
+ signal?.throwIfAborted();
1479
+ if (host.host !== "ready" || host.authenticated === void 0) return { kind: "host-unavailable" };
1480
+ const acp = await observeAcpFacts(host, scope, effectiveDeps);
1481
+ signal?.throwIfAborted();
1482
+ if (acp.acp === "disabled") return { kind: "acp-disabled" };
1483
+ if (acp.acp !== "enabled" || acp.acpSocket === void 0) return { kind: "acp-unavailable" };
1484
+ return {
1485
+ kind: "ready",
1486
+ socketPath: acp.acpSocket,
1487
+ instanceId: host.authenticated.identity.instanceId
1488
+ };
1489
+ }
1490
+ /** The `status` handler. */
1491
+ async function runStatus(profile, deps) {
1492
+ const snapshot = await readSnapshot(profile, deps, inspectScope(profile, deps));
1493
+ return statusResult(snapshot, await observeAcpFacts(snapshot, snapshot.scope, deps));
1494
+ }
1495
+ /** The `start` handler. */
1496
+ async function runStart(profile, deps) {
1497
+ const inspected = inspectScope(profile, deps);
1498
+ return await withAdminSeat(inspected, deps, async () => {
1499
+ const hostFacts = await readHostFacts(inspected, deps);
1500
+ if (hostFacts.host === "ready" && hostFacts.authenticated !== void 0) {
1501
+ if (hostFacts.failure !== void 0) throw hostFacts.failure;
1502
+ return {
1503
+ code: 0,
1504
+ stdout: `profile=${profile.name.replace(/[\u0000-\u001f\u007f]/gu, "")}\nhost=ready\ncompatibility=compatible\npid=${String(hostFacts.authenticated.record.hostPid)}\ninstance=${hostFacts.authenticated.identity.instanceId.slice(0, 8)}\n`,
1505
+ stderr: ""
1506
+ };
1507
+ }
1508
+ if (hostFacts.failure !== void 0) throw hostFacts.failure;
1509
+ if (hostFacts.host !== "stopped" && hostFacts.host !== "starting") throw refuseHostState(hostFacts);
1510
+ const pre = await readSnapshot(profile, deps, inspected, hostFacts);
1511
+ if (pre.failure !== void 0) throw pre.failure;
1512
+ assertNotAborted(deps.signal);
1513
+ const startScope = pre.unit !== void 0 || pre.launchdUnit !== void 0 ? ensureInstalledProfileScopeDirectory(inspected) : ensureInstalledProfileScopeDirectory(materializeBuild(inspected, profile.packageRoot));
1514
+ assertNotAborted(deps.signal);
1515
+ const ensureHost = deps.ensureHost ?? ensureLocalHost;
1516
+ try {
1517
+ await ensureHost({
1518
+ scope: startScope,
1519
+ hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
1520
+ dshAnchor: profile.installAnchor,
1521
+ profile: profile.name,
1522
+ hostStartPolicy: "public"
1523
+ });
1524
+ } catch (error) {
1525
+ throw toDaemonControlError(error);
1526
+ }
1527
+ try {
1528
+ const post = await readSnapshot(profile, deps, startScope);
1529
+ if (post.failure !== void 0) throw post.failure;
1530
+ if (post.status.host !== "ready") throw refuseHostState(post.status);
1531
+ return statusResult(post, {}, { commandSuccess: true });
1532
+ } catch (error) {
1533
+ throw afterCommittedAction(toDaemonControlError(error), "Host start");
1534
+ }
1535
+ });
1536
+ }
1537
+ /** The `stop` handler. */
1538
+ async function runStop(profile, deps) {
1539
+ const inspected = inspectScope(profile, deps);
1540
+ return await withAdminSeat(inspected, deps, async () => {
1541
+ const pre = await readSnapshot(profile, deps, inspected);
1542
+ if (pre.failure !== void 0 && !verifiedUnitManagementAdmitted(pre) && !verifiedLaunchdManagementAdmitted(pre)) throw pre.failure;
1543
+ assertNotAborted(deps.signal);
1544
+ await stopFromSnapshot(pre, deps);
1545
+ try {
1546
+ const post = await readSnapshot(profile, deps, inspected);
1547
+ if (post.failure !== void 0) throw post.failure;
1548
+ if (post.status.host !== "stopped") throw refuseHostState(post.status);
1549
+ return statusResult(post, {}, {
1550
+ commandSuccess: true,
1551
+ extraStderr: RUNNING_WORK_NOTICE
1552
+ });
1553
+ } catch (error) {
1554
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop");
1555
+ }
1556
+ });
1557
+ }
1558
+ /** The `restart` handler: stop -> confirmed exit -> start. */
1559
+ async function runRestart(profile, deps) {
1560
+ const inspected = inspectScope(profile, deps);
1561
+ return await withAdminSeat(inspected, deps, async () => {
1562
+ const pre = await readSnapshot(profile, deps, inspected);
1563
+ const launchdLoaded = pre.launchdService?.kind === "loaded" ? pre.launchdService.service : void 0;
1564
+ const launchdVerified = pre.launchdUnit !== void 0 && pre.launchdFacts !== void 0 && launchdLoaded !== void 0 && launchdServiceMatches(pre.launchdFacts, pre.launchdUnit, launchdLoaded);
1565
+ const unitFailureRecovery = verifiedUnitManagementAdmitted(pre) && (pre.record === void 0 || !pre.processAlive || pre.unitMainPid === pre.record.hostPid);
1566
+ const launchdFailureRecovery = launchdVerified && (pre.hostAuthenticationFailed || pre.hostCompatibilityFailed) && (pre.record === void 0 || !pre.processAlive || launchdLoaded?.pid === pre.record.hostPid);
1567
+ 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);
1568
+ 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);
1569
+ const serviceFailureRecovery = unitFailureRecovery || launchdFailureRecovery;
1570
+ if (pre.failure !== void 0 && !serviceFailureRecovery) throw pre.failure;
1571
+ if (pre.status.host !== "ready" && pre.status.host !== "stopped" && !serviceFailureRecovery && !verifiedUnitRestart && !verifiedLaunchdRestart) throw refuseHostState(pre.status);
1572
+ const oldInstance = pre.record?.instanceId;
1573
+ const startScope = pre.unit !== void 0 || pre.launchdUnit !== void 0 ? inspected : materializeBuild(inspected, profile.packageRoot);
1574
+ assertNotAborted(deps.signal);
1575
+ await stopFromSnapshot(pre, deps);
1576
+ try {
1577
+ assertNotAborted(deps.signal);
1578
+ const scope = ensureInstalledProfileScopeDirectory(startScope);
1579
+ await (deps.ensureHost ?? ensureLocalHost)({
1580
+ scope,
1581
+ hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
1582
+ dshAnchor: profile.installAnchor,
1583
+ profile: profile.name,
1584
+ hostStartPolicy: "public"
1585
+ });
1586
+ const post = await readSnapshot(profile, deps, scope);
1587
+ if (post.failure !== void 0) throw post.failure;
1588
+ if (post.status.host !== "ready") throw refuseHostState(post.status);
1589
+ 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");
1590
+ if (oldInstance !== void 0 && post.record?.instanceId === oldInstance) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the restart did not produce a new Host instance");
1591
+ return {
1592
+ code: 0,
1593
+ stdout: `previous=${oldInstance === void 0 ? "none" : oldInstance.slice(0, 8)}\n${formatDaemonStatus(post.status)}`,
1594
+ stderr: RUNNING_WORK_NOTICE
1595
+ };
1596
+ } catch (error) {
1597
+ throw afterCommittedAction(toDaemonControlError(error), "Host restart");
1598
+ }
1599
+ });
1600
+ }
1601
+ /** The `install` handler: explicit unit installation only, never host control. */
1602
+ async function runInstall(profile, intent, deps) {
1603
+ const autostart = intent.autostart === true;
1604
+ if (platformOf(deps) === "win32") return await runWindowsInstall(profile, deps);
1605
+ if (platformOf(deps) === "darwin") return await runDarwinInstall(profile, deps, autostart);
1606
+ const inspected = inspectScope(profile, deps);
1607
+ return await withAdminSeat(inspected, deps, async () => {
1608
+ assertNotAborted(deps.signal);
1609
+ const installed = await installProfileHostUnit({
1610
+ scope: inspected,
1611
+ hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
1612
+ dshAnchor: profile.installAnchor,
1613
+ profile: profile.name
1614
+ }, managerDepsOf(deps));
1615
+ return {
1616
+ code: 0,
1617
+ stdout: `profile=${profile.name.replace(/[\u0000-\u001f\u007f]/gu, "")}\nunit=${installed.unitName}\n`,
1618
+ stderr: ""
1619
+ };
1620
+ });
1621
+ }
1622
+ /** The Windows `install --autostart` handler: register the login-only task only. */
1623
+ async function runWindowsInstall(profile, deps) {
1624
+ const inspected = inspectScope(profile, deps);
1625
+ return await withAdminSeat(inspected, deps, async () => {
1626
+ const profileName = profile.name.replace(/[\u0000-\u001f\u007f]/gu, "");
1627
+ const existing = await inspectWindowsLoginTask(inspected);
1628
+ switch (existing.kind) {
1629
+ case "owned": return {
1630
+ code: 0,
1631
+ stdout: `profile=${profileName}\ntask=${existing.taskName}\n`,
1632
+ stderr: WINDOWS_EXISTING_DEFINITION_NOTE
1633
+ };
1634
+ case "foreign": throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the existing Windows login task is not owned by this profile");
1635
+ case "refused": throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Windows login task cannot be managed in this user context");
1636
+ case "os-failure": throw new DaemonControlError("MANAGER_OR_OS_FAILURE", existing.reason);
1637
+ }
1638
+ assertNotAborted(deps.signal);
1639
+ const created = await createWindowsLoginTask(inspected, profile);
1640
+ switch (created.kind) {
1641
+ case "created": return {
1642
+ code: 0,
1643
+ stdout: `profile=${profileName}\ntask=${created.taskName}\n`,
1644
+ stderr: ""
1645
+ };
1646
+ case "reused": return {
1647
+ code: 0,
1648
+ stdout: `profile=${profileName}\ntask=${created.taskName}\n`,
1649
+ stderr: WINDOWS_EXISTING_DEFINITION_NOTE
1650
+ };
1651
+ case "foreign": throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "a foreign Windows login task already exists");
1652
+ case "refused": throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Windows login task cannot be created in this user context");
1653
+ case "uncertain": throw new DaemonControlError("TRANSITION_UNCERTAIN", "the Windows login task creation may already have been committed; check the native Task Scheduler for the exact task");
1654
+ case "os-failure": throw new DaemonControlError("MANAGER_OR_OS_FAILURE", created.reason);
1655
+ }
1656
+ });
1657
+ }
1658
+ /** The Windows `uninstall` handler: remove only the login task; never the Host. */
1659
+ async function runWindowsUninstall(profile, deps) {
1660
+ const inspected = inspectScope(profile, deps);
1661
+ return await withAdminSeat(inspected, deps, async () => {
1662
+ assertNotAborted(deps.signal);
1663
+ const result = await uninstallWindowsLoginTask(inspected, profile);
1664
+ const profileName = profile.name.replace(/[\u0000-\u001f\u007f]/gu, "");
1665
+ switch (result.kind) {
1666
+ case "absent":
1667
+ case "deleted": return {
1668
+ code: 0,
1669
+ stdout: `profile=${profileName}\ntask=none\n`,
1670
+ stderr: ""
1671
+ };
1672
+ case "refused": throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Windows login task is not owned by this profile");
1673
+ case "busy":
1674
+ case "uncertain": throw new DaemonControlError("TRANSITION_UNCERTAIN", result.reason);
1675
+ case "os-failure": throw new DaemonControlError("MANAGER_OR_OS_FAILURE", result.reason);
1676
+ }
1677
+ });
1678
+ }
1679
+ /** The current user's real Linger setting, or undefined when it cannot be confirmed. */
1680
+ function queryLingerState(uid) {
1681
+ return new Promise((resolve) => {
1682
+ execFile("loginctl", [
1683
+ "show-user",
1684
+ String(uid),
1685
+ "-p",
1686
+ "Linger",
1687
+ "--value"
1688
+ ], {
1689
+ timeout: 3e3,
1690
+ maxBuffer: 4096,
1691
+ encoding: "utf8"
1692
+ }, (error, stdout) => {
1693
+ if (error !== null) {
1694
+ resolve(void 0);
1695
+ return;
1696
+ }
1697
+ const value = stdout.trim();
1698
+ resolve(value === "yes" || value === "no" ? value : void 0);
1699
+ });
1700
+ });
1701
+ }
1702
+ /**
1703
+ * The Linux-only `enable`/`disable` handler. It acts on this Profile's already
1704
+ * installed and manager-verified unit through ONE native request; enablement
1705
+ * never starts, stops or rewrites the Host or its definition.
1706
+ */
1707
+ async function runUnitEnablement(profile, verb, deps) {
1708
+ if (platformOf(deps) !== "linux") throw new DaemonControlError("UNSUPPORTED_PLATFORM", `daemon ${verb} requires Linux systemd`);
1709
+ const inspected = inspectScope(profile, deps);
1710
+ return await withAdminSeat(inspected, deps, async () => {
1711
+ assertNotAborted(deps.signal);
1712
+ const systemctl = deps.systemctl ?? runSystemctl;
1713
+ const runtimeDir = runtimeDirOf(deps);
1714
+ let unit;
1715
+ try {
1716
+ unit = inspectOwnedProfileUnit(inspected, profile.name, deps.unitDir);
1717
+ } catch (error) {
1718
+ throw toDaemonControlError(error);
1719
+ }
1720
+ if (unit.kind === "none") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "no owned unit for this profile; run daemon install first");
1721
+ let before;
1722
+ try {
1723
+ before = await queryOwnedProfileUnit(unit, runtimeDir, systemctl);
1724
+ } catch (error) {
1725
+ throw toDaemonControlError(error);
1726
+ }
1727
+ if (before.loadState === "not-found") throw new DaemonControlError("MANAGER_OR_OS_FAILURE", "the installed unit is not loaded by the user manager; reload or reinstall it first");
1728
+ assertNotAborted(deps.signal);
1729
+ try {
1730
+ await setOwnedProfileUnitEnablement(unit, verb, runtimeDir, systemctl);
1731
+ } catch (error) {
1732
+ const failure = toDaemonControlError(error);
1733
+ if (failure.code === "IDENTITY_OR_OWNERSHIP_REFUSED") throw failure;
1734
+ throw afterCommittedAction(failure, `native ${verb}`);
1735
+ }
1736
+ let state = "not-found";
1737
+ let remaining;
1738
+ try {
1739
+ remaining = inspectOwnedProfileUnit(inspected, profile.name, deps.unitDir);
1740
+ } catch (error) {
1741
+ throw afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", toDaemonControlError(error).reason), `native ${verb}`);
1742
+ }
1743
+ if (remaining.kind === "owned") {
1744
+ try {
1745
+ state = (await queryOwnedProfileUnit(remaining, runtimeDir, systemctl)).unitFileState;
1746
+ } catch (error) {
1747
+ throw afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", toDaemonControlError(error).reason), `native ${verb}`);
1748
+ }
1749
+ if (state === "") throw afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", "the user manager reported no unit-file-state after the native request"), `native ${verb}`);
1750
+ }
1751
+ const profileName = profile.name.replace(/[\u0000-\u001f\u007f]/gu, "");
1752
+ let stderr = "";
1753
+ if (verb === "enable") {
1754
+ const uid = uidOf(deps);
1755
+ const linger = deps.lingerState === void 0 ? await queryLingerState(uid) : await deps.lingerState(uid);
1756
+ if (linger === "no") stderr = "dsh-pi-tui daemon: note: Linger is disabled for the current user. To start at system boot and keep the user manager running after logout, run: loginctl enable-linger\n";
1757
+ else if (linger === void 0) stderr = "dsh-pi-tui daemon: note: Linger could not be confirmed; query loginctl show-user <uid> -p Linger --value manually\n";
1758
+ }
1759
+ if (verb === "enable" && state === "static") stderr += "dsh-pi-tui daemon: note: the native unit-file-state is static; no login enablement was established. If desired, adjust the definition (for example add [Install] with WantedBy=default.target and reload), then run daemon enable again\n";
1760
+ return {
1761
+ code: 0,
1762
+ stdout: `profile=${profileName}\nunit=${unit.unitName}\nunit-file-state=${state}\n`,
1763
+ stderr
1764
+ };
1765
+ });
1766
+ }
1767
+ /** The `uninstall` handler: remove this Profile's service definition only. */
1768
+ async function runUninstall(profile, deps) {
1769
+ if (platformOf(deps) === "win32") return await runWindowsUninstall(profile, deps);
1770
+ if (platformOf(deps) === "darwin") return await runDarwinUninstall(profile, deps);
1771
+ const inspected = inspectScope(profile, deps);
1772
+ return await withAdminSeat(inspected, deps, async () => {
1773
+ const pre = await readSnapshot(profile, deps, inspected);
1774
+ if (pre.unitInspectionFailure !== void 0) throw pre.unitInspectionFailure;
1775
+ if (pre.unit === void 0) return statusResult(pre, {}, { commandSuccess: true });
1776
+ if (pre.failure !== void 0 && !verifiedUnitManagementAdmitted(pre)) throw pre.failure;
1777
+ if (pre.userManager !== "available") throw new DaemonControlError("MANAGER_OR_OS_FAILURE", "the user manager cannot verify the profile unit");
1778
+ const loaded = pre.unitState !== "not-found";
1779
+ const running = loaded && (pre.unitActiveState === "active" || pre.unitActiveState === "activating");
1780
+ const ended = loaded && (pre.unitActiveState === "inactive" || pre.unitActiveState === "failed");
1781
+ const liveHost = pre.processAlive && pre.record !== void 0;
1782
+ 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`);
1783
+ if (running) {
1784
+ 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");
1785
+ const systemctl = deps.systemctl ?? runSystemctl;
1786
+ assertNotAborted(deps.signal);
1787
+ await stopOwnedProfileUnit(pre.unit, runtimeDirOf(deps), systemctl, deps.stopTimeoutMs);
1788
+ const ownHost = liveHost && pre.record !== void 0 && pre.record.hostPid === pre.unitMainPid ? pre.record : void 0;
1789
+ try {
1790
+ await waitForHostStopped(ownHost, pre.unitMainPid, deps);
1791
+ } catch (error) {
1792
+ throw afterCommittedAction(toDaemonControlError(error), "Host stop for uninstall");
1793
+ }
1794
+ }
1795
+ const systemctl = deps.systemctl ?? runSystemctl;
1796
+ assertNotAborted(deps.signal);
1797
+ try {
1798
+ await setOwnedProfileUnitEnablement(pre.unit, "disable", runtimeDirOf(deps), systemctl);
1799
+ } catch (error) {
1800
+ const failure = toDaemonControlError(error);
1801
+ if (failure.code === "IDENTITY_OR_OWNERSHIP_REFUSED") throw failure;
1802
+ throw afterCommittedAction(failure, "native disable for uninstall");
1803
+ }
1804
+ let removalNeeded = true;
1805
+ try {
1806
+ removalNeeded = inspectOwnedProfileUnit(inspected, profile.name, deps.unitDir).kind === "owned";
1807
+ } catch (error) {
1808
+ throw afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", toDaemonControlError(error).reason), "native disable for uninstall");
1809
+ }
1810
+ if (removalNeeded) {
1811
+ assertNotAborted(deps.signal);
1812
+ uninstallOwnedProfileUnit(pre.unit);
1813
+ }
1814
+ try {
1815
+ if (removalNeeded) {
1816
+ const reload = await systemctl([
1817
+ "--user",
1818
+ "--no-pager",
1819
+ "--no-ask-password",
1820
+ "daemon-reload"
1821
+ ], runtimeDirOf(deps));
1822
+ if (reload.kind !== "exited" || reload.code !== 0) throw new DaemonControlError("MANAGER_OR_OS_FAILURE", "daemon-reload failed after removing the profile unit");
1823
+ }
1824
+ const post = await readSnapshot(profile, deps, inspected);
1825
+ if (post.unitInspectionFailure !== void 0) throw post.unitInspectionFailure;
1826
+ if (post.unitQueryFailure !== void 0) throw post.unitQueryFailure;
1827
+ if (post.unit !== void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the profile unit could not be confirmed removed");
1828
+ return statusResult(post, {}, {
1829
+ commandSuccess: true,
1830
+ extraStderr: running ? RUNNING_WORK_NOTICE : ""
1831
+ });
1832
+ } catch (error) {
1833
+ throw afterCommittedAction(toDaemonControlError(error), "profile unit removal");
1834
+ }
1835
+ });
1836
+ }
1837
+ /** The Darwin `install` handler: explicit LaunchAgent plist only, never host control. */
1838
+ async function runDarwinInstall(profile, deps, autostart) {
1839
+ const inspected = inspectScope(profile, deps);
1840
+ return await withAdminSeat(inspected, deps, async () => {
1841
+ assertNotAborted(deps.signal);
1842
+ const installed = await installLaunchdUnit(launchdFactsOf(inspected, profile), launchdDepsOf(deps), () => collectLaunchdUnitFacts({
1843
+ scope: autostart ? ensureInstalledProfileScopeDirectory(inspected) : inspected,
1844
+ hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
1845
+ dshAnchor: profile.installAnchor,
1846
+ profile: profile.name
1847
+ }), { autostart });
1848
+ const profileName = profile.name.replace(/[\u0000-\u001f\u007f]/gu, "");
1849
+ const preserved = autostart && !installed.created ? "dsh-pi-tui daemon: note: existing definition preserved; --autostart applies only to a new installation\n" : "";
1850
+ return {
1851
+ code: 0,
1852
+ stdout: `profile=${profileName}\nunit=${installed.label}\n`,
1853
+ stderr: preserved
1854
+ };
1855
+ });
1856
+ }
1857
+ /** The Darwin `uninstall` handler: remove this Profile's LaunchAgent only. */
1858
+ async function runDarwinUninstall(profile, deps) {
1859
+ const inspected = inspectScope(profile, deps);
1860
+ return await withAdminSeat(inspected, deps, async () => {
1861
+ const pre = await readSnapshot(profile, deps, inspected);
1862
+ if (pre.launchdInspectionFailure !== void 0) throw pre.launchdInspectionFailure;
1863
+ if (pre.launchdUnit === void 0) return statusResult(pre, {}, { commandSuccess: true });
1864
+ if (pre.launchdQueryFailure !== void 0) throw pre.launchdQueryFailure;
1865
+ if (pre.launchdFacts === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd plist facts are unavailable; refusing to uninstall");
1866
+ const service = pre.launchdService;
1867
+ if (service?.kind === "unknown") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job state is not recognizable; refusing to uninstall");
1868
+ const loadedService = service?.kind === "loaded" ? service.service : void 0;
1869
+ const liveHost = pre.processAlive && pre.record !== void 0;
1870
+ const running = loadedService !== void 0 && (loadedService.pid !== void 0 || loadedService.state === "running" || loadedService.state === "spawn scheduled");
1871
+ 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");
1872
+ 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");
1873
+ assertNotAborted(deps.signal);
1874
+ try {
1875
+ const expectedPid = liveHost && pre.record !== void 0 ? pre.record.hostPid : void 0;
1876
+ await uninstallLaunchdUnit(pre.launchdFacts, pre.launchdUnit, launchdDepsOf(deps), expectedPid);
1877
+ if (running && liveHost && pre.record !== void 0) await waitForHostStopped(pre.record, loadedService?.pid ?? pre.record.hostPid, deps);
1878
+ } catch (error) {
1879
+ throw afterCommittedAction(toDaemonControlError(error), "launchd plist removal");
1880
+ }
1881
+ try {
1882
+ const post = await readSnapshot(profile, deps, inspected);
1883
+ if (post.launchdInspectionFailure !== void 0) throw post.launchdInspectionFailure;
1884
+ if (post.launchdUnit !== void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the profile LaunchAgent could not be confirmed removed");
1885
+ return statusResult(post, {}, {
1886
+ commandSuccess: true,
1887
+ extraStderr: running ? RUNNING_WORK_NOTICE : ""
1888
+ });
1889
+ } catch (error) {
1890
+ throw afterCommittedAction(toDaemonControlError(error), "launchd plist removal");
1891
+ }
1892
+ });
1893
+ }
1894
+ /**
1895
+ * Run one fixed `journalctl --user-unit <name>` invocation. `--unit` filters the
1896
+ * SYSTEM unit field, while `--user-unit` selects `_SYSTEMD_USER_UNIT`. The `-n`
1897
+ * value selects recent journal records; display-line limiting happens only
1898
+ * after the captured bytes are sanitized.
1899
+ */
1900
+ function journalctlArgs(unit, lines) {
1901
+ return [
1902
+ "--user-unit",
1903
+ unit,
1904
+ "--no-pager",
1905
+ "-o",
1906
+ "cat",
1907
+ "-n",
1908
+ String(lines)
1909
+ ];
1910
+ }
1911
+ function runJournalctl(unit, lines) {
1912
+ return new Promise((resolve, reject) => {
1913
+ execFile(JOURNALCTL, journalctlArgs(unit, lines), {
1914
+ encoding: "buffer",
1915
+ timeout: JOURNALCTL_TIMEOUT_MS,
1916
+ maxBuffer: JOURNAL_MAX_OUTPUT_BYTES,
1917
+ killSignal: "SIGKILL"
1918
+ }, (error, stdout) => {
1919
+ if (error === null) {
1920
+ resolve({ stdout: stdout.toString("utf8") });
1921
+ return;
1922
+ }
1923
+ const code = error.code;
1924
+ if (code === "ENOENT") {
1925
+ resolve(void 0);
1926
+ return;
1927
+ }
1928
+ if (code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" && error.message === "stdout maxBuffer length exceeded") {
1929
+ resolve({ stdout: `${stdout.toString("utf8")}\n${LOG_TRUNCATION_MARKER}\n` });
1930
+ return;
1931
+ }
1932
+ reject(new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host journal could not be read"));
1933
+ });
1934
+ });
1935
+ }
1936
+ /**
1937
+ * Read a bounded tail of a fixed log. POSIX never follows a final symlink and
1938
+ * opens non-blocking; Windows rejects an identifiable final symlink/non-file
1939
+ * before an ordinary read. Both paths admit only the opened regular file.
1940
+ */
1941
+ async function tailHostLog(path) {
1942
+ let fd;
1943
+ if (process.platform === "win32") {
1944
+ try {
1945
+ const info = lstatSync(path);
1946
+ if (info.isSymbolicLink() || !info.isFile()) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log is not a regular file");
1947
+ } catch (error) {
1948
+ if (error.code === "ENOENT") return void 0;
1949
+ if (error instanceof DaemonControlError) throw error;
1950
+ throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log could not be inspected");
1951
+ }
1952
+ try {
1953
+ fd = openSync(path, constants.O_RDONLY);
1954
+ } catch (error) {
1955
+ if (error.code === "ENOENT") return void 0;
1956
+ throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log could not be opened");
1957
+ }
1958
+ } else try {
1959
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1960
+ } catch (error) {
1961
+ if (error.code === "ENOENT") return void 0;
1962
+ throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log could not be opened");
1963
+ }
1964
+ let readFailure;
1965
+ try {
1966
+ const info = fstatSync(fd);
1967
+ if (!info.isFile()) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log is not a regular file");
1968
+ const length = Math.min(info.size, HOST_LOG_MAX_BYTES);
1969
+ const start = info.size - length;
1970
+ const buffer = Buffer.alloc(length);
1971
+ let offset = 0;
1972
+ while (offset < buffer.length) {
1973
+ const read = readSync(fd, buffer, offset, buffer.length - offset, start + offset);
1974
+ if (read <= 0) break;
1975
+ offset += read;
1976
+ }
1977
+ const text = buffer.toString("utf8", 0, offset);
1978
+ return `${start > 0 ? `${LOG_TRUNCATION_MARKER}\n` : ""}${text}`;
1979
+ } catch (error) {
1980
+ readFailure = error instanceof DaemonControlError ? error : new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log could not be read");
1981
+ throw readFailure;
1982
+ } finally {
1983
+ try {
1984
+ closeSync(fd);
1985
+ } catch {
1986
+ if (readFailure === void 0) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log could not be closed");
1987
+ }
1988
+ }
1989
+ }
1990
+ /** Remove terminal control sequences and best-effort secret material. */
1991
+ function sanitizeLogText(text) {
1992
+ return stripVTControlCharacters(text).replace(/\r\n/gu, "\n").replace(/\r/gu, " ").replace(/\t/gu, " ").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/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");
1993
+ }
1994
+ /**
1995
+ * Read the Profile's fixed historical diagnostic sources without asserting
1996
+ * which Host instance produced them. A source failure is a safe warning, never
1997
+ * a reason to discard another source's real content.
1998
+ */
1999
+ async function runLogs(profile, intent, deps) {
2000
+ const scope = inspectScope(profile, deps);
2001
+ const platform = platformOf(deps);
2002
+ const lines = intent.lines ?? 100;
2003
+ const sections = [];
2004
+ const warnings = [];
2005
+ const tail = deps.hostLogTail ?? tailHostLog;
2006
+ const warn = (source, reason) => {
2007
+ warnings.push(`dsh-pi-tui daemon: warning: ${source} unavailable (${reason})\n`);
2008
+ };
2009
+ const append = (label, raw) => {
2010
+ const rawRecords = raw.split("\n");
2011
+ while (rawRecords.length > 0 && rawRecords[rawRecords.length - 1] === "") rawRecords.pop();
2012
+ let truncated = false;
2013
+ if (rawRecords[0] === "[dsh-pi-tui daemon: log output truncated]") {
2014
+ truncated = true;
2015
+ rawRecords.shift();
2016
+ }
2017
+ if (rawRecords[rawRecords.length - 1] === "[dsh-pi-tui daemon: log output truncated]") {
2018
+ truncated = true;
2019
+ rawRecords.pop();
2020
+ }
2021
+ const records = sanitizeLogText(rawRecords.join("\n")).split("\n");
2022
+ while (records.length > 0 && records[records.length - 1] === "") records.pop();
2023
+ if (records.length > lines) {
2024
+ records.splice(0, records.length - lines);
2025
+ truncated = true;
2026
+ }
2027
+ const body = records.join("\n");
2028
+ if (body.trim() === "") return false;
2029
+ sections.push(`[dsh-pi-tui daemon: ${label}]\n${body}\n${truncated ? `${LOG_TRUNCATION_MARKER}\n` : ""}`);
2030
+ return true;
2031
+ };
2032
+ const readFile = async (label, source, path) => {
2033
+ let value;
2034
+ try {
2035
+ value = await tail(path);
2036
+ } catch (error) {
2037
+ if (!(error instanceof DaemonControlError) || error.code !== "LOG_SOURCE_UNAVAILABLE") throw error;
2038
+ warn(source, "file could not be read");
2039
+ return;
2040
+ }
2041
+ if (value !== void 0) append(label, value);
2042
+ };
2043
+ await readFile("host.log", "host.log", join(scope.dir, "host.log"));
2044
+ if (platform === "darwin") {
2045
+ const fixed = launchdLogPaths(scope.dir);
2046
+ await readFile("launchd stdout", "launchd stdout", fixed.stdout);
2047
+ await readFile("launchd stderr", "launchd stderr", fixed.stderr);
2048
+ } else if (platform === "linux") try {
2049
+ const result = await (deps.journal ?? runJournalctl)(buildUnitName(profile.name, scope.scopeId), lines);
2050
+ if (result !== void 0 && !append("systemd user-unit journal", result.stdout) && result.stdout.includes("[dsh-pi-tui daemon: log output truncated]")) warn("systemd user-unit journal", "journal produced no readable content");
2051
+ } catch (error) {
2052
+ if (!(error instanceof DaemonControlError) || error.code !== "LOG_SOURCE_UNAVAILABLE") throw error;
2053
+ warn("systemd user-unit journal", "journal could not be read");
2054
+ }
2055
+ if (sections.length === 0) {
2056
+ const failure = new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "no Host log content is available for this profile");
2057
+ return {
2058
+ code: 4,
2059
+ stdout: "",
2060
+ stderr: `${warnings.join("")}${formatDaemonControlError(failure)}`
2061
+ };
2062
+ }
2063
+ return {
2064
+ code: 0,
2065
+ stdout: sections.join("\n"),
2066
+ stderr: `${warnings.join("")}${LOG_SANITIZATION_NOTICE}`
2067
+ };
2068
+ }
2069
+ /**
2070
+ * Run ONE daemon management command for ONE official Profile. Every failure is
2071
+ * mapped to the fixed stable code/exit taxonomy; no raw Error message, command
2072
+ * argv, Host URL, Cookie or private path reaches stdout/stderr.
2073
+ */
2074
+ async function runDaemonControl(intent, profile, deps = {}) {
2075
+ try {
2076
+ const platform = platformOf(deps);
2077
+ if (intent.verb === "install" && intent.autostart === true && platform !== "darwin" && platform !== "win32") throw new DaemonControlError("UNSUPPORTED_PLATFORM", "daemon install --autostart is supported on macOS and Windows only; use daemon install (and daemon enable on Linux)");
2078
+ if (platform === "win32" && intent.verb === "install" && intent.autostart !== true) throw new DaemonControlError("UNSUPPORTED_PLATFORM", "Windows has no service manager; use daemon install --autostart to register the login-only task");
2079
+ switch (intent.verb) {
2080
+ case "status": return await runStatus(profile, deps);
2081
+ case "start": return await runStart(profile, deps);
2082
+ case "stop": return await runStop(profile, deps);
2083
+ case "restart": return await runRestart(profile, deps);
2084
+ case "logs": return await runLogs(profile, intent, deps);
2085
+ case "install": return await runInstall(profile, intent, deps);
2086
+ case "uninstall": return await runUninstall(profile, deps);
2087
+ case "enable": return await runUnitEnablement(profile, "enable", deps);
2088
+ case "disable": return await runUnitEnablement(profile, "disable", deps);
2089
+ }
2090
+ } catch (error) {
2091
+ const failure = toDaemonControlError(error);
2092
+ const notice = intent.verb === "stop" || intent.verb === "restart" ? RUNNING_WORK_NOTICE : "";
2093
+ return {
2094
+ code: failure.exitCode,
2095
+ stdout: "",
2096
+ stderr: `${formatDaemonControlError(failure)}${notice}`
2097
+ };
2098
+ }
2099
+ }
2100
+ //#endregion
2101
+ export { readAcpStdioTarget, runDaemonControl };