@xmoon76/dsh-pi-tui 0.5.8 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.en.md +61 -25
  2. package/README.md +61 -25
  3. package/cordis.patch.yml +13 -0
  4. package/dist/acp-stdio.mjs +151 -0
  5. package/dist/{bootstrap-CMIjGyuk.mjs → bootstrap-CVyHGQDX.mjs} +21901 -6575
  6. package/dist/browser-CDUSHIIr.mjs +76 -0
  7. package/dist/builtins.mjs +2 -2
  8. package/dist/{client-bootstrap-BjGPc-DM.mjs → client-bootstrap-4UoeVIHE.mjs} +2488 -2734
  9. package/dist/client-runtime-BHBlVUf5.mjs +1376 -0
  10. package/dist/{daemon-launcher-Dult7Jxv.mjs → daemon-launcher-DxIgjBHW.mjs} +1549 -172
  11. package/dist/daemon-launcher.d.mts +85 -14
  12. package/dist/daemon-launcher.mjs +2 -2
  13. package/dist/{local-profile-daemon-admin-BmQSdzT0.mjs → diagnostics-Db5iVcuJ.mjs} +3 -90
  14. package/dist/{entry-control-DjNsE3I0.mjs → entry-control-BDLZgg4m.mjs} +1 -1
  15. package/dist/{extensions-B4uLpSTv.mjs → extensions-Dx7ncPNA.mjs} +1 -1
  16. package/dist/extensions.mjs +1 -1
  17. package/dist/handoff-BjoEy3f8.mjs +106 -0
  18. package/dist/history-search-limits-Cx2UvRC2.mjs +16 -0
  19. package/dist/history-search-remote-BHuoellG.mjs +113 -0
  20. package/dist/history-search-remote-BzXdvrxk.mjs +26 -0
  21. package/dist/history-search-seat-BcHJTpeB.mjs +639 -0
  22. package/dist/history-search-seat-rZcq0XV6.mjs +639 -0
  23. package/dist/{host-bootstrap-MVxks641.mjs → host-bootstrap-BfnufpnW.mjs} +37 -72
  24. package/dist/{host-foundation-probe-DMNTmNrH.mjs → host-foundation-probe-DlD8-N_Q.mjs} +2 -2
  25. package/dist/host-runtime.mjs +5611 -290
  26. package/dist/index.d.mts +13 -6
  27. package/dist/index.mjs +22334 -6695
  28. package/dist/installed-dsh-BjUiJSwR.mjs +142 -0
  29. package/dist/interaction-port-D1Yv9zgu.mjs +45 -0
  30. package/dist/local-acp-control-CC5z4Xbq.mjs +304 -0
  31. package/dist/local-acp-endpoint-D1jYdJdv.mjs +41 -0
  32. package/dist/local-acp-listener-Cmgb5M0H.mjs +9493 -0
  33. package/dist/local-acp-status-B_25Q6kU.mjs +101 -0
  34. package/dist/local-client.mjs +292 -63
  35. package/dist/local-daemon-control-BFJAC8Kg.mjs +2199 -0
  36. package/dist/local-daemon-control-Bm3imctD.mjs +2101 -0
  37. package/dist/{local-discovery-uOBfFq5j.mjs → local-discovery-BMhaGIiJ.mjs} +254 -544
  38. package/dist/{local-discovery-egN4_gsQ.mjs → local-discovery-Ba7_-NNC.mjs} +1 -1
  39. package/dist/{local-discovery-DOSsCh9q.mjs → local-discovery-QSbFpjK2.mjs} +301 -544
  40. package/dist/local-host.mjs +952 -501
  41. package/dist/local-profile-daemon-admin-otpm69R6.mjs +469 -0
  42. package/dist/{local-scope-DamiMqPd.mjs → local-scope-5DEKA_lW.mjs} +1023 -96
  43. package/dist/{local-transport-Iwo0mtu3.mjs → local-transport-DeWmdZ5E.mjs} +14 -3
  44. package/dist/{local-web-control-DMrjwCkl.mjs → local-web-control-Dny93N-r.mjs} +10 -7
  45. package/dist/{local-workspace-object-D06GL0UO.mjs → local-workspace-object-D0RVQt8U.mjs} +33 -9
  46. package/dist/model-selection-CYlqg2DV.mjs +83 -0
  47. package/dist/native-client-domains-Dg4srzYt.mjs +2 -0
  48. package/dist/native-client.d.mts +735 -0
  49. package/dist/native-client.mjs +3534 -0
  50. package/dist/{open-CmOBxSjN.mjs → open-QQva8-ar.mjs} +24 -20
  51. package/dist/{pi-tui-remote-contribution-Do8ECrUy.mjs → pi-tui-remote-contribution-565wiLWp.mjs} +741 -150
  52. package/dist/preferences.mjs +1 -1
  53. package/dist/{profile-preferences-migration-CThz4rHH.mjs → profile-preferences-migration-CNOWIdnr.mjs} +1 -1
  54. package/dist/{profile-preferences-migration-BfUGdPZx.mjs → profile-preferences-migration-IrnXcJWK.mjs} +10 -8
  55. package/dist/{prompt-sections-DXmjB58H.mjs → prompt-sections-Bi-9_Gr_.mjs} +28 -10
  56. package/dist/{prompt-sections-DUKmWb8g.mjs → prompt-sections-DFS1dqsY.mjs} +342 -56
  57. package/dist/{dist-BFgC-5tL.mjs → recall-scope-9Nuoto_i.mjs} +353 -1
  58. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  59. package/dist/schema-CCLvDa7Q.mjs +177 -0
  60. package/dist/{schema-qE_P09zJ.mjs → schema-t97l3aK8.mjs} +56 -3
  61. package/dist/{session-C6tSs86s.mjs → session-Cs8iLCEx.mjs} +784 -342
  62. package/dist/{session-CstInGIA.mjs → session-EBRZF6Ow.mjs} +783 -341
  63. package/dist/session-create-facts-CkfG5DpQ.mjs +20 -0
  64. package/dist/{startup-CarQxWwi.d.mts → startup-Dti3Udne.d.mts} +30 -3
  65. package/dist/{startup-EG5UqIcd.mjs → startup-UtFQSDe_.mjs} +90 -15
  66. package/dist/startup.d.mts +2 -2
  67. package/dist/startup.mjs +1 -1
  68. package/dist/task-read-remote-DRtkXDrZ.mjs +1083 -0
  69. package/dist/{terminal-progress-source-CpfpQO_h.mjs → terminal-progress-source-VsczdXA-.mjs} +610 -332
  70. package/dist/{transcript-view-CuJYWkhp.mjs → transcript-view-B6vCnukn.mjs} +2096 -977
  71. package/dist/{transcript-view-C1YtJ49Y.mjs → transcript-view-DSSdE2vK.mjs} +2078 -651
  72. package/dist/write-failure-xNKczXH7.mjs +189 -0
  73. package/package.json +20 -3
  74. package/dist/local-acp-listener-B65J0Bx4.mjs +0 -3115
  75. package/dist/local-daemon-control-C14q9KnD.mjs +0 -1588
  76. package/dist/local-daemon-control-TCnERL7n.mjs +0 -1424
  77. package/dist/preset-BcWqOtY7.mjs +0 -46
@@ -1,6 +1,7 @@
1
- import { _ as parseProcessStat, b as readProcessStarttime, d as readInstalledDshVersion, f as readLinuxStarttime, n as LocalScopeError, s as computeBuildId, u as installedPackageRootFromEntry, x as sameKernelProcess, y as readKernelProcess } from "./local-scope-DamiMqPd.mjs";
2
- import { createHash, randomUUID } from "node:crypto";
3
- import { accessSync, closeSync, constants, existsSync, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
1
+ import { C as sameKernelProcess, P as win32PrivateFileStatus, S as readProcessStarttime, d as installedPackageRootFromEntry, f as materializeBuild, m as readLinuxStarttime, n as LocalScopeError, x as readKernelProcess, y as parseProcessStat } from "./local-scope-5DEKA_lW.mjs";
2
+ import { a as scrubProgramResumeEnvironment } from "./handoff-BjoEy3f8.mjs";
3
+ import { randomUUID } from "node:crypto";
4
+ import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
4
5
  import { basename, dirname, isAbsolute, join } from "node:path";
5
6
  import { pathToFileURL } from "node:url";
6
7
  import { userInfo } from "node:os";
@@ -23,8 +24,10 @@ import { spawn, spawnSync } from "node:child_process";
23
24
  * invoked with a fixed argument array through `/bin/launchctl` (no shell).
24
25
  *
25
26
  * The default job does NOT start at login and is NOT restarted automatically:
26
- * `RunAtLoad=false` and `KeepAlive=false` are deliberate. The product does not
27
- * rewrite user runtime directives in an existing same-owner plist.
27
+ * `RunAtLoad=false` and `KeepAlive=false` are deliberate. A FRESH definition
28
+ * created with the explicit `daemon install --autostart` opt-in instead asks
29
+ * launchd to start the Host at login and to restart it after an abnormal exit;
30
+ * the product never rewrites those keys in an existing same-owner plist.
28
31
  *
29
32
  * @module app/remote-process/local-host-launchd
30
33
  */
@@ -72,7 +75,8 @@ function encodePlistValue(value, label) {
72
75
  return value.replace(/&/gu, "&amp;").replace(/</gu, "&lt;").replace(/>/gu, "&gt;").replace(/"/gu, "&quot;").replace(/'/gu, "&apos;");
73
76
  }
74
77
  /** Render the complete, fixed LaunchAgent plist for one installed Host. */
75
- function renderLaunchdPlist(facts) {
78
+ function renderLaunchdPlist(facts, options = {}) {
79
+ const autostart = options.autostart === true;
76
80
  const label = buildLaunchdLabel(facts.scopeId);
77
81
  const logs = launchdLogPaths(facts.scopeDir);
78
82
  return [
@@ -90,9 +94,14 @@ function renderLaunchdPlist(facts) {
90
94
  " <key>WorkingDirectory</key>",
91
95
  ` <string>${encodePlistValue(facts.profileRealpath, "WorkingDirectory")}</string>`,
92
96
  " <key>RunAtLoad</key>",
93
- " <false/>",
97
+ ...autostart ? [" <true/>"] : [" <false/>"],
94
98
  " <key>KeepAlive</key>",
95
- " <false/>",
99
+ ...autostart ? [
100
+ " <dict>",
101
+ " <key>SuccessfulExit</key>",
102
+ " <false/>",
103
+ " </dict>"
104
+ ] : [" <false/>"],
96
105
  " <key>StandardOutPath</key>",
97
106
  ` <string>${encodePlistValue(logs.stdout, "StandardOutPath")}</string>`,
98
107
  " <key>StandardErrorPath</key>",
@@ -112,10 +121,6 @@ function renderLaunchdPlist(facts) {
112
121
  ` <string>${encodePlistValue(LAUNCHD_OWNER_MARKER, "owner marker")}</string>`,
113
122
  " <key>X-DshPiTuiScopeId</key>",
114
123
  ` <string>${encodePlistValue(facts.scopeId, "scope id")}</string>`,
115
- " <key>X-DshPiTuiProfileIdentity</key>",
116
- ` <string>${encodePlistValue(facts.profileIdentity, "profile identity")}</string>`,
117
- " <key>X-DshPiTuiInstallBuild</key>",
118
- ` <string>${encodePlistValue(facts.buildId, "install build")}</string>`,
119
124
  "</dict>",
120
125
  "</plist>",
121
126
  ""
@@ -157,10 +162,9 @@ function requirePlistString(root, key) {
157
162
  *
158
163
  * The named path survives an official profile package upgrade (pnpm keeps the
159
164
  * lexical path while the physical payload changes), unlike a versioned store
160
- * path. The caller uses it ONLY when creating a FRESH plist or migrating a
161
- * proven old generated entry; every other command keeps validating the real
162
- * installed entry through `collectUnitFacts()`. The path must resolve to the
163
- * very same physical file the official facts named, and the nearest manifest
165
+ * path. The caller uses it ONLY when creating a FRESH plist; existing plists
166
+ * are never rewritten. The path must resolve to the very same physical file
167
+ * the official facts named, and the nearest manifest
164
168
  * above the named entry must be this installed product package — otherwise the
165
169
  * profile layout does not provide a stable entry and the operation fails closed.
166
170
  */
@@ -190,8 +194,8 @@ function resolveNamedLaunchdEntry(facts) {
190
194
  * The native plist decoder is the authority for the top-level semantics: XML
191
195
  * comments, character references, CDATA and tag whitespace all normalize to the
192
196
  * same keys/values. Only the facts that bind the job to THIS profile are
193
- * checked: the exact `Label` and the three official environment anchors
194
- * (`DSH_HOME`, `SPLIT_PROCESS_DSH_ANCHOR`, `SPLIT_PROCESS_PROFILE`). Every
197
+ * checked: the three official environment anchors (`DSH_HOME`,
198
+ * `SPLIT_PROCESS_DSH_ANCHOR`, `SPLIT_PROCESS_PROFILE`). Every
195
199
  * other runtime directive — `ProgramArguments`, `WorkingDirectory`, log
196
200
  * sinks, `RunAtLoad`, `KeepAlive`, triggers, extra environment keys and
197
201
  * comments — belongs to the user and launchd, and is executed as written; the
@@ -201,14 +205,7 @@ function assertLaunchdProfileAnchors(facts, content) {
201
205
  const reject = (reason) => {
202
206
  throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `launchd: the profile plist has a changed profile launch anchor (${reason}); refusing to bootstrap it`);
203
207
  };
204
- const root = decodeLaunchdPlist(content);
205
- const text = (key) => {
206
- const value = root[key];
207
- if (typeof value !== "string") return reject(key);
208
- return value;
209
- };
210
- if (text("Label") !== buildLaunchdLabel(facts.scopeId)) reject("Label");
211
- const environment = root.EnvironmentVariables;
208
+ const environment = decodeLaunchdPlist(content).EnvironmentVariables;
212
209
  if (environment === null || typeof environment !== "object" || Array.isArray(environment)) reject("EnvironmentVariables");
213
210
  const env = environment;
214
211
  const expectedEnvironment = {
@@ -218,16 +215,12 @@ function assertLaunchdProfileAnchors(facts, content) {
218
215
  };
219
216
  for (const [key, value] of Object.entries(expectedEnvironment)) if (env[key] !== value) reject(`EnvironmentVariables.${key}`);
220
217
  }
221
- /** The installed plist metadata of one owned unit (native top-level values). */
218
+ /** Verify the native top-level identity of one owned LaunchAgent. */
222
219
  function inspectLaunchdIdentity(content, facts, label) {
223
220
  const root = decodeLaunchdPlist(content);
224
221
  if (requirePlistString(root, "Label") !== label) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist Label is not this profile scope");
225
222
  if (requirePlistString(root, "X-DshPiTuiOwner") !== LAUNCHD_OWNER_MARKER) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist is not owned by this product");
226
223
  if (requirePlistString(root, "X-DshPiTuiScopeId") !== facts.scopeId) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist belongs to another profile scope");
227
- if (requirePlistString(root, "X-DshPiTuiProfileIdentity") !== facts.profileIdentity) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist belongs to another canonical profile");
228
- const installBuild = requirePlistString(root, "X-DshPiTuiInstallBuild");
229
- if (!/^[0-9a-f]{64}$/u.test(installBuild)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist has no valid install build identity");
230
- return installBuild;
231
224
  }
232
225
  /** Resolve and prove the OS account home without trusting `$HOME`/`DSH_HOME`. */
233
226
  function resolveAccountHome(deps) {
@@ -357,20 +350,20 @@ function inspectOwnedLaunchdUnit(facts, deps = {}) {
357
350
  }
358
351
  if (!exists) return { kind: "none" };
359
352
  const file = readLaunchdFileIdentity(filePath);
353
+ inspectLaunchdIdentity(file.content, facts, label);
360
354
  return {
361
355
  kind: "owned",
362
356
  unit: {
363
357
  label,
364
358
  filePath,
365
- installBuild: inspectLaunchdIdentity(file.content, facts, label),
366
359
  ...file
367
360
  }
368
361
  };
369
362
  }
370
363
  /** Re-prove one owned plist's captured file identity before a mutation. */
371
- function assertLaunchdFileIdentity(unit, facts, deps) {
372
- const inspected = inspectOwnedLaunchdUnit(facts, deps);
373
- if (inspected.kind !== "owned" || inspected.unit.filePath !== unit.filePath || inspected.unit.resolvedPath !== unit.resolvedPath || inspected.unit.pathDevice !== unit.pathDevice || inspected.unit.pathInode !== unit.pathInode || inspected.unit.device !== unit.device || inspected.unit.inode !== unit.inode || inspected.unit.content !== unit.content) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist changed during the transition");
364
+ function assertLaunchdFileIdentity(unit) {
365
+ const current = readLaunchdFileIdentity(unit.filePath);
366
+ if (current.resolvedPath !== unit.resolvedPath || current.pathDevice !== unit.pathDevice || current.pathInode !== unit.pathInode || current.device !== unit.device || current.inode !== unit.inode || current.content !== unit.content) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist changed during the transition");
374
367
  }
375
368
  /**
376
369
  * Run exactly one fixed `launchctl` invocation: `shell: false`, an absolute
@@ -390,6 +383,8 @@ function runLaunchctl(args, options = {}) {
390
383
  };
391
384
  let child;
392
385
  try {
386
+ const env = { ...process.env };
387
+ scrubProgramResumeEnvironment(env);
393
388
  child = spawn(LAUNCHCTL, [...args], {
394
389
  shell: false,
395
390
  stdio: options.discardStdout === true ? [
@@ -401,7 +396,7 @@ function runLaunchctl(args, options = {}) {
401
396
  "pipe",
402
397
  "pipe"
403
398
  ],
404
- env: process.env
399
+ env
405
400
  });
406
401
  } catch (error) {
407
402
  settle({
@@ -478,25 +473,9 @@ function parseLaunchctlPrint(stdout) {
478
473
  const type = readLaunchctlScalar(lines, "type");
479
474
  const path = readLaunchctlScalar(lines, "path");
480
475
  const state = readLaunchctlScalar(lines, "state");
481
- const program = readLaunchctlScalar(lines, "program");
482
- const workingDirectory = readLaunchctlScalar(lines, "working directory");
483
- const stdoutPath = readLaunchctlScalar(lines, "stdout path");
484
- const stderrPath = readLaunchctlScalar(lines, "stderr path");
485
- const argumentLines = readLaunchctlBlock(lines, "arguments");
486
476
  const environmentLines = readLaunchctlBlock(lines, "environment");
487
- if (type === void 0 || path === void 0 || state === void 0 || program === void 0 || argumentLines === void 0 || environmentLines === void 0) return void 0;
488
- if (type !== "LaunchAgent" || !path.startsWith("/") || !program.startsWith("/")) return void 0;
489
- for (const optional of [
490
- workingDirectory,
491
- stdoutPath,
492
- stderrPath
493
- ]) if (optional !== void 0 && !optional.startsWith("/")) return void 0;
494
- const argumentsList = [];
495
- for (const line of argumentLines) {
496
- if (line === "") return void 0;
497
- argumentsList.push(line);
498
- }
499
- if (argumentsList.length === 0) return void 0;
477
+ if (type === void 0 || path === void 0 || state === void 0 || state === "" || environmentLines === void 0) return void 0;
478
+ if (type !== "LaunchAgent" || !path.startsWith("/")) return void 0;
500
479
  const environment = {};
501
480
  for (const line of environmentLines) {
502
481
  const separator = line.indexOf(" => ");
@@ -517,11 +496,6 @@ function parseLaunchctlPrint(stdout) {
517
496
  type,
518
497
  path,
519
498
  state,
520
- program,
521
- arguments: argumentsList,
522
- ...workingDirectory === void 0 ? {} : { workingDirectory },
523
- ...stdoutPath === void 0 ? {} : { stdoutPath },
524
- ...stderrPath === void 0 ? {} : { stderrPath },
525
499
  environment,
526
500
  ...pid === void 0 ? {} : { pid }
527
501
  };
@@ -713,9 +687,12 @@ function rollbackNewLaunchdFile(installed, error) {
713
687
  * job source, then writes the plist atomically. A job loaded from our target
714
688
  * path with no owned file is an unprovable source and is refused rather than
715
689
  * conflated with a new file. It never bootstraps, kickstarts, enables, stops or
716
- * restarts a job and never creates the profile runtime scope.
690
+ * restarts a job and creates no profile runtime scope for a plain install; only
691
+ * a FRESH definition requested with `autostart` prepares the private scope
692
+ * (through the caller's fresh facts supplier) and the default log sinks before
693
+ * the plist is published.
717
694
  */
718
- async function installLaunchdUnit(facts, deps = {}) {
695
+ async function installLaunchdUnit(facts, deps = {}, strictFacts, options = {}) {
719
696
  const accountHome = resolveAccountHome(deps);
720
697
  const label = buildLaunchdLabel(facts.scopeId);
721
698
  await assertLaunchdDomain(deps);
@@ -741,13 +718,17 @@ async function installLaunchdUnit(facts, deps = {}) {
741
718
  filePath: existing.unit.filePath,
742
719
  created: false
743
720
  };
721
+ const full = "nodePath" in facts && "hostEntryPath" in facts ? facts : strictFacts?.();
722
+ if (full === void 0) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: a fresh plist requires the current Node and Host entry facts");
723
+ const content = renderLaunchdPlist({
724
+ ...full,
725
+ hostEntryPath: resolveNamedLaunchdEntry(full)
726
+ }, options);
727
+ if (options.autostart === true) ensureLaunchdLogFiles(full);
744
728
  const installed = installLaunchdFile({
745
729
  dir,
746
730
  label,
747
- content: renderLaunchdPlist({
748
- ...facts,
749
- hostEntryPath: resolveNamedLaunchdEntry(facts)
750
- })
731
+ content
751
732
  });
752
733
  try {
753
734
  const verified = (deps.verifyInstalledUnit ?? ((current) => inspectOwnedLaunchdUnit(current, deps)))(facts);
@@ -769,13 +750,27 @@ async function kickstartLaunchdJob(unit, deps) {
769
750
  if (result.kind !== "exited" || result.code !== 0) throw launchctlFailure(result, "kickstart");
770
751
  }
771
752
  /**
753
+ * Does one loaded observation already satisfy a start REQUEST?
754
+ *
755
+ * A real `pid` or launchd's own `spawn scheduled` transition means the manager
756
+ * has already accepted the launch. Neither is Host readiness — the caller's
757
+ * authenticated wait owns that verdict — so this only prevents a second
758
+ * destructive transition.
759
+ */
760
+ function launchdStartRequested(service) {
761
+ return service.pid !== void 0 || service.state === "spawn scheduled";
762
+ }
763
+ /**
772
764
  * Start the installed job through launchd only: prove the captured file
773
765
  * identity and the profile launch anchors, inspect the current service,
774
766
  * refuse a foreign loaded definition, reload a verified IDLE loaded job from
775
767
  * the current on-disk user plist (launchd's `kickstart` reuses the cached
776
768
  * bootstrap definition, which may predate a user edit), `bootstrap` exactly
777
- * once when the job is not loaded, then `kickstart` exactly once when no
778
- * process is running. The USER-OWNED definition is executed as written:
769
+ * once when the job is not loaded, then `kickstart` exactly once only when the
770
+ * job is still provably idle. A real PID or launchd's own `spawn scheduled`
771
+ * transition is already an accepted start request: the caller waits for the
772
+ * authenticated Host instead of mutating the job again. The USER-OWNED
773
+ * definition is executed as written:
779
774
  * `RunAtLoad`, `KeepAlive`, custom arguments, working directory, triggers and
780
775
  * extra environment keys are legal launchd configuration and are not judged
781
776
  * here; the caller proves the resulting Host through the official
@@ -784,19 +779,17 @@ async function kickstartLaunchdJob(unit, deps) {
784
779
  */
785
780
  async function startLaunchdService(facts, unit, deps = {}) {
786
781
  const uid = effectiveUid(deps);
787
- assertLaunchdFileIdentity(unit, facts, deps);
788
782
  assertLaunchdProfileAnchors(facts, unit.content);
789
783
  let observed = await inspectLaunchdService(unit, deps);
790
784
  if (observed.kind === "unknown") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the loaded job state is not recognizable; refusing to start");
791
785
  if (observed.kind === "loaded") {
792
786
  if (!launchdServiceMatches(facts, unit, observed.service)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the loaded job does not match this profile plist; run daemon uninstall before reinstalling");
793
- if (observed.service.pid !== void 0) return;
787
+ if (launchdStartRequested(observed.service)) return;
794
788
  if (observed.service.state !== "not running") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the loaded job is in an unconfirmed state; refusing to start");
795
789
  await stopLaunchdService(facts, unit, deps);
796
- if ((await inspectLaunchdService(unit, deps)).kind !== "not-loaded") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the idle job could not be confirmed unloaded before the reload");
797
790
  }
798
791
  ensureLaunchdLogFiles(facts);
799
- assertLaunchdFileIdentity(unit, facts, deps);
792
+ assertLaunchdFileIdentity(unit);
800
793
  const bootstrap = await (deps.launchctl ?? runLaunchctl)([
801
794
  "bootstrap",
802
795
  `gui/${String(uid)}`,
@@ -805,15 +798,17 @@ async function startLaunchdService(facts, unit, deps = {}) {
805
798
  if (bootstrap.kind !== "exited" || bootstrap.code !== 0) {
806
799
  const raced = await inspectLaunchdService(unit, deps);
807
800
  if (raced.kind !== "loaded" || !launchdServiceMatches(facts, unit, raced.service)) throw launchctlFailure(bootstrap, "bootstrap");
808
- if (raced.service.pid !== void 0) return;
809
- assertLaunchdFileIdentity(unit, facts, deps);
801
+ if (launchdStartRequested(raced.service)) return;
802
+ if (raced.service.state !== "not running") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the bootstrapped job is in an unconfirmed state; refusing to start");
803
+ assertLaunchdFileIdentity(unit);
810
804
  await kickstartLaunchdJob(unit, deps);
811
805
  return;
812
806
  }
813
807
  observed = await inspectLaunchdService(unit, deps);
814
808
  if (observed.kind !== "loaded" || !launchdServiceMatches(facts, unit, observed.service)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the bootstrapped job is not this profile plist");
815
- if (observed.service.pid !== void 0) return;
816
- assertLaunchdFileIdentity(unit, facts, deps);
809
+ if (launchdStartRequested(observed.service)) return;
810
+ if (observed.service.state !== "not running") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the bootstrapped job is in an unconfirmed state; refusing to start");
811
+ assertLaunchdFileIdentity(unit);
817
812
  await kickstartLaunchdJob(unit, deps);
818
813
  }
819
814
  /** Bounded wait until a verified label is genuinely no longer loaded. */
@@ -834,7 +829,6 @@ async function waitForLaunchdJobRemoved(unit, deps) {
834
829
  * match the current profile plist is never booted out.
835
830
  */
836
831
  async function stopLaunchdService(facts, unit, deps = {}, expectedPid) {
837
- assertLaunchdFileIdentity(unit, facts, deps);
838
832
  const observed = await inspectLaunchdService(unit, deps);
839
833
  if (observed.kind === "not-loaded") return { stopped: false };
840
834
  if (observed.kind === "unknown") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the loaded job state is not recognizable; refusing to stop");
@@ -848,7 +842,7 @@ async function stopLaunchdService(facts, unit, deps = {}, expectedPid) {
848
842
  if (observed.service.state !== "not running") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `launchd: the loaded job is in an unconfirmed state (${observed.service.state === "" ? "unknown" : observed.service.state}); refusing to stop`);
849
843
  }
850
844
  const stopped = observed.service.pid !== void 0;
851
- assertLaunchdFileIdentity(unit, facts, deps);
845
+ assertLaunchdFileIdentity(unit);
852
846
  const uid = effectiveUid(deps);
853
847
  const result = await (deps.launchctl ?? runLaunchctl)(["bootout", `gui/${String(uid)}/${unit.label}`]);
854
848
  if (result.kind !== "exited" || result.code !== 0 && result.code !== 3) throw launchctlFailure(result, "bootout");
@@ -861,234 +855,14 @@ async function stopLaunchdService(facts, unit, deps = {}, expectedPid) {
861
855
  * credentials, `host.log` and the launchd private logs are never removed.
862
856
  */
863
857
  async function uninstallLaunchdUnit(facts, unit, deps = {}, expectedPid) {
864
- assertLaunchdFileIdentity(unit, facts, deps);
865
- const observed = await inspectLaunchdService(unit, deps);
866
- if (observed.kind === "unknown") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the loaded job state is not recognizable; refusing to uninstall");
867
- if (observed.kind === "loaded") {
868
- if (!launchdServiceMatches(facts, unit, observed.service)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the loaded job does not match this profile plist; refusing to remove the job");
869
- await stopLaunchdService(facts, unit, deps, expectedPid);
870
- }
871
- assertLaunchdFileIdentity(unit, facts, deps);
858
+ await stopLaunchdService(facts, unit, deps, expectedPid);
859
+ assertLaunchdFileIdentity(unit);
872
860
  try {
873
861
  unlinkSync(unit.filePath);
874
862
  } catch (error) {
875
863
  if (error.code === "ENOENT") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist vanished during uninstall");
876
864
  throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the profile plist could not be removed", error);
877
865
  }
878
- if (inspectOwnedLaunchdUnit(facts, deps).kind !== "none") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist could not be confirmed removed");
879
- }
880
- /** The exact `ProgramArguments` block this product's renderer has always written. */
881
- const GENERATED_PROGRAM_ARGUMENTS_SPAN = {
882
- head: " <key>ProgramArguments</key>\n <array>\n <string>",
883
- tail: "</string>\n </array>\n"
884
- };
885
- /** The exact `X-DshPiTuiInstallBuild` block this product's renderer writes. */
886
- const GENERATED_INSTALL_BUILD_SPAN = {
887
- head: " <key>X-DshPiTuiInstallBuild</key>\n <string>",
888
- tail: "</string>\n"
889
- };
890
- /** The stable product entry suffix shared by every legal package layout. */
891
- const PRODUCT_ENTRY_SUFFIX = "/node_modules/@xmoon76/dsh-pi-tui/dist/local-host.mjs";
892
- /**
893
- * Prove one old `ProgramArguments[1]` was generated by THIS Profile's install.
894
- *
895
- * A matching package name or a pnpm directory spelling only proves a layout,
896
- * not generation provenance. Provenance requires the old package to live under
897
- * THIS Profile's own `node_modules` layout (the real DSH install layout), to be
898
- * readable, to be this product, and to have a computed build identity equal to
899
- * the plist's recorded `X-DshPiTuiInstallBuild`. A pruned old package or any
900
- * user pin outside this Profile (external store, another Profile, global
901
- * install) cannot prove provenance and is preserved as user-managed.
902
- */
903
- function proveGeneratedEntryForProfile(entryValue, facts, recordedBuild) {
904
- if (!entryValue.startsWith(`${facts.profileRealpath}/node_modules/`)) return false;
905
- let packageRoot;
906
- let manifest;
907
- try {
908
- packageRoot = realpathSync(dirname(dirname(entryValue)));
909
- manifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
910
- } catch {
911
- return false;
912
- }
913
- if (manifest === null || typeof manifest !== "object" || manifest.name !== "@xmoon76/dsh-pi-tui") return false;
914
- try {
915
- return computeBuildId(packageRoot, readInstalledDshVersion(facts.dshAnchor)) === recordedBuild;
916
- } catch {
917
- return false;
918
- }
919
- }
920
- /**
921
- * Locate the product's EXACT generated `ProgramArguments` block: precisely two
922
- * `<string>` children whose first value is the renderer's node executable form
923
- * and whose second value is an accepted product Host entry path. The lexical
924
- * span must equal the renderer's exact bytes; any reordering, binary plist,
925
- * wrapper, extra argument or another program is not our generated block and
926
- * returns `undefined`.
927
- */
928
- function locateGeneratedProgramArguments(content, facts) {
929
- const decoded = decodeLaunchdPlist(content);
930
- const argv = decoded.ProgramArguments;
931
- if (!Array.isArray(argv) || argv.length !== 2 || argv.some((value) => typeof value !== "string")) return void 0;
932
- const [nodeValue, entryValue] = argv;
933
- if (nodeValue !== facts.nodePath) return void 0;
934
- if (!entryValue.endsWith(PRODUCT_ENTRY_SUFFIX)) return void 0;
935
- const recordedBuild = decoded["X-DshPiTuiInstallBuild"];
936
- if (typeof recordedBuild !== "string" || !/^[0-9a-f]{64}$/u.test(recordedBuild)) return void 0;
937
- const entryStart = content.indexOf(GENERATED_PROGRAM_ARGUMENTS_SPAN.head);
938
- if (entryStart < 0) return void 0;
939
- const valueStart = entryStart + GENERATED_PROGRAM_ARGUMENTS_SPAN.head.length;
940
- const firstTail = content.indexOf("</string>\n <string>", valueStart);
941
- if (firstTail < 0) return void 0;
942
- const secondStart = firstTail + 22;
943
- const tailStart = content.indexOf(GENERATED_PROGRAM_ARGUMENTS_SPAN.tail, secondStart);
944
- if (tailStart < 0) return void 0;
945
- const end = tailStart + GENERATED_PROGRAM_ARGUMENTS_SPAN.tail.length;
946
- if (content.slice(entryStart, end) !== ` <key>ProgramArguments</key>\n <array>\n <string>${nodeValue}</string>\n <string>${entryValue}</string>\n </array>\n`) return void 0;
947
- if (content.indexOf(" <key>ProgramArguments</key>", entryStart + 1) >= 0) return void 0;
948
- return {
949
- oldEntry: entryValue,
950
- recordedBuild,
951
- start: entryStart,
952
- end
953
- };
954
- }
955
- /** Locate the product's exact generated `X-DshPiTuiInstallBuild` block. */
956
- function locateGeneratedInstallBuild(content) {
957
- const start = content.indexOf(GENERATED_INSTALL_BUILD_SPAN.head);
958
- if (start < 0) return void 0;
959
- const valueStart = start + GENERATED_INSTALL_BUILD_SPAN.head.length;
960
- const tailStart = content.indexOf(GENERATED_INSTALL_BUILD_SPAN.tail, valueStart);
961
- if (tailStart < 0) return void 0;
962
- const end = tailStart + GENERATED_INSTALL_BUILD_SPAN.tail.length;
963
- const block = content.slice(start, end);
964
- const value = block.slice(GENERATED_INSTALL_BUILD_SPAN.head.length, block.length - GENERATED_INSTALL_BUILD_SPAN.tail.length);
965
- if (!/^[0-9a-f]{64}$/u.test(value)) return void 0;
966
- if (content.indexOf(GENERATED_INSTALL_BUILD_SPAN.head, start + 1) >= 0) return void 0;
967
- return {
968
- start,
969
- end
970
- };
971
- }
972
- /**
973
- * The ONE bounded migration of an old PRODUCT-GENERATED plist fragment to the
974
- * current install. `inspect` is read-only and may run before a stop; `apply`
975
- * performs the atomic in-place replacement and is legal ONLY after the old
976
- * Host kernel identity is proven gone and the loaded job is proven booted out.
977
- *
978
- * The ONLY bytes ever modified are a PROVEN generated `ProgramArguments[1]`
979
- * (old installed entry -> the current stable named entry) and, when the
980
- * arguments actually migrate, the adjacent generated `X-DshPiTuiInstallBuild`
981
- * value. Provenance requires the old package to live under THIS Profile's own
982
- * `node_modules` layout and the recorded install-build identity to equal its
983
- * computed build identity. A user-customized argv, an external pin to another
984
- * Profile/store/build, a pruned old package,
985
- * a restructured XML, a binary plist or any other unrecognized shape is
986
- * preserved byte-for-byte and reported `user-managed`: the plist is then
987
- * executed exactly as the user wrote it and the resulting Host is authenticated
988
- * (or truthfully reported `other-build`).
989
- */
990
- function prepareOwnedLaunchdForCurrentInstall(facts, unit, deps, mode) {
991
- assertLaunchdFileIdentity(unit, facts, deps);
992
- assertLaunchdProfileAnchors(facts, unit.content);
993
- const generated = locateGeneratedProgramArguments(unit.content, facts);
994
- if (generated === void 0) return { plan: {
995
- kind: "no-op",
996
- reason: "user-managed"
997
- } };
998
- const namedEntry = resolveNamedLaunchdEntry(facts);
999
- if (generated.oldEntry === namedEntry) return { plan: {
1000
- kind: "no-op",
1001
- reason: "current"
1002
- } };
1003
- if (!proveGeneratedEntryForProfile(generated.oldEntry, facts, generated.recordedBuild)) return { plan: {
1004
- kind: "no-op",
1005
- reason: "user-managed"
1006
- } };
1007
- const plan = {
1008
- kind: "migrate",
1009
- namedEntry
1010
- };
1011
- if (mode === "inspect") return { plan };
1012
- const current = inspectOwnedLaunchdUnit(facts, deps);
1013
- if (current.kind !== "owned" || current.unit.filePath !== unit.filePath || current.unit.content !== unit.content || current.unit.device !== unit.device || current.unit.inode !== unit.inode) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist changed before the migration was applied");
1014
- const reGenerated = locateGeneratedProgramArguments(current.unit.content, facts);
1015
- if (reGenerated === void 0 || reGenerated.oldEntry !== generated.oldEntry) return { plan: {
1016
- kind: "no-op",
1017
- reason: "user-managed"
1018
- } };
1019
- let next = spliceString(current.unit.content, generated.start, generated.end, [
1020
- " <key>ProgramArguments</key>\n <array>\n <string>",
1021
- encodePlistValue(facts.nodePath, "node path"),
1022
- "</string>\n <string>",
1023
- encodePlistValue(namedEntry, "Host entry path"),
1024
- "</string>\n </array>\n"
1025
- ].join(""));
1026
- const buildSpan = locateGeneratedInstallBuild(next);
1027
- if (buildSpan !== void 0) next = spliceString(next, buildSpan.start, buildSpan.end, [
1028
- " <key>X-DshPiTuiInstallBuild</key>\n <string>",
1029
- encodePlistValue(facts.buildId, "install build"),
1030
- "</string>\n"
1031
- ].join(""));
1032
- decodeLaunchdPlist(next);
1033
- const written = replacePlistAtomic(current.unit.filePath, next);
1034
- const verified = inspectOwnedLaunchdUnit(facts, deps);
1035
- if (verified.kind !== "owned" || verified.unit.content !== written) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the migrated plist could not be confirmed after the replacement");
1036
- const argv = decodeLaunchdPlist(verified.unit.content).ProgramArguments;
1037
- if (!Array.isArray(argv) || argv.length !== 2 || argv[1] !== namedEntry) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the migrated plist does not decode to the stable named entry");
1038
- return {
1039
- plan,
1040
- unit: verified.unit
1041
- };
1042
- }
1043
- /** Replace an exact byte span of one string. */
1044
- function spliceString(content, start, end, replacement) {
1045
- return content.slice(0, start) + replacement + content.slice(end);
1046
- }
1047
- /**
1048
- * Atomically replace one owned plist file in its own directory with the
1049
- * original file mode, through a same-directory temp file, native `plutil`
1050
- * validation, `fsync` and `rename`. The target must still be a regular
1051
- * non-symlink file; a replaced or vanished target is a hard refusal (never a
1052
- * blind overwrite).
1053
- */
1054
- function replacePlistAtomic(filePath, content) {
1055
- let originalMode;
1056
- try {
1057
- const info = lstatSync(filePath);
1058
- if (!info.isFile() || info.isSymbolicLink()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist is not a regular file for an in-place migration");
1059
- originalMode = info.mode & 511;
1060
- } catch (error) {
1061
- if (error instanceof LocalScopeError) throw error;
1062
- throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist could not be re-read before the migration", error);
1063
- }
1064
- const tempPath = join(dirname(filePath), `.${basename(filePath)}.${String(process.pid)}.${randomUUID()}.tmp`);
1065
- let fd;
1066
- try {
1067
- fd = openSync(tempPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, originalMode);
1068
- fchmodSync(fd, originalMode);
1069
- const buffer = Buffer.from(content, "utf8");
1070
- let offset = 0;
1071
- while (offset < buffer.length) offset += writeSync(fd, buffer, offset, buffer.length - offset);
1072
- fsyncSync(fd);
1073
- closeSync(fd);
1074
- fd = void 0;
1075
- const lint = spawnSync("/usr/bin/plutil", [
1076
- "-lint",
1077
- "-s",
1078
- "--",
1079
- tempPath
1080
- ], { timeout: 5e3 });
1081
- if (lint.error !== void 0 || lint.status !== 0) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the migrated plist failed the native lint before publication");
1082
- renameSync(tempPath, filePath);
1083
- } catch (error) {
1084
- if (fd !== void 0) closeSync(fd);
1085
- try {
1086
- unlinkSync(tempPath);
1087
- } catch {}
1088
- if (error instanceof LocalScopeError) throw error;
1089
- throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the migrated plist could not be installed atomically", error);
1090
- }
1091
- return content;
1092
866
  }
1093
867
  //#endregion
1094
868
  //#region src/app/remote-process/local-host-manager.ts
@@ -1103,11 +877,8 @@ function replacePlistAtomic(filePath, content) {
1103
877
  * start`. On macOS no plist keeps the same detached path; an owned plist means
1104
878
  * one verified launchd bootstrap/kickstart through the Darwin adapter. The
1105
879
  * Linux `installProfileHostUnit()` and macOS `installLaunchdUnit()` are the ONLY
1106
- * paths that create a service definition; the ONE bounded exception is
1107
- * `prepareOwnedProfileUnitForCurrentInstall()`, which an EXPLICIT CLI
1108
- * `start`/`restart` uses to migrate a recognized pre-existing generated unit
1109
- * field pair to the stable Profile entry. None of them starts, stops, enables,
1110
- * auto-restarts or migrates a Host.
880
+ * paths that create a service definition. They never start, stop, enable or
881
+ * auto-restart a Host, and never rewrite an existing definition.
1111
882
  *
1112
883
  * `systemctl`/`journalctl` and `/bin/launchctl` are invoked through fixed
1113
884
  * argument arrays. A missing command can only affect the explicit service-
@@ -1156,11 +927,11 @@ function selectRuntimeDir(uid) {
1156
927
  if (ambient !== void 0 && ambient !== "") return ambient;
1157
928
  }
1158
929
  function systemctlEnv(runtimeDir) {
1159
- if (runtimeDir === void 0) return { ...process.env };
1160
- return {
1161
- ...process.env,
1162
- XDG_RUNTIME_DIR: runtimeDir
1163
- };
930
+ const env = { ...process.env };
931
+ scrubProgramResumeEnvironment(env);
932
+ if (runtimeDir === void 0) return env;
933
+ env.XDG_RUNTIME_DIR = runtimeDir;
934
+ return env;
1164
935
  }
1165
936
  /**
1166
937
  * Run exactly one fixed `systemctl` invocation: `shell: false`, an absolute
@@ -1298,10 +1069,6 @@ function encodeUnitPath(value, label) {
1298
1069
  function encodeEnvironment(key, value) {
1299
1070
  return `Environment=${encodeUnitValue(`${key}=${value}`, `environment ${key}`, false)}`;
1300
1071
  }
1301
- /** The deterministic profile-identity digest stored in the unit owner metadata. */
1302
- function profileIdentityDigest(profileRealpath) {
1303
- return createHash("sha256").update(`dsh-pi-tui/profile-identity/1\0${profileRealpath}`).digest("hex");
1304
- }
1305
1072
  /**
1306
1073
  * Build the readable, ASCII-safe profile slug used ONLY in the unit file name.
1307
1074
  * Full scopeId ownership is always validated separately; the slug never grants
@@ -1327,8 +1094,6 @@ function renderUnitContent(facts) {
1327
1094
  "Description=dsh-pi-tui local Host (profile-scoped)",
1328
1095
  `X-DshPiTuiOwner=${UNIT_OWNER_MARKER}`,
1329
1096
  `X-DshPiTuiScopeId=${facts.scopeId}`,
1330
- `X-DshPiTuiProfileIdentity=${profileIdentityDigest(facts.profileRealpath)}`,
1331
- `X-DshPiTuiInstallBuild=${facts.buildId}`,
1332
1097
  "StartLimitIntervalSec=60s",
1333
1098
  "StartLimitBurst=3",
1334
1099
  "",
@@ -1345,6 +1110,9 @@ function renderUnitContent(facts) {
1345
1110
  "KillMode=control-group",
1346
1111
  "StandardOutput=journal",
1347
1112
  "StandardError=journal",
1113
+ "",
1114
+ "[Install]",
1115
+ "WantedBy=default.target",
1348
1116
  ""
1349
1117
  ].join("\n");
1350
1118
  }
@@ -1410,13 +1178,9 @@ function inspectTrustedDshAnchor(path) {
1410
1178
  if (!lstatSync(real).isFile()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor must be a regular file");
1411
1179
  return real;
1412
1180
  }
1413
- /** Collect and validate the exact installed facts one service definition is rendered from. */
1414
- function collectUnitFacts(options) {
1415
- const nodePath = inspectTrustedExecutable(process.execPath, "node executable");
1416
- if (!isAbsolute(options.hostEntryPath)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the Host entry path must be absolute");
1417
- inspectOwnedRegular(options.hostEntryPath, "Host entry");
1418
- assertEntrySelfLocation(options.hostEntryPath, "HOST_MANAGER_UNIT_CONFLICT", "Host entry");
1419
- const dshAnchor = inspectTrustedDshAnchor(options.dshAnchor);
1181
+ /** Validate the DSH install anchor and its exact runtime version once. */
1182
+ function readVerifiedDshAnchor(path, dshVersion) {
1183
+ const dshAnchor = inspectTrustedDshAnchor(path);
1420
1184
  let manifest;
1421
1185
  try {
1422
1186
  manifest = JSON.parse(readFileSync(dshAnchor, "utf8"));
@@ -1424,13 +1188,21 @@ function collectUnitFacts(options) {
1424
1188
  throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor manifest is unreadable", error);
1425
1189
  }
1426
1190
  if (manifest === null || typeof manifest !== "object" || manifest.name !== "@deepseek-ai/dsh") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor is not @deepseek-ai/dsh");
1427
- if (manifest.version !== options.scope.dshVersion) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor version does not match the installed runtime pin");
1191
+ if (manifest.version !== dshVersion) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor version does not match the installed runtime pin");
1192
+ return dshAnchor;
1193
+ }
1194
+ /** Collect and validate the exact installed facts one service definition is rendered from. */
1195
+ function collectUnitFacts(options) {
1196
+ const nodePath = inspectTrustedExecutable(process.execPath, "node executable");
1197
+ if (!isAbsolute(options.hostEntryPath)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the Host entry path must be absolute");
1198
+ inspectOwnedRegular(options.hostEntryPath, "Host entry");
1199
+ assertEntrySelfLocation(options.hostEntryPath, "HOST_MANAGER_UNIT_CONFLICT", "Host entry");
1200
+ const dshAnchor = readVerifiedDshAnchor(options.dshAnchor, options.scope.dshVersion);
1428
1201
  return {
1429
1202
  dshHome: options.scope.dshHome,
1430
1203
  profileRealpath: options.scope.profileRealpath,
1431
1204
  profile: options.profile,
1432
1205
  scopeId: options.scope.scopeId,
1433
- buildId: options.scope.buildId,
1434
1206
  nodePath,
1435
1207
  hostEntryPath: options.hostEntryPath,
1436
1208
  dshAnchor
@@ -1696,15 +1468,11 @@ function readUnitFileIdentity(filePath) {
1696
1468
  throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit configuration could not be read", error);
1697
1469
  }
1698
1470
  }
1699
- /** Runtime directives belong to the user and systemd; only metadata proves scope. */
1471
+ /** Runtime directives belong to the user and systemd; only owner and full scope prove identity. */
1700
1472
  function inspectUnitIdentity(content, scope) {
1701
1473
  const lines = content.split("\n");
1702
1474
  if (readUnitMetadata(lines, "X-DshPiTuiOwner") !== UNIT_OWNER_MARKER) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit is not owned by this product");
1703
1475
  if (readUnitMetadata(lines, "X-DshPiTuiScopeId") !== scope.scopeId) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit belongs to another profile scope");
1704
- if (readUnitMetadata(lines, "X-DshPiTuiProfileIdentity") !== profileIdentityDigest(scope.profileRealpath)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit belongs to another canonical profile");
1705
- const installBuild = readUnitMetadata(lines, "X-DshPiTuiInstallBuild");
1706
- if (!/^[0-9a-f]{64}$/u.test(installBuild)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit has no valid install build identity");
1707
- return installBuild;
1708
1476
  }
1709
1477
  /** Compare this operation's observation, never the generated default template. */
1710
1478
  function assertUnitFileIdentity(unit) {
@@ -1724,12 +1492,12 @@ function inspectOwnedProfileUnit(scope, profile, unitDir) {
1724
1492
  throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit path is not accessible", error);
1725
1493
  }
1726
1494
  const file = readUnitFileIdentity(filePath);
1495
+ inspectUnitIdentity(file.content, scope);
1727
1496
  return {
1728
1497
  kind: "owned",
1729
1498
  unitName,
1730
1499
  unitDir: dir,
1731
1500
  filePath,
1732
- installBuild: inspectUnitIdentity(file.content, scope),
1733
1501
  ...file
1734
1502
  };
1735
1503
  }
@@ -1800,9 +1568,7 @@ async function stopOwnedProfileUnit(unit, runtimeDir, systemctl, timeoutMs = UNI
1800
1568
  * independent Host is not unit-supervised and is never stopped by uninstall. The
1801
1569
  * caller owns the `daemon-reload` that follows.
1802
1570
  */
1803
- function uninstallOwnedProfileUnit(unit, scope, profile) {
1804
- const current = inspectOwnedProfileUnit(scope, profile, unit.unitDir);
1805
- if (current.kind !== "owned" || current.filePath !== unit.filePath || current.device !== unit.device || current.inode !== unit.inode) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit file changed during the transition");
1571
+ function uninstallOwnedProfileUnit(unit) {
1806
1572
  assertUnitFileIdentity(unit);
1807
1573
  try {
1808
1574
  unlinkSync(unit.filePath);
@@ -1812,6 +1578,23 @@ function uninstallOwnedProfileUnit(unit, scope, profile) {
1812
1578
  }
1813
1579
  }
1814
1580
  /**
1581
+ * Submit ONE native `systemctl --user enable|disable <unit>` for an already
1582
+ * verified owned profile unit. Enablement, install links and the manager's
1583
+ * reload are systemd's responsibility: this adapter never parses Install
1584
+ * directives, edits user configuration, retries or reports a Host transition.
1585
+ */
1586
+ async function setOwnedProfileUnitEnablement(unit, verb, runtimeDir, systemctl) {
1587
+ assertUnitFileIdentity(unit);
1588
+ const result = await systemctl([
1589
+ "--user",
1590
+ "--no-pager",
1591
+ "--no-ask-password",
1592
+ verb,
1593
+ unit.unitName
1594
+ ], runtimeDir);
1595
+ if (result.kind !== "exited" || result.code !== 0) throw new LocalScopeError("HOST_MANAGER_ERROR", `managed Host: systemctl could not ${verb} the unit`);
1596
+ }
1597
+ /**
1815
1598
  * Prove the manager does not already run THIS unit name from another source
1816
1599
  * before a fresh high-priority unit file may shadow it. A loaded definition
1817
1600
  * with a different FragmentPath is either a foreign service (must be refused,
@@ -1853,7 +1636,7 @@ function requireLinuxUid() {
1853
1636
  * path that writes a unit: it proves the user manager is reachable before any
1854
1637
  * write (an empty target directory is legitimately absent from `UnitPath`),
1855
1638
  * installs the rendered file atomically (never overwriting user content),
1856
- * re-verifies the same-profile metadata/build identity and reloads/verifies the
1639
+ * re-verifies the same-profile owner/scope identity and reloads/verifies the
1857
1640
  * manager's real `LoadState`/`FragmentPath`. It never starts, stops,
1858
1641
  * enables or restarts a unit and never creates a Client/Host.
1859
1642
  */
@@ -1958,195 +1741,12 @@ function rollbackFreshUnit(unit) {
1958
1741
  return error instanceof Error ? error : new Error(String(error));
1959
1742
  }
1960
1743
  }
1961
- /** Decode ONE canonical `encodeUnitValue(..., commandLine: true)` double-quoted token. */
1962
- function decodeCommandToken(text, start) {
1963
- if (text[start] !== "\"") return void 0;
1964
- let value = "";
1965
- let index = start + 1;
1966
- for (; index < text.length; index += 1) {
1967
- const character = text[index];
1968
- if (character === "\"") return {
1969
- raw: text.slice(start, index + 1),
1970
- value,
1971
- end: index + 1
1972
- };
1973
- if (character === "\\") {
1974
- const escaped = text[index + 1];
1975
- if (escaped !== "\\" && escaped !== "\"") return void 0;
1976
- value += escaped;
1977
- index += 1;
1978
- continue;
1979
- }
1980
- if (character === "%" || character === "$") {
1981
- if (text[index + 1] !== character) return void 0;
1982
- value += character;
1983
- index += 1;
1984
- continue;
1985
- }
1986
- value += character;
1987
- }
1988
- }
1989
- /**
1990
- * Recognize the ONE generated command line: exactly two canonical encoded
1991
- * tokens (absolute Node executable and a physical PiTui `local-host.mjs`). The
1992
- * historical root may already be gone; then only the recognizable published
1993
- * layout is required. A root that is still accessible must declare this exact
1994
- * package. Anything else is user configuration and returns `undefined`.
1995
- */
1996
- function parseGeneratedExecStart(value) {
1997
- const node = decodeCommandToken(value, 0);
1998
- if (node === void 0 || value[node.end] !== " ") return void 0;
1999
- const host = decodeCommandToken(value, node.end + 1);
2000
- if (host === void 0 || host.end !== value.length) return void 0;
2001
- if (!isAbsolute(node.value) || !isAbsolute(host.value)) return void 0;
2002
- if (!host.value.endsWith("/node_modules/@xmoon76/dsh-pi-tui/dist/local-host.mjs")) return void 0;
2003
- if (existsSync(host.value)) try {
2004
- installedPackageRootFromEntry(pathToFileURL(host.value).href);
2005
- } catch {
2006
- return;
2007
- }
2008
- return {
2009
- line: `ExecStart=${value}`,
2010
- nodeToken: node.raw,
2011
- hostEntryPath: host.value
2012
- };
2013
- }
2014
- /** Find the single PiTui-generated `ExecStart=` of one unit, if it is recognized. */
2015
- function inspectGeneratedExecStart(content) {
2016
- let section = "";
2017
- let found;
2018
- let count = 0;
2019
- for (const line of content.split("\n")) {
2020
- const sectionMatch = /^\[([^\]]+)\]$/u.exec(line);
2021
- if (sectionMatch !== null) {
2022
- section = sectionMatch[1];
2023
- continue;
2024
- }
2025
- if (!/^\s*ExecStart\s*=/u.test(line)) continue;
2026
- count += 1;
2027
- if (count > 1 || section !== "Service" || !line.startsWith("ExecStart=")) return void 0;
2028
- found = {
2029
- line,
2030
- value: line.slice(10)
2031
- };
2032
- }
2033
- if (found === void 0) return void 0;
2034
- return parseGeneratedExecStart(found.value);
2035
- }
2036
- /** The current user may replace this regular main unit file in place. */
2037
- function inspectMigrationWriteAdmission(unit, uid) {
2038
- let info;
2039
- try {
2040
- info = lstatSync(unit.filePath);
2041
- } catch (error) {
2042
- throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit changed during the migration plan", error);
2043
- }
2044
- if (info.isSymbolicLink()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit is a user-managed symlink; its configuration source is never rewritten");
2045
- if (!info.isFile()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit is not a regular file");
2046
- if (info.uid !== uid) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit is not owned by the current user");
2047
- if ((info.mode & 128) === 0) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit is not writable by the current user");
2048
- try {
2049
- accessSync(unit.unitDir, constants.W_OK);
2050
- } catch (error) {
2051
- throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the user unit directory is not writable", error);
2052
- }
2053
- return info.mode & 511;
2054
- }
2055
- /** Rewrite exactly the two generated fields; every other byte is preserved. */
2056
- function migrateGeneratedUnitContent(content, generated, namedEntry, buildId) {
2057
- const execStart = `ExecStart=${generated.nodeToken} ${encodeUnitValue(namedEntry, "Host entry path", true)}`;
2058
- let execStartReplaced = false;
2059
- let buildReplaced = false;
2060
- const migrated = content.split("\n").map((line) => {
2061
- if (line === generated.line) {
2062
- execStartReplaced = true;
2063
- return execStart;
2064
- }
2065
- if (line.startsWith("X-DshPiTuiInstallBuild=")) {
2066
- buildReplaced = true;
2067
- return `X-DshPiTuiInstallBuild=${buildId}`;
2068
- }
2069
- return line;
2070
- });
2071
- if (!execStartReplaced || !buildReplaced) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the generated unit fields are not the planned shape");
2072
- return migrated.join("\n");
2073
- }
2074
- /** Atomically replace the OWNED main unit file, preserving its original mode. */
2075
- function replaceOwnedUnitFile(unit, content, mode) {
2076
- const tempPath = join(unit.unitDir, `.${unit.unitName}.${String(process.pid)}.${randomUUID()}.tmp`);
2077
- let fd;
2078
- try {
2079
- fd = openSync(tempPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, mode);
2080
- fchmodSync(fd, mode);
2081
- const buffer = Buffer.from(content, "utf8");
2082
- let offset = 0;
2083
- while (offset < buffer.length) offset += writeSync(fd, buffer, offset, buffer.length - offset);
2084
- fsyncSync(fd);
2085
- closeSync(fd);
2086
- fd = void 0;
2087
- assertUnitFileIdentity(unit);
2088
- renameSync(tempPath, unit.filePath);
2089
- } catch (error) {
2090
- if (fd !== void 0) closeSync(fd);
2091
- try {
2092
- unlinkSync(tempPath);
2093
- } catch {}
2094
- if (error instanceof LocalScopeError) throw error;
2095
- throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the migrated unit could not be written", error);
2096
- } finally {
2097
- try {
2098
- unlinkSync(tempPath);
2099
- } catch {}
2100
- }
2101
- }
2102
- /**
2103
- * Prepare the Profile unit for the CURRENT installed package, for the explicit
2104
- * CLI `start`/`restart` paths only. `inspect` never writes and proves whether the
2105
- * `apply` rewrite is possible before a Host is stopped; `apply` performs the one
2106
- * bounded atomic rewrite plus manager reload and re-verifies the manager source.
2107
- * A user-custom `ExecStart` and a unit already pointing at the stable entry are
2108
- * byte-preserved no-ops. There is no upgrade state, parser or manager here.
2109
- */
2110
- async function prepareOwnedProfileUnitForCurrentInstall(options, deps = {}) {
2111
- const uid = requireLinuxUid();
2112
- const unitDir = deps.unitDir !== void 0 ? deps.unitDir(uid) : inspectExistingUserUnitDir();
2113
- if (unitDir === void 0) return { kind: "none" };
2114
- const inspected = inspectOwnedProfileUnit(options.scope, options.profile, unitDir);
2115
- if (inspected.kind === "none") return { kind: "none" };
2116
- const systemctl = deps.systemctl ?? runSystemctl;
2117
- const runtimeDir = selectRuntimeDir(uid);
2118
- if ((await queryOwnedProfileUnit(inspected, runtimeDir, systemctl)).loadState === "not-found") return { kind: "not-loaded" };
2119
- const generated = inspectGeneratedExecStart(inspected.content);
2120
- if (generated === void 0) return { kind: "unchanged" };
2121
- if (generated.hostEntryPath === stableProfileHostEntry(options.scope)) return { kind: "unchanged" };
2122
- const namedEntry = resolveStableProfileHostEntry(options.scope, options.hostEntryPath);
2123
- const mode = inspectMigrationWriteAdmission(inspected, uid);
2124
- if (options.mode === "inspect") return { kind: "migration-required" };
2125
- const content = migrateGeneratedUnitContent(inspected.content, generated, namedEntry, options.scope.buildId);
2126
- assertUnitFileIdentity(inspected);
2127
- const beforeWrite = await queryOwnedProfileUnit(inspected, runtimeDir, systemctl);
2128
- if (beforeWrite.loadState === "not-found") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the installed unit is not loaded by the manager");
2129
- if (beforeWrite.activeState !== "inactive" && beforeWrite.activeState !== "failed") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the profile unit is not stopped; refusing to rewrite its command while it may start a Host");
2130
- replaceOwnedUnitFile(inspected, content, mode);
2131
- const reload = await systemctl([
2132
- "--user",
2133
- "--no-pager",
2134
- "--no-ask-password",
2135
- "daemon-reload"
2136
- ], runtimeDir);
2137
- if (reload.kind !== "exited" || reload.code !== 0) throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the migrated unit was written but systemctl daemon-reload failed; the manager load state is unconfirmed");
2138
- const refreshed = inspectOwnedProfileUnit(options.scope, options.profile, unitDir);
2139
- if (refreshed.kind !== "owned" || refreshed.filePath !== inspected.filePath || refreshed.content !== content) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the migrated unit could not be confirmed");
2140
- if ((await queryOwnedProfileUnit(refreshed, runtimeDir, systemctl)).loadState === "not-found") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the migrated unit is not loaded by the manager");
2141
- return { kind: "migrated" };
2142
- }
2143
1744
  /**
2144
1745
  * Start the public daemon Host candidate. The ONE decision input is the
2145
1746
  * installed unit fact: no unit means the basic detached Host immediately, with
2146
1747
  * no user-manager probe and no systemctl call; an installed unit must be loaded
2147
1748
  * by the real manager with a matching FragmentPath, and is then started through
2148
- * exactly one `systemctl --user start`. A different installed build is a
2149
- * diagnostic fact, never an ownership verdict. A manager failure or unit
1749
+ * exactly one `systemctl --user start`. A manager failure or unit
2150
1750
  * conflict is thrown and NEVER degrades to a detached process; this function
2151
1751
  * never writes a unit.
2152
1752
  */
@@ -2171,14 +1771,25 @@ async function startPublicHostCandidate(options, deps = {}) {
2171
1771
  return () => void 0;
2172
1772
  }
2173
1773
  /**
2174
- * Collect the same validated installed facts for BOTH manager renderers; the
2175
- * profile identity digest is the shared canonical-profile owner.
1774
+ * Validate only the canonical DSH anchor and profile facts needed to read an
1775
+ * installed LaunchAgent. This deliberately does not validate the current Node,
1776
+ * Host entry or build.
2176
1777
  */
1778
+ function collectLaunchdProfileFacts(scope, profile, dshAnchor) {
1779
+ return {
1780
+ dshHome: scope.dshHome,
1781
+ scopeDir: scope.dir,
1782
+ profileRealpath: scope.profileRealpath,
1783
+ profile,
1784
+ scopeId: scope.scopeId,
1785
+ dshAnchor: readVerifiedDshAnchor(dshAnchor, scope.dshVersion)
1786
+ };
1787
+ }
1788
+ /** Collect the validated installed facts needed to render a new LaunchAgent. */
2177
1789
  function collectLaunchdUnitFacts(options) {
2178
1790
  return {
2179
1791
  ...collectUnitFacts(options),
2180
- scopeDir: options.scope.dir,
2181
- profileIdentity: profileIdentityDigest(options.scope.profileRealpath)
1792
+ scopeDir: options.scope.dir
2182
1793
  };
2183
1794
  }
2184
1795
  /**
@@ -2192,10 +1803,11 @@ function collectLaunchdUnitFacts(options) {
2192
1803
  * qualification/peer/manual/reexec policies never consider a manager job.
2193
1804
  */
2194
1805
  async function startManagedHostCandidate(options, deps = {}) {
1806
+ if (process.platform === "win32") return spawnHostCandidate(options);
2195
1807
  if (process.platform === "darwin") {
2196
1808
  if (options.hostStartPolicy !== "public") return spawnHostCandidate(options);
2197
1809
  const launchdDeps = deps.launchd ?? {};
2198
- const facts = collectLaunchdUnitFacts(options);
1810
+ const facts = collectLaunchdProfileFacts(options.scope, options.profile, options.dshAnchor);
2199
1811
  const inspected = inspectOwnedLaunchdUnit(facts, launchdDeps);
2200
1812
  if (inspected.kind === "none") return spawnHostCandidate(options);
2201
1813
  await startLaunchdService(facts, inspected.unit, launchdDeps);
@@ -2204,6 +1816,24 @@ async function startManagedHostCandidate(options, deps = {}) {
2204
1816
  return startPublicHostCandidate(options, deps);
2205
1817
  }
2206
1818
  /**
1819
+ * The exact environment of one detached Host candidate. The Host is never an
1820
+ * OSC 7577 reporter: the protocol capability and its private handoff are
1821
+ * removed even if an older caller left them ambient.
1822
+ */
1823
+ function hostCandidateEnvironment(options, source = process.env) {
1824
+ const env = {
1825
+ ...source,
1826
+ SPLIT_PROCESS_DSH_ANCHOR: options.dshAnchor,
1827
+ SPLIT_PROCESS_PROFILE: options.profile
1828
+ };
1829
+ scrubProgramResumeEnvironment(env);
1830
+ delete env.SPLIT_PROCESS_EXTRA_PATCH;
1831
+ delete env.DSH_PI_TUI_ROLE;
1832
+ delete env.DSH_PI_TUI_HOST_ENTRY;
1833
+ delete env.DSH_PI_TUI_BACKEND;
1834
+ return env;
1835
+ }
1836
+ /**
2207
1837
  * Start one Host candidate as a detached OS process: the default basic daemon
2208
1838
  * whenever no profile unit is installed, and the internal qualification/peer/
2209
1839
  * manual path. It opens/creates the scope `host.log` (a NEW file is 0600; an
@@ -2222,21 +1852,22 @@ function spawnHostCandidate(options) {
2222
1852
  }
2223
1853
  if (!lstatSync(realEntry).isFile()) throw new LocalScopeError("HOST_START_FAILED", "managed Host: the installed Host entry must be a regular file");
2224
1854
  assertEntrySelfLocation(options.hostEntryPath, "HOST_START_FAILED", "installed Host entry");
2225
- const logPath = join(options.scope.dir, "host.log");
1855
+ const scope = "buildId" in options.scope ? options.scope : materializeBuild(options.scope, installedPackageRootFromEntry(pathToFileURL(options.hostEntryPath).href));
1856
+ const logPath = join(scope.dir, "host.log");
2226
1857
  let fd;
2227
1858
  try {
2228
- fd = openSync(logPath, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 384);
2229
- const env = {
2230
- ...process.env,
2231
- SPLIT_PROCESS_DSH_ANCHOR: options.dshAnchor,
2232
- SPLIT_PROCESS_PROFILE: options.profile
2233
- };
2234
- delete env.SPLIT_PROCESS_EXTRA_PATCH;
2235
- delete env.DSH_PI_TUI_ROLE;
2236
- delete env.DSH_PI_TUI_HOST_ENTRY;
2237
- delete env.DSH_PI_TUI_BACKEND;
1859
+ let logFlags = constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND;
1860
+ let win32LogMissing = false;
1861
+ if (process.platform === "win32") {
1862
+ const status = win32PrivateFileStatus(logPath);
1863
+ if (status === "unsafe") throw new LocalScopeError("LOCAL_FILE_UNSAFE", "managed Host: the existing Host log is not a private regular file");
1864
+ win32LogMissing = status === "missing";
1865
+ } else logFlags |= constants.O_NOFOLLOW;
1866
+ fd = openSync(logPath, logFlags, 384);
1867
+ if (win32LogMissing && win32PrivateFileStatus(logPath) !== "private") throw new LocalScopeError("LOCAL_FILE_UNSAFE", "managed Host: the Host log did not inherit a private boundary");
1868
+ const env = hostCandidateEnvironment(options);
2238
1869
  const child = spawn(process.execPath, [options.hostEntryPath], {
2239
- cwd: options.scope.profileRealpath,
1870
+ cwd: scope.profileRealpath,
2240
1871
  detached: true,
2241
1872
  stdio: [
2242
1873
  "ignore",
@@ -2329,6 +1960,27 @@ const DARWIN_IDENTITY_KEYS = [
2329
1960
  "uid",
2330
1961
  "state"
2331
1962
  ];
1963
+ /** Exact Win32 registry keys; `hostKernelIdentity` replaces `hostStarttime`. */
1964
+ const WIN32_RECORD_KEYS = [
1965
+ "schema",
1966
+ "scopeId",
1967
+ "profileRealpath",
1968
+ "instanceId",
1969
+ "hostPid",
1970
+ "hostKernelIdentity",
1971
+ "origin",
1972
+ "protocol",
1973
+ "bundleVersion",
1974
+ "dshVersion",
1975
+ "buildId"
1976
+ ];
1977
+ /** Exact Win32 kernel-identity keys. */
1978
+ const WIN32_IDENTITY_KEYS = [
1979
+ "platform",
1980
+ "pid",
1981
+ "ownerSid",
1982
+ "creationFiletime"
1983
+ ];
2332
1984
  /** Exact launch-material keys. */
2333
1985
  const LAUNCH_KEYS = [
2334
1986
  "schema",
@@ -2371,6 +2023,19 @@ function assertLoopbackOrigin(origin) {
2371
2023
  * `hostStarttime` stays between `hostPid` and `origin`.
2372
2024
  */
2373
2025
  function buildHostInstanceRecord(shared, hostIdentity) {
2026
+ if (hostIdentity.schema === 3) return {
2027
+ schema: 3,
2028
+ scopeId: shared.scopeId,
2029
+ profileRealpath: shared.profileRealpath,
2030
+ instanceId: shared.instanceId,
2031
+ hostPid: shared.hostPid,
2032
+ hostKernelIdentity: hostIdentity.hostKernelIdentity,
2033
+ origin: shared.origin,
2034
+ protocol: shared.protocol,
2035
+ bundleVersion: shared.bundleVersion,
2036
+ dshVersion: shared.dshVersion,
2037
+ buildId: shared.buildId
2038
+ };
2374
2039
  if (hostIdentity.schema === 1) return {
2375
2040
  schema: 1,
2376
2041
  scopeId: shared.scopeId,
@@ -2436,6 +2101,24 @@ function parseDarwinKernelIdentity(value, hostPid) {
2436
2101
  state: requireDecimalInteger(identity, "state", "registry.hostKernelIdentity")
2437
2102
  };
2438
2103
  }
2104
+ /** Parse the complete Win32 kernel identity. `ownerSid` is canonical SID text
2105
+ * and `creationFiletime` is an exact unsigned 64-bit decimal string. */
2106
+ function parseWin32KernelIdentity(value, hostPid) {
2107
+ const identity = assertExactObject(value, WIN32_IDENTITY_KEYS, "registry.hostKernelIdentity");
2108
+ if (identity.platform !== "win32") throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostKernelIdentity.platform must be win32");
2109
+ const pid = requirePositiveInteger(identity, "pid", "registry.hostKernelIdentity");
2110
+ if (pid !== hostPid) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostKernelIdentity.pid must equal registry.hostPid");
2111
+ const ownerSid = requireString(identity, "ownerSid", "registry.hostKernelIdentity");
2112
+ if (!/^S-\d+-\d+(?:-\d+)+$/u.test(ownerSid)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostKernelIdentity.ownerSid must be a canonical SID");
2113
+ const creationFiletime = requireDecimal(identity, "creationFiletime", "registry.hostKernelIdentity");
2114
+ if (BigInt(creationFiletime) > 18446744073709551615n) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostKernelIdentity.creationFiletime exceeds uint64");
2115
+ return {
2116
+ platform: "win32",
2117
+ pid,
2118
+ ownerSid,
2119
+ creationFiletime
2120
+ };
2121
+ }
2439
2122
  function requireDecimalInteger(record, key, label) {
2440
2123
  const value = record[key];
2441
2124
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label}.${key} must be a non-negative integer`);
@@ -2491,6 +2174,23 @@ function parseRecord(value, scope) {
2491
2174
  buildId: shared.buildId
2492
2175
  };
2493
2176
  }
2177
+ if (schema === 3) {
2178
+ const record = assertExactObject(value, WIN32_RECORD_KEYS, "registry");
2179
+ const shared = parseSharedRecord(record, scope);
2180
+ return {
2181
+ schema: 3,
2182
+ scopeId: shared.scopeId,
2183
+ profileRealpath: shared.profileRealpath,
2184
+ instanceId: shared.instanceId,
2185
+ hostPid: shared.hostPid,
2186
+ hostKernelIdentity: parseWin32KernelIdentity(record.hostKernelIdentity, shared.hostPid),
2187
+ origin: shared.origin,
2188
+ protocol: shared.protocol,
2189
+ bundleVersion: shared.bundleVersion,
2190
+ dshVersion: shared.dshVersion,
2191
+ buildId: shared.buildId
2192
+ };
2193
+ }
2494
2194
  if (schema === 2) {
2495
2195
  const record = assertExactObject(value, DARWIN_RECORD_KEYS, "registry");
2496
2196
  const shared = parseSharedRecord(record, scope);
@@ -2513,9 +2213,10 @@ function parseRecord(value, scope) {
2513
2213
  /** Reject a schema that cannot belong to the running local platform. A Linux
2514
2214
  * schema1 record on macOS (or the reverse) is not a candidate this process may
2515
2215
  * authenticate, spawn around or treat as a readiness proof. */
2516
- function assertRecordSchemaPlatform(record) {
2517
- if (record.schema === 1 && process.platform !== "linux") throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: schema 1 is a Linux Host publication");
2518
- if (record.schema === 2 && process.platform !== "darwin") throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: schema 2 is a macOS Host publication");
2216
+ function assertRecordSchemaPlatform(record, platform = process.platform) {
2217
+ if (record.schema === 1 && platform !== "linux") throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: schema 1 is a Linux Host publication");
2218
+ if (record.schema === 2 && platform !== "darwin") throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: schema 2 is a macOS Host publication");
2219
+ if (record.schema === 3 && platform !== "win32") throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: schema 3 is a Windows Host publication");
2519
2220
  }
2520
2221
  /** The ONE record equality used by authentication and transport currentness:
2521
2222
  * the shared fields plus the schema-specific kernel identity. */
@@ -2527,6 +2228,11 @@ function sameLocalInstanceRecord(left, right) {
2527
2228
  const b = right.hostKernelIdentity;
2528
2229
  return a.platform === b.platform && a.pid === b.pid && a.bootUUID === b.bootUUID && a.uniqueId === b.uniqueId && a.parentUniqueId === b.parentUniqueId && a.processUUID === b.processUUID && a.startSec === b.startSec && a.startUsec === b.startUsec && a.ppid === b.ppid && a.pgid === b.pgid && a.sid === b.sid && a.uid === b.uid && a.state === b.state;
2529
2230
  }
2231
+ if (left.schema === 3 && right.schema === 3) {
2232
+ const a = left.hostKernelIdentity;
2233
+ const b = right.hostKernelIdentity;
2234
+ return a.platform === b.platform && a.pid === b.pid && a.ownerSid === b.ownerSid && a.creationFiletime === b.creationFiletime;
2235
+ }
2530
2236
  return false;
2531
2237
  }
2532
2238
  /** Can this Client speak the live Host's required local wire contract? */
@@ -2546,6 +2252,24 @@ function assertHostPublicationIdentity(record, scope) {
2546
2252
  * failure.
2547
2253
  */
2548
2254
  function readPrivateJsonFile(path, maxBytes, label) {
2255
+ if (process.platform === "win32") {
2256
+ const status = win32PrivateFileStatus(path);
2257
+ if (status === "missing") return void 0;
2258
+ if (status !== "private") throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} must be a private regular file`);
2259
+ let info;
2260
+ try {
2261
+ info = lstatSync(path);
2262
+ } catch (error) {
2263
+ throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} is not readable`, error);
2264
+ }
2265
+ if (info.size > maxBytes) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} exceeds ${String(maxBytes)} bytes`);
2266
+ const text = readFileSync(path, "utf8");
2267
+ try {
2268
+ return JSON.parse(text);
2269
+ } catch (error) {
2270
+ throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} is not valid JSON`, error);
2271
+ }
2272
+ }
2549
2273
  let fd;
2550
2274
  try {
2551
2275
  fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
@@ -2612,7 +2336,7 @@ function assertConnectUrl(connectUrl, record) {
2612
2336
  */
2613
2337
  function inspectHostProcess(record, procRoot = "/proc", readKernel = readKernelProcess) {
2614
2338
  assertRecordSchemaPlatform(record);
2615
- if (record.schema === 2) {
2339
+ if (record.schema === 2 || record.schema === 3) {
2616
2340
  const observed = readKernel(record.hostPid);
2617
2341
  if (observed.kind === "unknown") throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", `local discovery: the kernel identity of Host pid ${String(record.hostPid)} is unavailable`);
2618
2342
  return sameKernelProcess(record.hostKernelIdentity, observed) === "same" ? "alive" : "dead";
@@ -2744,9 +2468,9 @@ async function readAuthenticatedIdentity(record, cookie, signal) {
2744
2468
  * complete PR-1 identity. `unknown` is always `PROCESS_STARTTIME_UNAVAILABLE`;
2745
2469
  * a different/absent process is `HOST_IDENTITY_MISMATCH` (never a kill permit).
2746
2470
  */
2747
- function assertRecordedHostKernelIdentityCurrent(record, readKernel = readKernelProcess) {
2748
- assertRecordSchemaPlatform(record);
2749
- if (record.schema === 2) {
2471
+ function assertRecordedHostKernelIdentityCurrent(record, readKernel = readKernelProcess, platform = process.platform) {
2472
+ assertRecordSchemaPlatform(record, platform);
2473
+ if (record.schema === 2 || record.schema === 3) {
2750
2474
  const observed = readKernel(record.hostPid);
2751
2475
  if (observed.kind === "unknown") throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", "local discovery: the Host kernel identity is unavailable");
2752
2476
  if (sameKernelProcess(record.hostKernelIdentity, observed) !== "same") throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: the Host PID is no longer the recorded process");
@@ -2774,6 +2498,14 @@ function readHostProcessIdentity(pid = process.pid) {
2774
2498
  hostKernelIdentity: observed.identity
2775
2499
  };
2776
2500
  }
2501
+ if (process.platform === "win32") {
2502
+ const observed = readKernelProcess(pid);
2503
+ if (observed.kind !== "alive" || observed.identity.platform !== "win32") throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", "local discovery: the Host kernel identity is unavailable");
2504
+ return {
2505
+ schema: 3,
2506
+ hostKernelIdentity: observed.identity
2507
+ };
2508
+ }
2777
2509
  throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", `local discovery: no Host process identity is implemented for ${process.platform}`);
2778
2510
  }
2779
2511
  /**
@@ -2830,10 +2562,34 @@ async function ensureLocalHost(options) {
2830
2562
  }
2831
2563
  throw new LocalScopeError("HOST_START_TIMEOUT", `local discovery: no ready Host registry appeared within ${String(REGISTRY_WAIT_TIMEOUT_MS / 1e3)}s`);
2832
2564
  }
2833
- /** Write one 0600 file through an exclusively-created same-directory temp file. */
2565
+ /** Publish through an exclusively-created same-directory temp file: POSIX mode
2566
+ * 0600; on Windows a new file inherits its parent directory's ACL and must
2567
+ * satisfy the shared private-file predicate; the file itself need not carry the
2568
+ * protected bit. */
2834
2569
  function writePrivateJsonFile(path, value) {
2835
2570
  const text = `${JSON.stringify(value)}\n`;
2836
2571
  const temp = join(dirname(path), `.${basename(path)}.${String(process.pid)}.${randomUUID()}.tmp`);
2572
+ if (process.platform === "win32") {
2573
+ if (win32PrivateFileStatus(path) === "unsafe") throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${basename(path)} has a foreign or non-private existing target`);
2574
+ let fd;
2575
+ try {
2576
+ fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384);
2577
+ if (win32PrivateFileStatus(temp) !== "private") throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${basename(path)} cannot inherit a private file boundary`);
2578
+ writeFileSync(fd, text, "utf8");
2579
+ fsyncSync(fd);
2580
+ closeSync(fd);
2581
+ fd = void 0;
2582
+ renameSync(temp, path);
2583
+ } catch (error) {
2584
+ if (fd !== void 0) closeSync(fd);
2585
+ try {
2586
+ unlinkSync(temp);
2587
+ } catch {}
2588
+ if (error instanceof LocalScopeError) throw error;
2589
+ throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${basename(path)} could not be written atomically`, error);
2590
+ }
2591
+ return;
2592
+ }
2837
2593
  let fd;
2838
2594
  try {
2839
2595
  fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
@@ -2875,9 +2631,10 @@ function cleanupOwnedFiles(scope, instanceId) {
2875
2631
  for (const file of [REGISTRY_FILE, LAUNCH_FILE]) {
2876
2632
  const path = join(scope.dir, file);
2877
2633
  try {
2634
+ if (process.platform === "win32" && win32PrivateFileStatus(path) !== "private") continue;
2878
2635
  if (JSON.parse(readFileSync(path, "utf8")).instanceId === instanceId) unlinkSync(path);
2879
2636
  } catch {}
2880
2637
  }
2881
2638
  }
2882
2639
  //#endregion
2883
- export { launchdLogPaths as A, runSystemctl as C, inspectLaunchdService as D, uninstallOwnedProfileUnit as E, prepareOwnedLaunchdForCurrentInstall as M, stopLaunchdService as N, inspectOwnedLaunchdUnit as O, uninstallLaunchdUnit as P, queryOwnedProfileUnit as S, stopOwnedProfileUnit as T, collectUnitFacts as _, buildHostInstanceRecord as a, prepareOwnedProfileUnitForCurrentInstall as b, ensureLocalHost as c, readHostProcessIdentity as d, readLaunchMaterial as f, writeLocalRecord as g, writeLaunchMaterial as h, authenticateLocalHost as i, launchdServiceMatches as j, installLaunchdUnit as k, inspectHostProcess as l, sameLocalInstanceRecord as m, assertHostPublicationIdentity as n, cleanupOwnedFiles as o, readLocalRecord as p, assertRecordedHostKernelIdentityCurrent as r, connectForCookie as s, assertClientHostCompatible as t, readAuthenticatedIdentity as u, inspectOwnedProfileUnit as v, selectRuntimeDir as w, profileIdentityDigest as x, installProfileHostUnit as y };
2640
+ export { installLaunchdUnit as A, runSystemctl as C, uninstallOwnedProfileUnit as D, stopOwnedProfileUnit as E, launchdServiceMatches as M, stopLaunchdService as N, inspectLaunchdService as O, uninstallLaunchdUnit as P, queryOwnedProfileUnit as S, setOwnedProfileUnitEnablement as T, buildUnitName as _, buildHostInstanceRecord as a, inspectOwnedProfileUnit as b, ensureLocalHost as c, readHostProcessIdentity as d, readLaunchMaterial as f, writeLocalRecord as g, writeLaunchMaterial as h, authenticateLocalHost as i, launchdLogPaths as j, inspectOwnedLaunchdUnit as k, inspectHostProcess as l, sameLocalInstanceRecord as m, assertHostPublicationIdentity as n, cleanupOwnedFiles as o, readLocalRecord as p, assertRecordedHostKernelIdentityCurrent as r, connectForCookie as s, assertClientHostCompatible as t, readAuthenticatedIdentity as u, collectLaunchdProfileFacts as v, selectRuntimeDir as w, installProfileHostUnit as x, collectLaunchdUnitFacts as y };