openmeld 0.3.287 → 0.3.290

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 (137) hide show
  1. package/dist/{add-me-membership-BEXHAhjy.js → add-me-membership-inSSCZiT.js} +2 -2
  2. package/dist/{add-me-membership-BEXHAhjy.js.map → add-me-membership-inSSCZiT.js.map} +1 -1
  3. package/dist/{agents-DTdo7eeT.js → agents-Dai79qvd.js} +10 -10
  4. package/dist/{agents-DTdo7eeT.js.map → agents-Dai79qvd.js.map} +1 -1
  5. package/dist/{api-client-foundation-RM1pxGSx.js → api-client-foundation-BFlKjR9I.js} +1 -1
  6. package/dist/{api-client-foundation-i2KBsQ7r.js → api-client-foundation-DERyHDAT.js} +6 -6
  7. package/dist/{api-client-foundation-i2KBsQ7r.js.map → api-client-foundation-DERyHDAT.js.map} +1 -1
  8. package/dist/{auth-session-DRQMn41Z.js → auth-session-B2lS_bSW.js} +4 -4
  9. package/dist/{auth-session-DRQMn41Z.js.map → auth-session-B2lS_bSW.js.map} +1 -1
  10. package/dist/auth-session-Cj6PrTZ3.js +3 -0
  11. package/dist/{auth-url-Dnpds8Yf.js → auth-url-LPP-DGsD.js} +2 -2
  12. package/dist/{auth-url-Dnpds8Yf.js.map → auth-url-LPP-DGsD.js.map} +1 -1
  13. package/dist/{base-url-b30kK86t.js → base-url-DuppOOaB.js} +2 -2
  14. package/dist/{base-url-b30kK86t.js.map → base-url-DuppOOaB.js.map} +1 -1
  15. package/dist/{base-url-Mw6hstaO.js → base-url-GJgAnOwO.js} +1 -1
  16. package/dist/{channel-CFIRo4fR.js → channel-DFsCrkPT.js} +17 -6
  17. package/dist/channel-DFsCrkPT.js.map +1 -0
  18. package/dist/{client-CBTgmyFC.js → client-BoQLTU0k.js} +2 -2
  19. package/dist/{client-CBTgmyFC.js.map → client-BoQLTU0k.js.map} +1 -1
  20. package/dist/{cloud-computer-CuWSimwt.js → cloud-computer-DYQpdovK.js} +6 -6
  21. package/dist/{cloud-computer-CuWSimwt.js.map → cloud-computer-DYQpdovK.js.map} +1 -1
  22. package/dist/{command-DdMi5g2D.js → command-BMssGnS1.js} +19 -19
  23. package/dist/{command-DdMi5g2D.js.map → command-BMssGnS1.js.map} +1 -1
  24. package/dist/{computer-connection-review-B7eoK0xB.js → computer-connection-review-B2VBvkUf.js} +5 -5
  25. package/dist/{computer-connection-review-B7eoK0xB.js.map → computer-connection-review-B2VBvkUf.js.map} +1 -1
  26. package/dist/{computer-disconnect-DGsCTpe8.js → computer-disconnect-BsO7SqGv.js} +9 -9
  27. package/dist/{computer-disconnect-DGsCTpe8.js.map → computer-disconnect-BsO7SqGv.js.map} +1 -1
  28. package/dist/{computer-setup-continuation-CnIYFkOu.js → computer-setup-continuation-DN9nvTdz.js} +5 -5
  29. package/dist/{computer-setup-continuation-CnIYFkOu.js.map → computer-setup-continuation-DN9nvTdz.js.map} +1 -1
  30. package/dist/{computer-update-wait-Bm_oW5Ne.js → computer-update-wait-DjNHPLHV.js} +4 -4
  31. package/dist/{computer-update-wait-Bm_oW5Ne.js.map → computer-update-wait-DjNHPLHV.js.map} +1 -1
  32. package/dist/{context-BvLQjNGR.js → context-C6GiteNY.js} +8 -8
  33. package/dist/{context-BvLQjNGR.js.map → context-C6GiteNY.js.map} +1 -1
  34. package/dist/{daemon-device-id-D-RHe9se.js → daemon-device-id-CGV19VtH.js} +4 -4
  35. package/dist/{daemon-device-id-D-RHe9se.js.map → daemon-device-id-CGV19VtH.js.map} +1 -1
  36. package/dist/{daemon-lifecycle-journal-BK-K3kGX.js → daemon-lifecycle-journal-YFnaFEDn.js} +5 -5
  37. package/dist/{daemon-lifecycle-journal-BK-K3kGX.js.map → daemon-lifecycle-journal-YFnaFEDn.js.map} +1 -1
  38. package/dist/{daemon-runtime-lease-CslvUjEq.js → daemon-runtime-lease-CgP8D7m8.js} +1 -1
  39. package/dist/{daemon-runtime-lease-DRYVXnBQ.js → daemon-runtime-lease-IKWq2O8q.js} +2 -2
  40. package/dist/{daemon-runtime-lease-DRYVXnBQ.js.map → daemon-runtime-lease-IKWq2O8q.js.map} +1 -1
  41. package/dist/{daemon-service-contract-CsANv7K_.js → daemon-service-contract-D8osKBM6.js} +2 -2
  42. package/dist/{daemon-service-contract-CsANv7K_.js.map → daemon-service-contract-D8osKBM6.js.map} +1 -1
  43. package/dist/{daemon-service-manager-DS4kFs8x.js → daemon-service-manager-CAGPGW2q.js} +1 -1
  44. package/dist/{daemon-service-manager-a5tY3qpR.js → daemon-service-manager-DB2rSviv.js} +4 -4
  45. package/dist/{daemon-service-manager-a5tY3qpR.js.map → daemon-service-manager-DB2rSviv.js.map} +1 -1
  46. package/dist/{daemon-service-runtime-CaUu_AdU.js → daemon-service-runtime-Dnu6mxCS.js} +12 -12
  47. package/dist/{daemon-service-runtime-CaUu_AdU.js.map → daemon-service-runtime-Dnu6mxCS.js.map} +1 -1
  48. package/dist/{daemon-service-update-state-BSn45OHj.js → daemon-service-update-state-GCIZ6nGp.js} +2 -2
  49. package/dist/{daemon-service-update-state-BSn45OHj.js.map → daemon-service-update-state-GCIZ6nGp.js.map} +1 -1
  50. package/dist/{daemon-state-CTOVPwNq.js → daemon-state-C72A-n6c.js} +3 -3
  51. package/dist/{daemon-state-CTOVPwNq.js.map → daemon-state-C72A-n6c.js.map} +1 -1
  52. package/dist/{dispatch-owned-runtime-CZLplr8F.js → dispatch-owned-runtime-CoVWIxYl.js} +12 -12
  53. package/dist/{dispatch-owned-runtime-CZLplr8F.js.map → dispatch-owned-runtime-CoVWIxYl.js.map} +1 -1
  54. package/dist/{dist-53uvP0DN.js → dist-BC0SB_h-.js} +3 -3
  55. package/dist/{dist-53uvP0DN.js.map → dist-BC0SB_h-.js.map} +1 -1
  56. package/dist/{dist-BdlgY-m7.js → dist-BuqY1gad.js} +2 -2
  57. package/dist/dist-DahbdeDi.js +34 -0
  58. package/dist/{dist-D7SkvUZW.js → dist-VZtPE-jT.js} +2 -2
  59. package/dist/{dist-D7SkvUZW.js.map → dist-VZtPE-jT.js.map} +1 -1
  60. package/dist/{dist-CZyGORfc.js → dist-zOvEcl-o.js} +1 -1
  61. package/dist/{dual-view-guide-catalog-Df60SGOI.js → dual-view-guide-catalog-DJVTHfKM.js} +4 -4
  62. package/dist/{dual-view-guide-catalog-Df60SGOI.js.map → dual-view-guide-catalog-DJVTHfKM.js.map} +1 -1
  63. package/dist/{elapsed-time-jRFzKVlC.js → elapsed-time-CzR72jgL.js} +2 -2
  64. package/dist/{elapsed-time-jRFzKVlC.js.map → elapsed-time-CzR72jgL.js.map} +1 -1
  65. package/dist/{entry-CKyKfeY0.js → entry-hCEOH64N.js} +152 -82
  66. package/dist/entry-hCEOH64N.js.map +1 -0
  67. package/dist/{installation-inventory-Cm-cGiGv.js → installation-inventory-CsSfOQgL.js} +4 -4
  68. package/dist/{installation-inventory-Cm-cGiGv.js.map → installation-inventory-CsSfOQgL.js.map} +1 -1
  69. package/dist/{installer-BMX4Gbpp.js → installer-BytXmECH.js} +2 -2
  70. package/dist/{installer-BMX4Gbpp.js.map → installer-BytXmECH.js.map} +1 -1
  71. package/dist/{lock-DP8d33p_.js → lock-B0YzvcUu.js} +3 -3
  72. package/dist/lock-B0YzvcUu.js.map +1 -0
  73. package/dist/{meta-api-BpSn7MBy.js → meta-api-YLzAzgov.js} +8 -8
  74. package/dist/{meta-api-BpSn7MBy.js.map → meta-api-YLzAzgov.js.map} +1 -1
  75. package/dist/{openmeld-DI9YIFFj.js → openmeld-Dt4vpNjB.js} +43 -43
  76. package/dist/{openmeld-DI9YIFFj.js.map → openmeld-Dt4vpNjB.js.map} +1 -1
  77. package/dist/{openmeld-dev-environment-CAETyazL.js → openmeld-dev-environment-Rl0tTXNd.js} +3 -3
  78. package/dist/{openmeld-dev-environment-CAETyazL.js.map → openmeld-dev-environment-Rl0tTXNd.js.map} +1 -1
  79. package/dist/openmeld-dev.js +1 -1
  80. package/dist/{openmeld-environment-target-DydyKO8Z.js → openmeld-environment-target-KDkHbyUB.js} +4 -4
  81. package/dist/{openmeld-environment-target-DydyKO8Z.js.map → openmeld-environment-target-KDkHbyUB.js.map} +1 -1
  82. package/dist/{openmeld-maintenance-worker-C3cdKkJO.js → openmeld-maintenance-worker-BIWvvyIf.js} +16 -16
  83. package/dist/{openmeld-maintenance-worker-C3cdKkJO.js.map → openmeld-maintenance-worker-BIWvvyIf.js.map} +1 -1
  84. package/dist/{openmeld-tools-update-attempt-state-B6t53OYC.js → openmeld-tools-update-attempt-state-sK3W06wI.js} +2 -2
  85. package/dist/{openmeld-tools-update-attempt-state-B6t53OYC.js.map → openmeld-tools-update-attempt-state-sK3W06wI.js.map} +1 -1
  86. package/dist/{openmeld-tools-update-coordinator-B_Dd_-GW.js → openmeld-tools-update-coordinator-BWFtknlg.js} +31 -26
  87. package/dist/{openmeld-tools-update-coordinator-B_Dd_-GW.js.map → openmeld-tools-update-coordinator-BWFtknlg.js.map} +1 -1
  88. package/dist/{openmeld-tools-update-join-B0bVe2pL.js → openmeld-tools-update-join-vlA-GmSh.js} +4 -4
  89. package/dist/{openmeld-tools-update-join-B0bVe2pL.js.map → openmeld-tools-update-join-vlA-GmSh.js.map} +1 -1
  90. package/dist/openmeld.js +5 -5
  91. package/dist/{prepare-provider-runtime-B4go-qdR.js → prepare-provider-runtime-D4X1jiYQ.js} +46 -22
  92. package/dist/prepare-provider-runtime-D4X1jiYQ.js.map +1 -0
  93. package/dist/{prepare-session-executor-Cpq7jQJg.js → prepare-session-executor-Cwe666D0.js} +24 -24
  94. package/dist/{prepare-session-executor-Cpq7jQJg.js.map → prepare-session-executor-Cwe666D0.js.map} +1 -1
  95. package/dist/{presenter-DMoE2U_q.js → presenter-CfWGbWdq.js} +2 -2
  96. package/dist/{presenter-DMoE2U_q.js.map → presenter-CfWGbWdq.js.map} +1 -1
  97. package/dist/{process-channel-DtJ01mUI.js → process-channel-AjxeujN8.js} +2 -2
  98. package/dist/{process-channel-DtJ01mUI.js.map → process-channel-AjxeujN8.js.map} +1 -1
  99. package/dist/{runtime-CxjWWXTL.js → runtime-DVaIwyJM.js} +170 -80
  100. package/dist/runtime-DVaIwyJM.js.map +1 -0
  101. package/dist/{runtime-agent-controller-reporting-submission-Cnpnw9UC.js → runtime-agent-controller-reporting-submission-CkiUg9j0.js} +8 -8
  102. package/dist/{runtime-agent-controller-reporting-submission-Cnpnw9UC.js.map → runtime-agent-controller-reporting-submission-CkiUg9j0.js.map} +1 -1
  103. package/dist/{runtime-transport-Dg7E0ROH.js → runtime-transport-CLpKUHk_.js} +5 -1
  104. package/dist/{runtime-transport-Dg7E0ROH.js.map → runtime-transport-CLpKUHk_.js.map} +1 -1
  105. package/dist/{sensitive-operation-credentials-Dr_neVvL.js → sensitive-operation-credentials-D9DHfCDf.js} +4 -4
  106. package/dist/{sensitive-operation-credentials-Dr_neVvL.js.map → sensitive-operation-credentials-D9DHfCDf.js.map} +1 -1
  107. package/dist/{service-_kQjYdi5.js → service-BoxFPDKp.js} +104 -37
  108. package/dist/service-BoxFPDKp.js.map +1 -0
  109. package/dist/{service-account-authorization-DiSsm3hB.js → service-account-authorization-MARMxBls.js} +5 -5
  110. package/dist/{service-account-authorization-DiSsm3hB.js.map → service-account-authorization-MARMxBls.js.map} +1 -1
  111. package/dist/{service-account-control-B4Ja3gU_.js → service-account-control-D0f6SaS2.js} +13 -13
  112. package/dist/{service-account-control-B4Ja3gU_.js.map → service-account-control-D0f6SaS2.js.map} +1 -1
  113. package/dist/{service-control-capabilities-MWGiNNTg.js → service-control-capabilities-C5lV5eqZ.js} +5 -5
  114. package/dist/{service-control-capabilities-MWGiNNTg.js.map → service-control-capabilities-C5lV5eqZ.js.map} +1 -1
  115. package/dist/{service-control-capabilities-D39aQwkY.js → service-control-capabilities-DVnJWbBU.js} +1 -1
  116. package/dist/{state-Der85tER.js → state-LIaPm3LW.js} +2 -2
  117. package/dist/{state-Der85tER.js.map → state-LIaPm3LW.js.map} +1 -1
  118. package/dist/{updates-api-B8lZk9gI.js → updates-api-CV0uvAN1.js} +81 -77
  119. package/dist/updates-api-CV0uvAN1.js.map +1 -0
  120. package/dist/upgrade-Bi-kRFVX.js +3 -0
  121. package/dist/{upgrade-C8iFbxmb.js → upgrade-C23MjDuG.js} +10 -10
  122. package/dist/{upgrade-C8iFbxmb.js.map → upgrade-C23MjDuG.js.map} +1 -1
  123. package/dist/windows/openmeld-windows-process.exe +0 -0
  124. package/dist/{windows-user-task-CKb_u29X.js → windows-user-task-CR64LZEK.js} +3 -3
  125. package/dist/{windows-user-task-CKb_u29X.js.map → windows-user-task-CR64LZEK.js.map} +1 -1
  126. package/dist/{windows-user-task-zYK9uy2K.js → windows-user-task-Dr1wlrfz.js} +1 -1
  127. package/package.json +11 -11
  128. package/dist/auth-session-C9F7usbn.js +0 -3
  129. package/dist/channel-CFIRo4fR.js.map +0 -1
  130. package/dist/dist-8pH5plup.js +0 -34
  131. package/dist/entry-CKyKfeY0.js.map +0 -1
  132. package/dist/lock-DP8d33p_.js.map +0 -1
  133. package/dist/prepare-provider-runtime-B4go-qdR.js.map +0 -1
  134. package/dist/runtime-CxjWWXTL.js.map +0 -1
  135. package/dist/service-_kQjYdi5.js.map +0 -1
  136. package/dist/updates-api-B8lZk9gI.js.map +0 -1
  137. package/dist/upgrade-DECIvSJc.js +0 -3
@@ -1 +1 @@
1
- {"version":3,"file":"windows-user-task-CKb_u29X.js","names":[],"sources":["../src/local-service/lifecycle/windows-service-binary.ts","../src/local-service/lifecycle/windows-task-host.ts","../src/local-service/lifecycle/windows-user-task.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport {\n copyFile,\n mkdir,\n mkdtemp,\n open,\n rename,\n rm,\n stat,\n} from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { pruneWindowsBinaryBundle } from \"@openmeld/adapter-core/windows-system\";\nimport { WINDOWS_PROCESS_HELPER_FILENAME } from \"@openmeld/schemas\";\nimport { daemonRuntimeBundlesPath } from \"../../config/daemon-state\";\nimport type { OpenMeldPathResolutionInput } from \"../../config/paths\";\nimport type { CliBinaryReleaseInfo } from \"../../config/version-state\";\nimport type { DaemonActiveBundleState } from \"./daemon-service-bundle\";\n\nconst FINGERPRINT_PATTERN = /^[0-9a-f]{64}$/u;\n\nexport function windowsMaintenanceBinaryPath(\n bundle: DaemonActiveBundleState,\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n if (\n !(\n bundle.sourceDistFingerprint &&\n FINGERPRINT_PATTERN.test(bundle.sourceDistFingerprint)\n )\n ) {\n throw new Error(\n \"OpenMeld maintenance needs a verified Windows Service bundle.\"\n );\n }\n return join(\n daemonRuntimeBundlesPath(pathInput),\n `maintenance-${bundle.sourceDistFingerprint}`,\n \"openmeld.exe\"\n );\n}\n\nexport async function prepareWindowsMaintenanceBinary(\n bundle: DaemonActiveBundleState,\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<string> {\n const target = windowsMaintenanceBinaryPath(bundle, pathInput);\n const expected = bundle.sourceDistFingerprint;\n if (\n (await hashBinaryServiceBundle(target, true).catch(() => null)) === expected\n ) {\n return target;\n }\n if (\n (await hashBinaryServiceBundle(bundle.sourceEntryScriptPath, true)) !==\n expected\n ) {\n throw new Error(\n \"The Windows maintenance source no longer matches its verified bundle.\"\n );\n }\n const directory = dirname(target);\n if (\n await stat(directory).catch((error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n })\n ) {\n const result = await pruneWindowsBinaryBundle(directory);\n if (result !== \"removed\" && result !== \"absent\") {\n throw new Error(\n \"The existing Windows maintenance copy is still in use or contains unrecognized files.\"\n );\n }\n }\n await mkdir(daemonRuntimeBundlesPath(pathInput), { recursive: true });\n const temporary = await mkdtemp(\n join(daemonRuntimeBundlesPath(pathInput), \".maintenance-\")\n );\n try {\n for (const name of [\"openmeld.exe\", WINDOWS_PROCESS_HELPER_FILENAME]) {\n await copyFile(\n name === \"openmeld.exe\"\n ? bundle.sourceEntryScriptPath\n : join(dirname(bundle.sourceEntryScriptPath), name),\n join(temporary, name)\n );\n }\n if (\n (await hashBinaryServiceBundle(join(temporary, \"openmeld.exe\"), true)) !==\n expected\n ) {\n throw new Error(\n \"The prepared Windows maintenance copy failed verification.\"\n );\n }\n await rename(temporary, directory);\n } finally {\n await rm(temporary, { recursive: true, force: true });\n }\n return target;\n}\n\n// Windows binary_v1 bundles contain two indivisible, independently signed files.\n// Keep one bundle fingerprint for inventory, update jobs, and maintenance copies.\nexport function expectedBinaryServiceFingerprint(\n release: CliBinaryReleaseInfo\n): string {\n if (!release.platform.startsWith(\"windows-\")) {\n return release.sha256.toLowerCase();\n }\n if (!release.windows) {\n throw new Error(\n \"The selected Windows Service has no native helper metadata.\"\n );\n }\n return fingerprint(release.sha256, release.windows.processHelper.sha256);\n}\n\nexport async function hashBinaryServiceBundle(\n executablePath: string,\n windows: boolean = process.platform === \"win32\"\n): Promise<string> {\n const executableHash = await hashFile(executablePath);\n return windows\n ? fingerprint(\n executableHash,\n await hashFile(\n join(dirname(executablePath), WINDOWS_PROCESS_HELPER_FILENAME)\n )\n )\n : executableHash;\n}\n\nfunction fingerprint(executableHash: string, helperHash: string): string {\n return createHash(\"sha256\")\n .update(\n JSON.stringify([executableHash.toLowerCase(), helperHash.toLowerCase()])\n )\n .digest(\"hex\");\n}\n\nasync function hashFile(file: string): Promise<string> {\n const hash = createHash(\"sha256\");\n for await (const chunk of createReadStream(file)) {\n hash.update(chunk);\n }\n return hash.digest(\"hex\");\n}\n\n/** A valid signature does not establish the required console-free PE subsystem. */\nexport async function verifyWindowsServiceSubsystem(\n file: string\n): Promise<void> {\n const handle = await open(file, \"r\");\n try {\n const dos = Buffer.alloc(64);\n const first = await handle.read(dos, 0, dos.length, 0);\n if (\n first.bytesRead !== dos.length ||\n dos.toString(\"ascii\", 0, 2) !== \"MZ\"\n ) {\n throw new Error(\"The Windows Service artifact is not a PE executable.\");\n }\n const header = Buffer.alloc(94);\n const second = await handle.read(\n header,\n 0,\n header.length,\n dos.readUInt32LE(0x3c)\n );\n if (\n second.bytesRead !== header.length ||\n header.toString(\"ascii\", 0, 4) !== \"PE\\0\\0\" ||\n header.readUInt16LE(4) !== 0x86_64 ||\n header.readUInt16LE(24 + 68) !== 2\n ) {\n throw new Error(\n \"The selected Windows Service must be a console-free x64 executable.\"\n );\n }\n } finally {\n await handle.close();\n }\n}\n","// Task Scheduler must start a Windows-subsystem executable, not a console\n// executable that hides its window after startup. Keep the existing encoded\n// PowerShell action as the command/environment/logging owner.\n// Windows PowerShell 5.1 compiles this fixed source during guarded installation;\n// no SDK, downloaded executable, WSH/VBScript, or administrator access is needed.\nexport const WINDOWS_TASK_HOST_SOURCE = String.raw`\nusing System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\npublic static class OpenMeldTaskHostV1 {\n public static int Main(string[] args) {\n string logPath = Assembly.GetExecutingAssembly().Location + \".log\";\n try {\n // Accept only the existing OpenMeld action, never an arbitrary executable\n // or a shell-interpolated command line. Base64 contains no quoting syntax.\n if (args.Length != 7 || args[0] != \"-NoLogo\" || args[1] != \"-NoProfile\" ||\n args[2] != \"-NonInteractive\" || args[3] != \"-WindowStyle\" ||\n args[4] != \"Hidden\" || args[5] != \"-EncodedCommand\" ||\n !Regex.IsMatch(args[6], @\"\\A[A-Za-z0-9+/]+={0,2}\\z\"))\n throw new ArgumentException(\"Invalid OpenMeld task arguments.\");\n Convert.FromBase64String(args[6]);\n var start = new ProcessStartInfo();\n start.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System),\n @\"WindowsPowerShell\\v1.0\\powershell.exe\");\n start.Arguments = String.Join(\" \", args);\n start.UseShellExecute = false;\n start.CreateNoWindow = true;\n start.RedirectStandardInput = true;\n start.RedirectStandardOutput = true;\n start.RedirectStandardError = true;\n using (var log = Stream.Synchronized(new FileStream(logPath, FileMode.Append,\n FileAccess.Write, FileShare.ReadWrite)))\n using (var child = new Process()) {\n child.StartInfo = start;\n child.Start();\n child.StandardInput.Close();\n var stdout = child.StandardOutput.BaseStream.CopyToAsync(log);\n var stderr = child.StandardError.BaseStream.CopyToAsync(log);\n // Do not detach or break away from Task Scheduler's process ownership.\n // The task remains running until the action completes, and restart-on-\n // failure still receives the action's real exit code.\n child.WaitForExit();\n stdout.GetAwaiter().GetResult();\n stderr.GetAwaiter().GetResult();\n return child.ExitCode;\n }\n } catch (Exception error) {\n try { File.AppendAllText(logPath, DateTime.UtcNow.ToString(\"o\") + \" \" +\n error.GetType().Name + \": \" + error.Message + Environment.NewLine, Encoding.UTF8); }\n catch { /* Task Scheduler still receives a nonzero result if logging fails. */ }\n return 1;\n }\n }\n}\n`;\n\n// Per-task, lane-owned path: updating the maintenance host cannot replace the\n// executable of a running main Service, or vice versa. Keep v1 stable; a future\n// host format must explicitly support migration from this path.\nexport const WINDOWS_TASK_HOST_SUFFIX = \".task-host-v1.exe\";\n\n// The caller has already verified identity and acquired the lifecycle grant.\n// Build beside the target and replace atomically, never overwrite a running\n// host or fall back to a flashing console when compilation is unavailable.\nexport const WINDOWS_TASK_HOST_INSTALL_SCRIPT = `\n$hostDirectory = [IO.Path]::GetDirectoryName($hostPath)\n$null = [IO.Directory]::CreateDirectory($hostDirectory)\n$temporaryHost = Join-Path $hostDirectory ([Guid]::NewGuid().ToString('N') + '.exe')\ntry {\n Add-Type -TypeDefinition @'\n${WINDOWS_TASK_HOST_SOURCE}\n'@ -OutputAssembly $temporaryHost -OutputType WindowsApplication -ErrorAction Stop\n if ($task -and $task.State -eq 4) { throw 'OpenMeld cannot replace a background task while it is running.' }\n if ([IO.File]::Exists($hostPath)) {\n # PowerShell coerces bare $null to an empty string for this .NET parameter.\n # Pass a real null backup path; an empty path breaks repeat setup/repair.\n [IO.File]::Replace($temporaryHost, $hostPath, [NullString]::Value)\n } else {\n [IO.File]::Move($temporaryHost, $hostPath)\n }\n} finally {\n if ([IO.File]::Exists($temporaryHost)) { [IO.File]::Delete($temporaryHost) }\n}\n`;\n","import { type ExecFileException, execFile } from \"node:child_process\";\nimport { normalizeCommandEnvironment } from \"@openmeld/adapter-core/process-environment\";\nimport {\n powerShellEncodedArguments,\n resolveWindowsPowerShellPath,\n} from \"@openmeld/adapter-core/windows-system\";\nimport {\n type WindowsUserTaskAction,\n type WindowsUserTaskRequest,\n windowsUserTaskActionSchema,\n windowsUserTaskRequestSchema,\n windowsUserTaskStatusSchema,\n windowsUserTaskStoredActionSchema,\n} from \"@openmeld/schemas\";\nimport { currentDaemonServiceLifecycleLock } from \"../../config/daemon-state\";\nimport {\n attachLockProcess,\n type OpenMeldLock,\n releaseLock,\n} from \"../../config/lock\";\nimport { verifyWindowsServiceSubsystem } from \"./windows-service-binary\";\nimport { readWindowsDirectTaskAction } from \"./windows-task-command\";\nimport {\n WINDOWS_TASK_HOST_INSTALL_SCRIPT,\n WINDOWS_TASK_HOST_SUFFIX,\n} from \"./windows-task-host\";\n\n// Task Scheduler runs in the signed-in user's session, with that user's tokens\n// and ordinary permissions. No password, elevation, or third-party service host.\n// Native COM contracts: learn.microsoft.com/windows/win32/taskschd/\nconst TASK_CONTROL = String.raw`\n$ErrorActionPreference = 'Stop'\n$ProgressPreference = 'SilentlyContinue'\n[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)\n$r = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($env:OPENMELD_TASK_REQUEST)))\nif ($env:OPENMELD_TASK_GRANT_REQUIRED -eq '1' -and [Console]::In.ReadLine() -ne 'execute') { exit 125 }\n$env:OPENMELD_TASK_GRANT_REQUIRED = $null\n$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value\nif ($sid -in @('S-1-5-18','S-1-5-19','S-1-5-20')) { throw 'Run OpenMeld setup from your own Windows account, not a system account.' }\n$scheduler = New-Object -ComObject 'Schedule.Service'\n$scheduler.Connect()\n$folder = $scheduler.GetFolder('\\')\n$name = $r.name + '-' + $sid\n$hostPath = $r.legacyScript + '${WINDOWS_TASK_HOST_SUFFIX}'\n$runtimeRoot = [IO.Path]::GetDirectoryName($r.legacyScript)\nfunction Read-OwnedDirectAction($path, $arguments) {\n if ($arguments -notmatch '(?:^| )--openmeld-windows-task ([A-Za-z0-9+/=]+)$') { return $null }\n $c = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($Matches[1])))\n $bundles = [IO.Path]::GetFullPath((Join-Path $runtimeRoot 'bundles')) + '\\'\n $fullPath = [IO.Path]::GetFullPath($path)\n if ($c.executable -ne $path -or !$fullPath.StartsWith($bundles, [StringComparison]::OrdinalIgnoreCase) -or [IO.Path]::GetFileName($path) -ne 'openmeld.exe' -or !$c.env.OPENMELD_HOME -or [IO.Path]::GetFullPath((Join-Path $c.env.OPENMELD_HOME 'runtime\\daemon')) -ne [IO.Path]::GetFullPath($runtimeRoot)) {\n throw 'The Windows task does not belong to this OpenMeld installation.'\n }\n return $c\n}\n$existingDirect = $null\n$task = $null\ntry { $task = $folder.GetTask($name) } catch {\n if ($_.Exception.GetBaseException().HResult -ne -2147024894) { throw }\n}\nif ($task) {\n $principal = $task.Definition.Principal\n $taskSid = $principal.UserId\n if ($taskSid -notmatch '^S-\\d-') { $taskSid = ([Security.Principal.NTAccount]$taskSid).Translate([Security.Principal.SecurityIdentifier]).Value }\n $actionPath = $task.Definition.Actions.Item(1).Path\n $existingDirect = Read-OwnedDirectAction $actionPath $task.Definition.Actions.Item(1).Arguments\n if ($taskSid -ne $sid -or $principal.LogonType -ne 3 -or $principal.RunLevel -ne 0 -or $task.Definition.Actions.Count -ne 1 -or (!$existingDirect -and $actionPath -ne (Join-Path $PSHOME 'powershell.exe') -and $actionPath -ne $hostPath)) {\n throw 'An existing OpenMeld task uses a different user or launch configuration. Resolve that installation before continuing.'\n }\n}\n# Migration only owns the exact legacy script in this lane. Never stop another\n# user's or an administrator-customized service merely because its name matches.\n$legacy = Get-CimInstance Win32_Service -Filter (\"Name='\" + $r.name.Replace(\"'\",\"''\") + \"'\")\nif ($legacy -and $legacy.PathName.Trim('\"') -ne $r.legacyScript) {\n throw 'An existing Windows service uses a different installation. Resolve that installation before continuing.'\n}\nswitch ($r.operation) {\n 'install' {\n if ($legacy -and $legacy.State -ne 'Stopped') { throw 'The previous OpenMeld Service must finish stopping before migration.' }\n $nextDirect = Read-OwnedDirectAction $r.executable $r.arguments\n # A running maintenance invocation keeps its immutable copy and lease. Only\n # subsequent invocations select the new copy. Main Service replacement still\n # requires the existing drain and stopped-state proof.\n $maintenanceUpdate = $r.periodic -and $existingDirect -and $nextDirect -and $existingDirect.args.Count -eq 2 -and $nextDirect.args.Count -eq 2 -and $existingDirect.args[0] -eq 'service' -and $existingDirect.args[1] -eq 'update-worker' -and $nextDirect.args[0] -eq 'service' -and $nextDirect.args[1] -eq 'update-worker'\n if ($task -and $task.State -eq 4 -and !$maintenanceUpdate) { throw 'OpenMeld cannot replace a background task while it is running.' }\n if (!$nextDirect) {\n if ($r.executable -ne (Join-Path $PSHOME 'powershell.exe')) { throw 'OpenMeld tasks require a verified background executable.' }\n ${WINDOWS_TASK_HOST_INSTALL_SCRIPT}\n }\n $definition = $scheduler.NewTask(0)\n $definition.RegistrationInfo.Description = 'OpenMeld background process for the signed-in user.'\n $definition.Principal.UserId = $sid\n $definition.Principal.LogonType = 3\n $definition.Principal.RunLevel = 0\n $definition.Settings.Enabled = ($null -eq $legacy)\n $definition.Settings.Hidden = $true\n $definition.Settings.AllowDemandStart = $true\n $definition.Settings.DisallowStartIfOnBatteries = $false\n $definition.Settings.StopIfGoingOnBatteries = $false\n $definition.Settings.RunOnlyIfNetworkAvailable = $false\n $definition.Settings.StartWhenAvailable = $true\n $definition.Settings.ExecutionTimeLimit = 'PT0S'\n $definition.Settings.MultipleInstances = 2\n $definition.Settings.RestartInterval = 'PT1M'\n $definition.Settings.RestartCount = 999\n $trigger = $definition.Triggers.Create(9)\n $trigger.UserId = $sid\n if ($r.periodic) {\n $timer = $definition.Triggers.Create(1)\n $timer.StartBoundary = (Get-Date).AddMinutes(1).ToString('yyyy-MM-ddTHH:mm:ss')\n $timer.Repetition.Interval = 'PT1H'\n }\n $action = $definition.Actions.Create(0)\n $action.Path = $(if ($nextDirect) { $r.executable } else { $hostPath })\n $action.Arguments = $r.arguments\n $action.WorkingDirectory = $r.workingDirectory\n $task = $folder.RegisterTaskDefinition($name, $definition, 6, $sid, $null, 3, $null)\n if ($legacy) {\n try {\n $deleted = Invoke-CimMethod -InputObject $legacy -MethodName Delete\n if ($deleted.ReturnValue -ne 0) { throw ('Cannot remove the old Windows Service (code ' + $deleted.ReturnValue + '). An administrator must remove the old registration before setup can continue.') }\n } catch {\n $folder.DeleteTask($name,0)\n throw\n }\n $task.Enabled = $true\n }\n $legacy = $null\n }\n 'start' { if (!$task) { throw 'OpenMeld background task is not installed. Run setup to repair it.' }; $null = $task.Run($null) }\n 'enable' { if ($task) { $task.Enabled = $true } }\n 'disable' { if ($task) { $task.Enabled = $false }; if ($legacy) { $result = Invoke-CimMethod -InputObject $legacy -MethodName ChangeStartMode -Arguments @{StartMode='Manual'}; if ($result.ReturnValue -ne 0) { throw 'Cannot disable the old Windows Service. Administrator assistance is required.' } } }\n 'stop' {\n if ($task) { $task.Stop(0) }\n if ($legacy -and $legacy.State -ne 'Stopped') {\n $result = Invoke-CimMethod -InputObject $legacy -MethodName StopService\n if ($result.ReturnValue -notin @(0,6)) { throw 'Cannot stop the old Windows Service. Administrator assistance is required.' }\n }\n }\n 'uninstall' {\n if ($task) { $task.Stop(0); $folder.DeleteTask($name,0); $task = $null }\n if ($legacy) {\n if ($legacy.State -ne 'Stopped') { throw 'The old OpenMeld Service is still running.' }\n $result = Invoke-CimMethod -InputObject $legacy -MethodName Delete\n if ($result.ReturnValue -ne 0) { throw 'Cannot remove the old Windows Service. Administrator assistance is required.' }\n $legacy = $null\n }\n }\n 'status' { }\n default { throw 'Unknown OpenMeld task operation.' }\n}\n@{ installed=($null -ne $task -or $null -ne $legacy); running=($(if ($task) { $task.State -eq 4 } else { $legacy -and $legacy.State -ne 'Stopped' })); enabled=($(if ($task) { [bool]$task.Enabled } else { $legacy -and $legacy.StartMode -eq 'Auto' })); legacy=($null -ne $legacy); actionArguments=($(if ($task) { $task.Definition.Actions.Item(1).Arguments } else { $null })) } | ConvertTo-Json -Compress\n`;\n\nexport function windowsPowerShellPath(): string {\n return resolveWindowsPowerShellPath();\n}\n\nexport function windowsTaskActionArguments(\n input: WindowsUserTaskAction\n): string {\n // TypeScript's structural type does not strip fields from a spread spec.\n // Project and validate the actual wire value before encoding it.\n const action = windowsUserTaskActionSchema.parse({\n executable: input.executable,\n args: input.args,\n env: input.env,\n logPath: input.logPath,\n });\n const data = Buffer.from(JSON.stringify(action)).toString(\"base64\");\n const script = String.raw`\n$ErrorActionPreference = 'Stop'\n$c = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${data}')))\nfunction Quote-ProcessArgument([string]$value) {\n '\"' + [regex]::Replace([regex]::Replace($value, '(\\\\*)\"', '$1$1\\\"'), '(\\\\+)$', '$1$1') + '\"'\n}\n$start = New-Object Diagnostics.ProcessStartInfo\n$start.FileName = $c.executable\n$start.Arguments = (@($c.args | ForEach-Object { Quote-ProcessArgument $_ }) -join ' ')\n$start.UseShellExecute = $false\n$start.CreateNoWindow = $true\n$start.RedirectStandardOutput = $true\n$start.RedirectStandardError = $true\nforeach ($property in $c.env.PSObject.Properties) { $start.EnvironmentVariables[$property.Name] = [string]$property.Value }\n$log = [IO.Stream]::Synchronized([IO.File]::Open($c.logPath, [IO.FileMode]::Append, [IO.FileAccess]::Write, [IO.FileShare]::ReadWrite))\n$process = New-Object Diagnostics.Process\n$process.StartInfo = $start\ntry {\n $null = $process.Start()\n $stdout = $process.StandardOutput.BaseStream.CopyToAsync($log)\n $stderr = $process.StandardError.BaseStream.CopyToAsync($log)\n $process.WaitForExit()\n $stdout.GetAwaiter().GetResult()\n $stderr.GetAwaiter().GetResult()\n $exitCode = $process.ExitCode\n} finally {\n $log.Dispose()\n $process.Dispose()\n}\nexit $exitCode\n`;\n return `-NoLogo -NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ${Buffer.from(script, \"utf16le\").toString(\"base64\")}`;\n}\n\nconst ENCODED_ACTION_PATTERN = /-EncodedCommand ([A-Za-z0-9+/=]+)$/u;\nconst ACTION_DATA_PATTERN = /FromBase64String\\('([A-Za-z0-9+/=]+)'\\)/u;\n\nexport function readWindowsTaskAction(argumentsText: string) {\n const direct = readWindowsDirectTaskAction(argumentsText);\n if (direct) {\n return direct;\n }\n const encoded = argumentsText.match(ENCODED_ACTION_PATTERN)?.[1];\n const data =\n encoded &&\n Buffer.from(encoded, \"base64\")\n .toString(\"utf16le\")\n .match(ACTION_DATA_PATTERN)?.[1];\n if (!data) {\n throw new Error(\n \"Windows task does not contain an OpenMeld launch command.\"\n );\n }\n const action = windowsUserTaskStoredActionSchema.safeParse(\n JSON.parse(Buffer.from(data, \"base64\").toString(\"utf8\"))\n );\n if (!action.success) {\n throw new Error(\n \"Windows task contains an invalid OpenMeld launch command.\"\n );\n }\n return action.data;\n}\n\nexport async function runWindowsUserTask(\n request: WindowsUserTaskRequest\n): Promise<{\n installed: boolean;\n running: boolean;\n enabled: boolean;\n legacy: boolean;\n actionArguments: string | null;\n}> {\n const lock = currentDaemonServiceLifecycleLock();\n if (request.operation === \"install\" && request.arguments) {\n const direct = readWindowsDirectTaskAction(request.arguments);\n if (direct) {\n if (request.executable !== direct.executable) {\n throw new Error(\n \"The Windows task executable does not match its launch envelope.\"\n );\n }\n await verifyWindowsServiceSubsystem(direct.executable);\n }\n }\n const payload = Buffer.from(\n JSON.stringify(windowsUserTaskRequestSchema.parse(request))\n ).toString(\"base64\");\n let finish!: (value: {\n error: ExecFileException | null;\n stdout: string;\n }) => void;\n const completed = new Promise<{\n error: ExecFileException | null;\n stdout: string;\n }>((resolve) => {\n finish = resolve;\n });\n const child = execFile(\n windowsPowerShellPath(),\n powerShellEncodedArguments(TASK_CONTROL),\n {\n encoding: \"utf8\",\n windowsHide: true,\n timeout: 30_000,\n maxBuffer: 1024 * 1024,\n env: {\n ...normalizeCommandEnvironment(process.env),\n OPENMELD_TASK_REQUEST: payload,\n OPENMELD_TASK_GRANT_REQUIRED: lock ? \"1\" : \"0\",\n },\n },\n (error, stdout) => finish({ error, stdout })\n );\n // EOF before the grant prevents the COM operation. Once granted, this exact\n // PowerShell instance retains the existing lifecycle fence if its CLI dies.\n // This is not a Wake Job: the independently scheduled Service must survive it.\n child.stdin?.on(\"error\", () => undefined);\n let participant: OpenMeldLock | undefined;\n try {\n if (lock) {\n if (!child.pid) {\n throw new Error(\"Windows task control did not establish a process.\");\n }\n participant = await attachLockProcess(lock, child.pid);\n }\n child.stdin?.end(lock ? \"execute\\n\" : undefined);\n const result = await completed;\n if (result.error) {\n throw result.error;\n }\n const status = windowsUserTaskStatusSchema.safeParse(\n JSON.parse(result.stdout.trim())\n );\n if (!status.success) {\n throw new Error(\"Windows returned an invalid OpenMeld task status.\");\n }\n return status.data;\n } finally {\n child.stdin?.destroy();\n if (child.exitCode === null && child.signalCode === null) {\n child.kill();\n }\n await completed;\n if (participant) {\n await releaseLock(participant);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,MAAM,sBAAsB;AAE5B,SAAgB,6BACd,QACA,YAAyC,CAAC,GAClC;CACR,IACE,EACE,OAAO,yBACP,oBAAoB,KAAK,OAAO,qBAAqB,IAGvD,MAAM,IAAI,MACR,+DACF;CAEF,OAAO,KACL,yBAAyB,SAAS,GAClC,eAAe,OAAO,yBACtB,cACF;AACF;AAEA,eAAsB,gCACpB,QACA,YAAyC,CAAC,GACzB;CACjB,MAAM,SAAS,6BAA6B,QAAQ,SAAS;CAC7D,MAAM,WAAW,OAAO;CACxB,IACG,MAAM,wBAAwB,QAAQ,IAAI,CAAC,CAAC,YAAY,IAAI,MAAO,UAEpE,OAAO;CAET,IACG,MAAM,wBAAwB,OAAO,uBAAuB,IAAI,MACjE,UAEA,MAAM,IAAI,MACR,uEAC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CACF;CACA,MAAM,UAAU,OAAO,KACrB,KAAK,UAAU,6BAA6B,MAAM,OAAO,CAAC,CAC5D,CAAC,CAAC,SAAS,QAAQ;CACnB,IAAI;CAIJ,MAAM,YAAY,IAAI,SAGlB,YAAY;EACd,SAAS;CACX,CAAC;CACD,MAAM,QAAQ,SACZ,sBAAsB,GACtB,2BAA2B,YAAY,GACvC;EACE,UAAU;EACV,aAAa;EACb,SAAS;EACT,WAAW;EACX,KAAK;GACH,GAAG,4BAA4B,QAAQ,GAAG;GAC1C,uBAAuB;GACvB,8BAA8B,OAAO,MAAM;EAC7C;CACF,IACC,OAAO,WAAW,OAAO;EAAE;EAAO;CAAO,CAAC,CAC7C;CAIA,MAAM,OAAO,GAAG,eAAe,KAAA,CAAS;CACxC,IAAI;CACJ,IAAI;EACF,IAAI,MAAM;GACR,IAAI,CAAC,MAAM,KACT,MAAM,IAAI,MAAM,mDAAmD;GAErE,cAAc,MAAM,kBAAkB,MAAM,MAAM,GAAG;EACvD;EACA,MAAM,OAAO,IAAI,OAAO,cAAc,KAAA,CAAS;EAC/C,MAAM,SAAS,MAAM;EACrB,IAAI,OAAO,OACT,MAAM,OAAO;EAEf,MAAM,SAAS,4BAA4B,UACzC,KAAK,MAAM,OAAO,OAAO,KAAK,CAAC,CACjC;EACA,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,MAAM,mDAAmD;EAErE,OAAO,OAAO;CAChB,UAAU;EACR,MAAM,OAAO,QAAQ;EACrB,IAAI,MAAM,aAAa,QAAQ,MAAM,eAAe,MAClD,MAAM,KAAK;EAEb,MAAM;EACN,IAAI,aACF,MAAM,YAAY,WAAW;CAEjC;AACF"}
1
+ {"version":3,"file":"windows-user-task-CR64LZEK.js","names":[],"sources":["../src/local-service/lifecycle/windows-service-binary.ts","../src/local-service/lifecycle/windows-task-host.ts","../src/local-service/lifecycle/windows-user-task.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport {\n copyFile,\n mkdir,\n mkdtemp,\n open,\n rename,\n rm,\n stat,\n} from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { pruneWindowsBinaryBundle } from \"@openmeld/adapter-core/windows-system\";\nimport { WINDOWS_PROCESS_HELPER_FILENAME } from \"@openmeld/schemas\";\nimport { daemonRuntimeBundlesPath } from \"../../config/daemon-state\";\nimport type { OpenMeldPathResolutionInput } from \"../../config/paths\";\nimport type { CliBinaryReleaseInfo } from \"../../config/version-state\";\nimport type { DaemonActiveBundleState } from \"./daemon-service-bundle\";\n\nconst FINGERPRINT_PATTERN = /^[0-9a-f]{64}$/u;\n\nexport function windowsMaintenanceBinaryPath(\n bundle: DaemonActiveBundleState,\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n if (\n !(\n bundle.sourceDistFingerprint &&\n FINGERPRINT_PATTERN.test(bundle.sourceDistFingerprint)\n )\n ) {\n throw new Error(\n \"OpenMeld maintenance needs a verified Windows Service bundle.\"\n );\n }\n return join(\n daemonRuntimeBundlesPath(pathInput),\n `maintenance-${bundle.sourceDistFingerprint}`,\n \"openmeld.exe\"\n );\n}\n\nexport async function prepareWindowsMaintenanceBinary(\n bundle: DaemonActiveBundleState,\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<string> {\n const target = windowsMaintenanceBinaryPath(bundle, pathInput);\n const expected = bundle.sourceDistFingerprint;\n if (\n (await hashBinaryServiceBundle(target, true).catch(() => null)) === expected\n ) {\n return target;\n }\n if (\n (await hashBinaryServiceBundle(bundle.sourceEntryScriptPath, true)) !==\n expected\n ) {\n throw new Error(\n \"The Windows maintenance source no longer matches its verified bundle.\"\n );\n }\n const directory = dirname(target);\n if (\n await stat(directory).catch((error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n })\n ) {\n const result = await pruneWindowsBinaryBundle(directory);\n if (result !== \"removed\" && result !== \"absent\") {\n throw new Error(\n \"The existing Windows maintenance copy is still in use or contains unrecognized files.\"\n );\n }\n }\n await mkdir(daemonRuntimeBundlesPath(pathInput), { recursive: true });\n const temporary = await mkdtemp(\n join(daemonRuntimeBundlesPath(pathInput), \".maintenance-\")\n );\n try {\n for (const name of [\"openmeld.exe\", WINDOWS_PROCESS_HELPER_FILENAME]) {\n await copyFile(\n name === \"openmeld.exe\"\n ? bundle.sourceEntryScriptPath\n : join(dirname(bundle.sourceEntryScriptPath), name),\n join(temporary, name)\n );\n }\n if (\n (await hashBinaryServiceBundle(join(temporary, \"openmeld.exe\"), true)) !==\n expected\n ) {\n throw new Error(\n \"The prepared Windows maintenance copy failed verification.\"\n );\n }\n await rename(temporary, directory);\n } finally {\n await rm(temporary, { recursive: true, force: true });\n }\n return target;\n}\n\n// Windows binary_v1 bundles contain two indivisible, independently signed files.\n// Keep one bundle fingerprint for inventory, update jobs, and maintenance copies.\nexport function expectedBinaryServiceFingerprint(\n release: CliBinaryReleaseInfo\n): string {\n if (!release.platform.startsWith(\"windows-\")) {\n return release.sha256.toLowerCase();\n }\n if (!release.windows) {\n throw new Error(\n \"The selected Windows Service has no native helper metadata.\"\n );\n }\n return fingerprint(release.sha256, release.windows.processHelper.sha256);\n}\n\nexport async function hashBinaryServiceBundle(\n executablePath: string,\n windows: boolean = process.platform === \"win32\"\n): Promise<string> {\n const executableHash = await hashFile(executablePath);\n return windows\n ? fingerprint(\n executableHash,\n await hashFile(\n join(dirname(executablePath), WINDOWS_PROCESS_HELPER_FILENAME)\n )\n )\n : executableHash;\n}\n\nfunction fingerprint(executableHash: string, helperHash: string): string {\n return createHash(\"sha256\")\n .update(\n JSON.stringify([executableHash.toLowerCase(), helperHash.toLowerCase()])\n )\n .digest(\"hex\");\n}\n\nasync function hashFile(file: string): Promise<string> {\n const hash = createHash(\"sha256\");\n for await (const chunk of createReadStream(file)) {\n hash.update(chunk);\n }\n return hash.digest(\"hex\");\n}\n\n/** A valid signature does not establish the required console-free PE subsystem. */\nexport async function verifyWindowsServiceSubsystem(\n file: string\n): Promise<void> {\n const handle = await open(file, \"r\");\n try {\n const dos = Buffer.alloc(64);\n const first = await handle.read(dos, 0, dos.length, 0);\n if (\n first.bytesRead !== dos.length ||\n dos.toString(\"ascii\", 0, 2) !== \"MZ\"\n ) {\n throw new Error(\"The Windows Service artifact is not a PE executable.\");\n }\n const header = Buffer.alloc(94);\n const second = await handle.read(\n header,\n 0,\n header.length,\n dos.readUInt32LE(0x3c)\n );\n if (\n second.bytesRead !== header.length ||\n header.toString(\"ascii\", 0, 4) !== \"PE\\0\\0\" ||\n header.readUInt16LE(4) !== 0x86_64 ||\n header.readUInt16LE(24 + 68) !== 2\n ) {\n throw new Error(\n \"The selected Windows Service must be a console-free x64 executable.\"\n );\n }\n } finally {\n await handle.close();\n }\n}\n","// Task Scheduler must start a Windows-subsystem executable, not a console\n// executable that hides its window after startup. Keep the existing encoded\n// PowerShell action as the command/environment/logging owner.\n// Windows PowerShell 5.1 compiles this fixed source during guarded installation;\n// no SDK, downloaded executable, WSH/VBScript, or administrator access is needed.\nexport const WINDOWS_TASK_HOST_SOURCE = String.raw`\nusing System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\npublic static class OpenMeldTaskHostV1 {\n public static int Main(string[] args) {\n string logPath = Assembly.GetExecutingAssembly().Location + \".log\";\n try {\n // Accept only the existing OpenMeld action, never an arbitrary executable\n // or a shell-interpolated command line. Base64 contains no quoting syntax.\n if (args.Length != 7 || args[0] != \"-NoLogo\" || args[1] != \"-NoProfile\" ||\n args[2] != \"-NonInteractive\" || args[3] != \"-WindowStyle\" ||\n args[4] != \"Hidden\" || args[5] != \"-EncodedCommand\" ||\n !Regex.IsMatch(args[6], @\"\\A[A-Za-z0-9+/]+={0,2}\\z\"))\n throw new ArgumentException(\"Invalid OpenMeld task arguments.\");\n Convert.FromBase64String(args[6]);\n var start = new ProcessStartInfo();\n start.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System),\n @\"WindowsPowerShell\\v1.0\\powershell.exe\");\n start.Arguments = String.Join(\" \", args);\n start.UseShellExecute = false;\n start.CreateNoWindow = true;\n start.RedirectStandardInput = true;\n start.RedirectStandardOutput = true;\n start.RedirectStandardError = true;\n using (var log = Stream.Synchronized(new FileStream(logPath, FileMode.Append,\n FileAccess.Write, FileShare.ReadWrite)))\n using (var child = new Process()) {\n child.StartInfo = start;\n child.Start();\n child.StandardInput.Close();\n var stdout = child.StandardOutput.BaseStream.CopyToAsync(log);\n var stderr = child.StandardError.BaseStream.CopyToAsync(log);\n // Do not detach or break away from Task Scheduler's process ownership.\n // The task remains running until the action completes, and restart-on-\n // failure still receives the action's real exit code.\n child.WaitForExit();\n stdout.GetAwaiter().GetResult();\n stderr.GetAwaiter().GetResult();\n return child.ExitCode;\n }\n } catch (Exception error) {\n try { File.AppendAllText(logPath, DateTime.UtcNow.ToString(\"o\") + \" \" +\n error.GetType().Name + \": \" + error.Message + Environment.NewLine, Encoding.UTF8); }\n catch { /* Task Scheduler still receives a nonzero result if logging fails. */ }\n return 1;\n }\n }\n}\n`;\n\n// Per-task, lane-owned path: updating the maintenance host cannot replace the\n// executable of a running main Service, or vice versa. Keep v1 stable; a future\n// host format must explicitly support migration from this path.\nexport const WINDOWS_TASK_HOST_SUFFIX = \".task-host-v1.exe\";\n\n// The caller has already verified identity and acquired the lifecycle grant.\n// Build beside the target and replace atomically, never overwrite a running\n// host or fall back to a flashing console when compilation is unavailable.\nexport const WINDOWS_TASK_HOST_INSTALL_SCRIPT = `\n$hostDirectory = [IO.Path]::GetDirectoryName($hostPath)\n$null = [IO.Directory]::CreateDirectory($hostDirectory)\n$temporaryHost = Join-Path $hostDirectory ([Guid]::NewGuid().ToString('N') + '.exe')\ntry {\n Add-Type -TypeDefinition @'\n${WINDOWS_TASK_HOST_SOURCE}\n'@ -OutputAssembly $temporaryHost -OutputType WindowsApplication -ErrorAction Stop\n if ($task -and $task.State -eq 4) { throw 'OpenMeld cannot replace a background task while it is running.' }\n if ([IO.File]::Exists($hostPath)) {\n # PowerShell coerces bare $null to an empty string for this .NET parameter.\n # Pass a real null backup path; an empty path breaks repeat setup/repair.\n [IO.File]::Replace($temporaryHost, $hostPath, [NullString]::Value)\n } else {\n [IO.File]::Move($temporaryHost, $hostPath)\n }\n} finally {\n if ([IO.File]::Exists($temporaryHost)) { [IO.File]::Delete($temporaryHost) }\n}\n`;\n","import { type ExecFileException, execFile } from \"node:child_process\";\nimport { normalizeCommandEnvironment } from \"@openmeld/adapter-core/process-environment\";\nimport {\n powerShellEncodedArguments,\n resolveWindowsPowerShellPath,\n} from \"@openmeld/adapter-core/windows-system\";\nimport {\n type WindowsUserTaskAction,\n type WindowsUserTaskRequest,\n windowsUserTaskActionSchema,\n windowsUserTaskRequestSchema,\n windowsUserTaskStatusSchema,\n windowsUserTaskStoredActionSchema,\n} from \"@openmeld/schemas\";\nimport { currentDaemonServiceLifecycleLock } from \"../../config/daemon-state\";\nimport {\n attachLockProcess,\n type OpenMeldLock,\n releaseLock,\n} from \"../../config/lock\";\nimport { verifyWindowsServiceSubsystem } from \"./windows-service-binary\";\nimport { readWindowsDirectTaskAction } from \"./windows-task-command\";\nimport {\n WINDOWS_TASK_HOST_INSTALL_SCRIPT,\n WINDOWS_TASK_HOST_SUFFIX,\n} from \"./windows-task-host\";\n\n// Task Scheduler runs in the signed-in user's session, with that user's tokens\n// and ordinary permissions. No password, elevation, or third-party service host.\n// Native COM contracts: learn.microsoft.com/windows/win32/taskschd/\nconst TASK_CONTROL = String.raw`\n$ErrorActionPreference = 'Stop'\n$ProgressPreference = 'SilentlyContinue'\n[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)\n$r = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($env:OPENMELD_TASK_REQUEST)))\nif ($env:OPENMELD_TASK_GRANT_REQUIRED -eq '1' -and [Console]::In.ReadLine() -ne 'execute') { exit 125 }\n$env:OPENMELD_TASK_GRANT_REQUIRED = $null\n$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value\nif ($sid -in @('S-1-5-18','S-1-5-19','S-1-5-20')) { throw 'Run OpenMeld setup from your own Windows account, not a system account.' }\n$scheduler = New-Object -ComObject 'Schedule.Service'\n$scheduler.Connect()\n$folder = $scheduler.GetFolder('\\')\n$name = $r.name + '-' + $sid\n$hostPath = $r.legacyScript + '${WINDOWS_TASK_HOST_SUFFIX}'\n$runtimeRoot = [IO.Path]::GetDirectoryName($r.legacyScript)\nfunction Read-OwnedDirectAction($path, $arguments) {\n if ($arguments -notmatch '(?:^| )--openmeld-windows-task ([A-Za-z0-9+/=]+)$') { return $null }\n $c = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($Matches[1])))\n $bundles = [IO.Path]::GetFullPath((Join-Path $runtimeRoot 'bundles')) + '\\'\n $fullPath = [IO.Path]::GetFullPath($path)\n if ($c.executable -ne $path -or !$fullPath.StartsWith($bundles, [StringComparison]::OrdinalIgnoreCase) -or [IO.Path]::GetFileName($path) -ne 'openmeld.exe' -or !$c.env.OPENMELD_HOME -or [IO.Path]::GetFullPath((Join-Path $c.env.OPENMELD_HOME 'runtime\\daemon')) -ne [IO.Path]::GetFullPath($runtimeRoot)) {\n throw 'The Windows task does not belong to this OpenMeld installation.'\n }\n return $c\n}\n$existingDirect = $null\n$task = $null\ntry { $task = $folder.GetTask($name) } catch {\n if ($_.Exception.GetBaseException().HResult -ne -2147024894) { throw }\n}\nif ($task) {\n $principal = $task.Definition.Principal\n $taskSid = $principal.UserId\n if ($taskSid -notmatch '^S-\\d-') { $taskSid = ([Security.Principal.NTAccount]$taskSid).Translate([Security.Principal.SecurityIdentifier]).Value }\n $actionPath = $task.Definition.Actions.Item(1).Path\n $existingDirect = Read-OwnedDirectAction $actionPath $task.Definition.Actions.Item(1).Arguments\n if ($taskSid -ne $sid -or $principal.LogonType -ne 3 -or $principal.RunLevel -ne 0 -or $task.Definition.Actions.Count -ne 1 -or (!$existingDirect -and $actionPath -ne (Join-Path $PSHOME 'powershell.exe') -and $actionPath -ne $hostPath)) {\n throw 'An existing OpenMeld task uses a different user or launch configuration. Resolve that installation before continuing.'\n }\n}\n# Migration only owns the exact legacy script in this lane. Never stop another\n# user's or an administrator-customized service merely because its name matches.\n$legacy = Get-CimInstance Win32_Service -Filter (\"Name='\" + $r.name.Replace(\"'\",\"''\") + \"'\")\nif ($legacy -and $legacy.PathName.Trim('\"') -ne $r.legacyScript) {\n throw 'An existing Windows service uses a different installation. Resolve that installation before continuing.'\n}\nswitch ($r.operation) {\n 'install' {\n if ($legacy -and $legacy.State -ne 'Stopped') { throw 'The previous OpenMeld Service must finish stopping before migration.' }\n $nextDirect = Read-OwnedDirectAction $r.executable $r.arguments\n # A running maintenance invocation keeps its immutable copy and lease. Only\n # subsequent invocations select the new copy. Main Service replacement still\n # requires the existing drain and stopped-state proof.\n $maintenanceUpdate = $r.periodic -and $existingDirect -and $nextDirect -and $existingDirect.args.Count -eq 2 -and $nextDirect.args.Count -eq 2 -and $existingDirect.args[0] -eq 'service' -and $existingDirect.args[1] -eq 'update-worker' -and $nextDirect.args[0] -eq 'service' -and $nextDirect.args[1] -eq 'update-worker'\n if ($task -and $task.State -eq 4 -and !$maintenanceUpdate) { throw 'OpenMeld cannot replace a background task while it is running.' }\n if (!$nextDirect) {\n if ($r.executable -ne (Join-Path $PSHOME 'powershell.exe')) { throw 'OpenMeld tasks require a verified background executable.' }\n ${WINDOWS_TASK_HOST_INSTALL_SCRIPT}\n }\n $definition = $scheduler.NewTask(0)\n $definition.RegistrationInfo.Description = 'OpenMeld background process for the signed-in user.'\n $definition.Principal.UserId = $sid\n $definition.Principal.LogonType = 3\n $definition.Principal.RunLevel = 0\n $definition.Settings.Enabled = ($null -eq $legacy)\n $definition.Settings.Hidden = $true\n $definition.Settings.AllowDemandStart = $true\n $definition.Settings.DisallowStartIfOnBatteries = $false\n $definition.Settings.StopIfGoingOnBatteries = $false\n $definition.Settings.RunOnlyIfNetworkAvailable = $false\n $definition.Settings.StartWhenAvailable = $true\n $definition.Settings.ExecutionTimeLimit = 'PT0S'\n $definition.Settings.MultipleInstances = 2\n $definition.Settings.RestartInterval = 'PT1M'\n $definition.Settings.RestartCount = 999\n $trigger = $definition.Triggers.Create(9)\n $trigger.UserId = $sid\n if ($r.periodic) {\n $timer = $definition.Triggers.Create(1)\n $timer.StartBoundary = (Get-Date).AddMinutes(1).ToString('yyyy-MM-ddTHH:mm:ss')\n $timer.Repetition.Interval = 'PT1H'\n }\n $action = $definition.Actions.Create(0)\n $action.Path = $(if ($nextDirect) { $r.executable } else { $hostPath })\n $action.Arguments = $r.arguments\n $action.WorkingDirectory = $r.workingDirectory\n $task = $folder.RegisterTaskDefinition($name, $definition, 6, $sid, $null, 3, $null)\n if ($legacy) {\n try {\n $deleted = Invoke-CimMethod -InputObject $legacy -MethodName Delete\n if ($deleted.ReturnValue -ne 0) { throw ('Cannot remove the old Windows Service (code ' + $deleted.ReturnValue + '). An administrator must remove the old registration before setup can continue.') }\n } catch {\n $folder.DeleteTask($name,0)\n throw\n }\n $task.Enabled = $true\n }\n $legacy = $null\n }\n 'start' { if (!$task) { throw 'OpenMeld background task is not installed. Run setup to repair it.' }; $null = $task.Run($null) }\n 'enable' { if ($task) { $task.Enabled = $true } }\n 'disable' { if ($task) { $task.Enabled = $false }; if ($legacy) { $result = Invoke-CimMethod -InputObject $legacy -MethodName ChangeStartMode -Arguments @{StartMode='Manual'}; if ($result.ReturnValue -ne 0) { throw 'Cannot disable the old Windows Service. Administrator assistance is required.' } } }\n 'stop' {\n if ($task) { $task.Stop(0) }\n if ($legacy -and $legacy.State -ne 'Stopped') {\n $result = Invoke-CimMethod -InputObject $legacy -MethodName StopService\n if ($result.ReturnValue -notin @(0,6)) { throw 'Cannot stop the old Windows Service. Administrator assistance is required.' }\n }\n }\n 'uninstall' {\n if ($task) { $task.Stop(0); $folder.DeleteTask($name,0); $task = $null }\n if ($legacy) {\n if ($legacy.State -ne 'Stopped') { throw 'The old OpenMeld Service is still running.' }\n $result = Invoke-CimMethod -InputObject $legacy -MethodName Delete\n if ($result.ReturnValue -ne 0) { throw 'Cannot remove the old Windows Service. Administrator assistance is required.' }\n $legacy = $null\n }\n }\n 'status' { }\n default { throw 'Unknown OpenMeld task operation.' }\n}\n@{ installed=($null -ne $task -or $null -ne $legacy); running=($(if ($task) { $task.State -eq 4 } else { $legacy -and $legacy.State -ne 'Stopped' })); enabled=($(if ($task) { [bool]$task.Enabled } else { $legacy -and $legacy.StartMode -eq 'Auto' })); legacy=($null -ne $legacy); actionArguments=($(if ($task) { $task.Definition.Actions.Item(1).Arguments } else { $null })) } | ConvertTo-Json -Compress\n`;\n\nexport function windowsPowerShellPath(): string {\n return resolveWindowsPowerShellPath();\n}\n\nexport function windowsTaskActionArguments(\n input: WindowsUserTaskAction\n): string {\n // TypeScript's structural type does not strip fields from a spread spec.\n // Project and validate the actual wire value before encoding it.\n const action = windowsUserTaskActionSchema.parse({\n executable: input.executable,\n args: input.args,\n env: input.env,\n logPath: input.logPath,\n });\n const data = Buffer.from(JSON.stringify(action)).toString(\"base64\");\n const script = String.raw`\n$ErrorActionPreference = 'Stop'\n$c = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${data}')))\nfunction Quote-ProcessArgument([string]$value) {\n '\"' + [regex]::Replace([regex]::Replace($value, '(\\\\*)\"', '$1$1\\\"'), '(\\\\+)$', '$1$1') + '\"'\n}\n$start = New-Object Diagnostics.ProcessStartInfo\n$start.FileName = $c.executable\n$start.Arguments = (@($c.args | ForEach-Object { Quote-ProcessArgument $_ }) -join ' ')\n$start.UseShellExecute = $false\n$start.CreateNoWindow = $true\n$start.RedirectStandardOutput = $true\n$start.RedirectStandardError = $true\nforeach ($property in $c.env.PSObject.Properties) { $start.EnvironmentVariables[$property.Name] = [string]$property.Value }\n$log = [IO.Stream]::Synchronized([IO.File]::Open($c.logPath, [IO.FileMode]::Append, [IO.FileAccess]::Write, [IO.FileShare]::ReadWrite))\n$process = New-Object Diagnostics.Process\n$process.StartInfo = $start\ntry {\n $null = $process.Start()\n $stdout = $process.StandardOutput.BaseStream.CopyToAsync($log)\n $stderr = $process.StandardError.BaseStream.CopyToAsync($log)\n $process.WaitForExit()\n $stdout.GetAwaiter().GetResult()\n $stderr.GetAwaiter().GetResult()\n $exitCode = $process.ExitCode\n} finally {\n $log.Dispose()\n $process.Dispose()\n}\nexit $exitCode\n`;\n return `-NoLogo -NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ${Buffer.from(script, \"utf16le\").toString(\"base64\")}`;\n}\n\nconst ENCODED_ACTION_PATTERN = /-EncodedCommand ([A-Za-z0-9+/=]+)$/u;\nconst ACTION_DATA_PATTERN = /FromBase64String\\('([A-Za-z0-9+/=]+)'\\)/u;\n\nexport function readWindowsTaskAction(argumentsText: string) {\n const direct = readWindowsDirectTaskAction(argumentsText);\n if (direct) {\n return direct;\n }\n const encoded = argumentsText.match(ENCODED_ACTION_PATTERN)?.[1];\n const data =\n encoded &&\n Buffer.from(encoded, \"base64\")\n .toString(\"utf16le\")\n .match(ACTION_DATA_PATTERN)?.[1];\n if (!data) {\n throw new Error(\n \"Windows task does not contain an OpenMeld launch command.\"\n );\n }\n const action = windowsUserTaskStoredActionSchema.safeParse(\n JSON.parse(Buffer.from(data, \"base64\").toString(\"utf8\"))\n );\n if (!action.success) {\n throw new Error(\n \"Windows task contains an invalid OpenMeld launch command.\"\n );\n }\n return action.data;\n}\n\nexport async function runWindowsUserTask(\n request: WindowsUserTaskRequest\n): Promise<{\n installed: boolean;\n running: boolean;\n enabled: boolean;\n legacy: boolean;\n actionArguments: string | null;\n}> {\n const lock = currentDaemonServiceLifecycleLock();\n if (request.operation === \"install\" && request.arguments) {\n const direct = readWindowsDirectTaskAction(request.arguments);\n if (direct) {\n if (request.executable !== direct.executable) {\n throw new Error(\n \"The Windows task executable does not match its launch envelope.\"\n );\n }\n await verifyWindowsServiceSubsystem(direct.executable);\n }\n }\n const payload = Buffer.from(\n JSON.stringify(windowsUserTaskRequestSchema.parse(request))\n ).toString(\"base64\");\n let finish!: (value: {\n error: ExecFileException | null;\n stdout: string;\n }) => void;\n const completed = new Promise<{\n error: ExecFileException | null;\n stdout: string;\n }>((resolve) => {\n finish = resolve;\n });\n const child = execFile(\n windowsPowerShellPath(),\n powerShellEncodedArguments(TASK_CONTROL),\n {\n encoding: \"utf8\",\n windowsHide: true,\n timeout: 30_000,\n maxBuffer: 1024 * 1024,\n env: {\n ...normalizeCommandEnvironment(process.env),\n OPENMELD_TASK_REQUEST: payload,\n OPENMELD_TASK_GRANT_REQUIRED: lock ? \"1\" : \"0\",\n },\n },\n (error, stdout) => finish({ error, stdout })\n );\n // EOF before the grant prevents the COM operation. Once granted, this exact\n // PowerShell instance retains the existing lifecycle fence if its CLI dies.\n // This is not a Wake Job: the independently scheduled Service must survive it.\n child.stdin?.on(\"error\", () => undefined);\n let participant: OpenMeldLock | undefined;\n try {\n if (lock) {\n if (!child.pid) {\n throw new Error(\"Windows task control did not establish a process.\");\n }\n participant = await attachLockProcess(lock, child.pid);\n }\n child.stdin?.end(lock ? \"execute\\n\" : undefined);\n const result = await completed;\n if (result.error) {\n throw result.error;\n }\n const status = windowsUserTaskStatusSchema.safeParse(\n JSON.parse(result.stdout.trim())\n );\n if (!status.success) {\n throw new Error(\"Windows returned an invalid OpenMeld task status.\");\n }\n return status.data;\n } finally {\n child.stdin?.destroy();\n if (child.exitCode === null && child.signalCode === null) {\n child.kill();\n }\n await completed;\n if (participant) {\n await releaseLock(participant);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,MAAM,sBAAsB;AAE5B,SAAgB,6BACd,QACA,YAAyC,CAAC,GAClC;CACR,IACE,EACE,OAAO,yBACP,oBAAoB,KAAK,OAAO,qBAAqB,IAGvD,MAAM,IAAI,MACR,+DACF;CAEF,OAAO,KACL,yBAAyB,SAAS,GAClC,eAAe,OAAO,yBACtB,cACF;AACF;AAEA,eAAsB,gCACpB,QACA,YAAyC,CA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AAM,YAAY,WAAW;CAEjC;AACF"}
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- export { t as readWindowsTaskAction, n as runWindowsUserTask } from "./windows-user-task-CKb_u29X.js";
3
+ export { t as readWindowsTaskAction, n as runWindowsUserTask } from "./windows-user-task-CR64LZEK.js";
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://www.schemastore.org/package.json",
3
3
  "name": "openmeld",
4
- "version": "0.3.287",
5
- "openMeldReleaseDate": "2026-11-01",
4
+ "version": "0.3.290",
5
+ "openMeldReleaseDate": "2026-11-02",
6
6
  "description": "OpenMeld CLI - https://openmeld.ai",
7
7
  "license": "MIT",
8
8
  "type": "module",
@@ -49,27 +49,27 @@
49
49
  "unplugin-lightningcss": "^0.4.0",
50
50
  "vitest": "4.1.11",
51
51
  "@openmeld/adapter-antigravity": "0.0.1",
52
- "@openmeld/adapter-claude-code": "0.0.1",
53
52
  "@openmeld/adapter-codex": "0.0.1",
54
- "@openmeld/adapter-cursor": "0.0.1",
53
+ "@openmeld/adapter-claude-code": "0.0.1",
54
+ "@openmeld/adapter-core": "0.0.1",
55
55
  "@openmeld/adapter-grok-bot": "0.0.1",
56
+ "@openmeld/adapter-cursor": "0.0.1",
56
57
  "@openmeld/adapter-grok-build": "0.0.1",
57
58
  "@openmeld/adapter-openclaw": "0.0.1",
58
- "@openmeld/adapter-core": "0.0.1",
59
59
  "@openmeld/adapter-opencode": "0.0.1",
60
- "@openmeld/api-client": "0.0.1",
61
60
  "@openmeld/agent-runtime": "0.0.1",
61
+ "@openmeld/api-client": "0.0.1",
62
62
  "@openmeld/local-execution": "0.0.1",
63
- "@openmeld/gateway-contract": "0.0.1",
64
- "@openmeld/local-service": "0.0.1",
65
63
  "@openmeld/projects": "0.0.1",
66
- "@openmeld/protocol": "0.0.1",
64
+ "@openmeld/local-service": "0.0.1",
67
65
  "@openmeld/routine-schedule": "0.0.1",
68
66
  "@openmeld/schemas": "0.0.1",
69
67
  "@openmeld/space": "0.0.1",
68
+ "@openmeld/protocol": "0.0.1",
70
69
  "@openmeld/space-mesh": "0.0.1",
71
70
  "@openmeld/start": "0.0.1",
72
- "@openmeld/utils": "0.0.1"
71
+ "@openmeld/utils": "0.0.1",
72
+ "@openmeld/gateway-contract": "0.0.1"
73
73
  },
74
74
  "openmeld": {
75
75
  "releaseLine": "openmeld-greenfield-2026-07",
@@ -87,5 +87,5 @@
87
87
  "test:local-service": "vitest run --config vitest.integration.config.ts tests/local-service-state.integration.test.ts tests/local-service-command.integration.test.ts tests/local-service-menu.integration.test.ts tests/local-service-run.integration.test.ts tests/local-service-bootstrap-recommendation.test.ts",
88
88
  "test:watch": "vitest"
89
89
  },
90
- "gitHead": "c6a3c29b41797c50fb37aea0551e9348ffbc0d59"
90
+ "gitHead": "58f900b4818092b8add89cd5ae22bef886a85b6f"
91
91
  }
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- export { u as getAuthSessionMetadata } from "./auth-session-DRQMn41Z.js";
@@ -1 +0,0 @@
1
- {"version":3,"file":"channel-CFIRo4fR.js","names":[],"sources":["../../../packages/schemas/dist/local-execution-input.js","../../../packages/schemas/dist/service-execution-host.js","../src/local-service/execution-host/channel.ts"],"sourcesContent":["import { agentExecutionSteerResponseSchema } from \"./schemas/runtime/agent-execution-steer.js\";\nimport * as z$1 from \"zod/v4\";\n//#region src/local-execution-input.ts\nconst id = z$1.string().min(1).max(1024);\nconst LOCAL_EXECUTION_INPUT_CAPABILITY_HEADER = \"x-openmeld-local-execution-input\";\nconst LOCAL_EXECUTION_INPUT_PENDING_DIAGNOSTIC = \"service.execution_input.pending\";\nconst localExecutionInputRequestSchema = z$1.strictObject({\n\tinputId: id,\n\townerUserId: id,\n\tdispatchId: id,\n\truntimeCoordinatorExecutionId: id,\n\tattemptId: id,\n\truntimeCoordinatorRunId: id,\n\ttargetProfileId: id,\n\tsource: z$1.strictObject({\n\t\tspaceId: id,\n\t\tsignalId: id,\n\t\tauthorProfileId: id,\n\t\trequesterUserId: id,\n\t\teffect: z$1.literal(\"steer\")\n\t}),\n\ttext: z$1.string().trim().min(1).max(1e5)\n});\nconst localExecutionInputResponseSchema = z$1.discriminatedUnion(\"status\", [\n\tagentExecutionSteerResponseSchema.options[0].extend({ inputId: id }),\n\tagentExecutionSteerResponseSchema.options[1].extend({\n\t\tinputId: id,\n\t\ttaskId: id.nullable()\n\t}),\n\tagentExecutionSteerResponseSchema.options[2].extend({ inputId: id }),\n\tz$1.strictObject({\n\t\tinputId: id,\n\t\tstatus: z$1.enum([\n\t\t\t\"not_found\",\n\t\t\t\"conflict\",\n\t\t\t\"capacity\"\n\t\t])\n\t})\n]);\nconst localExecutionInputOperationSchema = z$1.strictObject({\n\toperation: z$1.enum([\"apply\", \"read\"]),\n\trequest: localExecutionInputRequestSchema\n});\nconst localExecutionInputFrameSchema = localExecutionInputOperationSchema.extend({\n\trequestId: id,\n\tconnectionGeneration: z$1.number().int().positive(),\n\tleaseEpoch: z$1.number().int().positive()\n});\nconst localExecutionInputResultFrameSchema = z$1.strictObject({\n\trequestId: id,\n\tresult: localExecutionInputResponseSchema\n});\nconst localExecutionInputResolveSchema = z$1.strictObject({\n\townerUserId: id,\n\truntimeCoordinatorExecutionId: id,\n\tdispatchId: id,\n\ttargetProfileId: id,\n\tspaceId: id,\n\tauthorProfileId: id\n});\nconst localExecutionInputBindingSchema = localExecutionInputRequestSchema.pick({\n\townerUserId: true,\n\truntimeCoordinatorExecutionId: true,\n\tdispatchId: true,\n\ttargetProfileId: true,\n\tattemptId: true,\n\truntimeCoordinatorRunId: true\n});\n//#endregion\nexport { LOCAL_EXECUTION_INPUT_CAPABILITY_HEADER, LOCAL_EXECUTION_INPUT_PENDING_DIAGNOSTIC, localExecutionInputBindingSchema, localExecutionInputFrameSchema, localExecutionInputOperationSchema, localExecutionInputRequestSchema, localExecutionInputResolveSchema, localExecutionInputResponseSchema, localExecutionInputResultFrameSchema };\n\n//# sourceMappingURL=local-execution-input.js.map","import { daemonServiceLaneSchema } from \"./schemas/daemon/service-contract.js\";\nimport { providerDispatchRuntimeContextSchema } from \"./schemas/daemon/provider-runtime-context.js\";\nimport { openMeldDaemonCancelPayloadSchema, openMeldDaemonCancelRequestPayloadSchema, openMeldDaemonConversationExecutionStatusPayloadSchema, openMeldDaemonConversationExecutionStatusRequestPayloadSchema, openMeldDaemonInterruptPayloadSchema, openMeldDaemonInterruptRequestPayloadSchema, openMeldDaemonSetLocalAgentEnabledPayloadSchema, openMeldDaemonSetLocalAgentEnabledRequestPayloadSchema, skippedDaemonProfileSchema } from \"./schemas/daemon/control-plane.js\";\nimport { daemonStreamFrameSchema, localWakeRouteWorkingFolderObservationSchema, runtimeTransportLeaseSchema } from \"./schemas/daemon/runtime-transport.js\";\nimport { localExecutionInputRequestSchema, localExecutionInputResponseSchema } from \"./local-execution-input.js\";\nimport { cachedDaemonRouteConfigSchema } from \"./schemas/daemon/route-catalog-cache.js\";\nimport * as z$1 from \"zod/v4\";\n//#region src/service-execution-host.ts\nconst SERVICE_EXECUTION_HOST_PROTOCOL = \"service-execution-host-v1\";\nconst SERVICE_EXECUTION_HOST_MAX_FRAME_BYTES = 8388608;\nconst SERVICE_EXECUTION_HOST_MAX_PENDING_REQUESTS = 64;\nconst identityString = z$1.string().min(1).max(1024);\nconst count = z$1.number().int().nonnegative();\nconst empty = z$1.strictObject({});\nconst serviceExecutionHostIdentitySchema = z$1.strictObject({\n\townerUserId: identityString,\n\tdeviceId: identityString,\n\tlane: daemonServiceLaneSchema,\n\tdaemonSessionId: identityString,\n\tserviceContractGeneration: count,\n\tsessionIdentity: identityString,\n\tstateRoot: z$1.string().min(1).max(4096),\n\tauthBaseUrl: z$1.url(),\n\tgatewayBaseUrl: z$1.url(),\n\tparentPid: z$1.number().int().positive(),\n\tparentProcessStartedAt: identityString\n});\nconst serviceExecutionHostSnapshotSchema = z$1.strictObject({\n\tpid: z$1.number().int().positive(),\n\tadmission: z$1.enum([\"open\", \"draining\"]),\n\tactiveCount: count,\n\tpendingCount: count,\n\tlocalQuiescent: z$1.boolean(),\n\tunacknowledgedResultCount: count,\n\tstartupReplayPending: z$1.boolean(),\n\tadapterIds: z$1.array(identityString).max(256)\n});\nconst serviceExecutionHostOwnerV1Schema = z$1.strictObject({\n\tschema: z$1.literal(\"service-execution-host-owner-v1\"),\n\thostInstanceId: z$1.uuid(),\n\townerUserId: identityString,\n\tdeviceId: identityString,\n\tlane: daemonServiceLaneSchema,\n\tpid: z$1.number().int().positive(),\n\tbootIdentity: identityString.nullable(),\n\tlocalQuiescent: z$1.boolean()\n});\nconst serviceExecutionHostOwnedProcessTreeSchema = z$1.strictObject({\n\tpid: z$1.number().int().positive(),\n\tprocessStartedAt: identityString,\n\tsignalTarget: z$1.enum([\"process\", \"process_group\"])\n});\nconst serviceExecutionHostOwnerV2Schema = z$1.strictObject({\n\tschema: z$1.literal(\"service-execution-host-owner-v2\"),\n\thostInstanceId: z$1.uuid(),\n\townerUserId: identityString,\n\tdeviceId: identityString,\n\tlane: daemonServiceLaneSchema,\n\tpid: z$1.number().int().positive(),\n\tprocessStartedAt: identityString,\n\tbootIdentity: identityString.nullable(),\n\tlocalQuiescent: z$1.boolean(),\n\tprocessEvidenceComplete: z$1.boolean(),\n\townedProcessTrees: z$1.array(serviceExecutionHostOwnedProcessTreeSchema).max(64)\n});\nconst serviceExecutionHostOwnerSchema = z$1.discriminatedUnion(\"schema\", [serviceExecutionHostOwnerV1Schema, serviceExecutionHostOwnerV2Schema]);\nconst profileWorkingFolderFactSchema = z$1.strictObject({\n\tdefaultProjectId: identityString.nullable(),\n\tlocalProjectBindingGeneration: identityString.nullable(),\n\tobservedAtMs: count,\n\treasonCode: z$1.enum([\n\t\t\"profile.workspace.invalid\",\n\t\t\"profile.workspace.missing\",\n\t\t\"project.local_connection.folder_missing\",\n\t\t\"project.local_connection.invalid\",\n\t\t\"project.local_connection.missing\"\n\t]).nullable(),\n\tsource: z$1.enum([\"default_project\", \"profile_workspace\"]),\n\tstatus: z$1.enum([\n\t\t\"invalid\",\n\t\t\"missing\",\n\t\t\"ready\"\n\t])\n});\nconst readyWorkingFolder = {\n\tconfiguredWorkspacePath: z$1.string().min(1),\n\teffectiveRuntimeWorkingDirectory: z$1.string().min(1),\n\truntimeContext: providerDispatchRuntimeContextSchema,\n\tstatus: z$1.literal(\"ready\"),\n\tworkingFolderFact: profileWorkingFolderFactSchema\n};\nconst workingFolderRuntimeSchema = z$1.union([\n\tz$1.strictObject({\n\t\t...readyWorkingFolder,\n\t\tconfigPath: z$1.string().min(1),\n\t\tworkspaceMode: z$1.enum([\"openmeld_managed\", \"custom\"]),\n\t\tworkingFolderSource: z$1.literal(\"profile_workspace\")\n\t}),\n\tz$1.strictObject({\n\t\tconfigPath: z$1.string().min(1),\n\t\tconfiguredWorkspacePath: z$1.null().optional(),\n\t\treasonCode: z$1.literal(\"workspace.missing\"),\n\t\treasonText: z$1.string().min(1),\n\t\tstatus: z$1.literal(\"missing\"),\n\t\tworkingFolderFact: profileWorkingFolderFactSchema,\n\t\tworkingFolderSource: z$1.literal(\"profile_workspace\"),\n\t\tworkspaceMode: z$1.null().optional()\n\t}),\n\tz$1.strictObject({\n\t\tconfigPath: z$1.string().min(1),\n\t\tconfiguredWorkspacePath: z$1.string().min(1).nullable().optional(),\n\t\treasonCode: z$1.literal(\"workspace.invalid\"),\n\t\treasonText: z$1.string().min(1),\n\t\tstatus: z$1.literal(\"invalid\"),\n\t\tworkingFolderFact: profileWorkingFolderFactSchema,\n\t\tworkingFolderSource: z$1.literal(\"profile_workspace\"),\n\t\tworkspaceMode: z$1.enum([\"openmeld_managed\", \"custom\"]).nullable().optional()\n\t}),\n\tz$1.strictObject({\n\t\t...readyWorkingFolder,\n\t\tconfigPath: z$1.null(),\n\t\tworkspaceMode: z$1.null(),\n\t\tdefaultProjectId: identityString,\n\t\tdefaultProjectBindingGeneration: identityString,\n\t\tworkingFolderSource: z$1.literal(\"default_project\")\n\t}),\n\tz$1.strictObject({\n\t\tconfigPath: z$1.null(),\n\t\tconfiguredWorkspacePath: z$1.string().min(1).nullable(),\n\t\tdefaultProjectBindingGeneration: identityString.optional(),\n\t\tdefaultProjectFailureReason: z$1.enum([\"folder_missing\", \"missing_connection\"]),\n\t\tdefaultProjectId: identityString,\n\t\treasonCode: z$1.literal(\"workspace.missing\"),\n\t\treasonText: z$1.string().min(1),\n\t\tstatus: z$1.literal(\"missing\"),\n\t\tworkingFolderFact: profileWorkingFolderFactSchema,\n\t\tworkingFolderSource: z$1.literal(\"default_project\"),\n\t\tworkspaceMode: z$1.null()\n\t}),\n\tz$1.strictObject({\n\t\tconfigPath: z$1.null(),\n\t\tconfiguredWorkspacePath: z$1.string().min(1),\n\t\tdefaultProjectBindingGeneration: identityString,\n\t\tdefaultProjectId: identityString,\n\t\treasonCode: z$1.literal(\"workspace.invalid\"),\n\t\treasonText: z$1.string().min(1),\n\t\tstatus: z$1.literal(\"invalid\"),\n\t\tworkingFolderFact: profileWorkingFolderFactSchema,\n\t\tworkingFolderSource: z$1.literal(\"default_project\"),\n\t\tworkspaceMode: z$1.null()\n\t})\n]);\nconst serviceExecutionHostRouteSchema = cachedDaemonRouteConfigSchema.extend({\n\tagentControllerConversationId: identityString.nullable().optional(),\n\tworkingFolderRuntime: workingFolderRuntimeSchema.optional()\n});\nconst serviceExecutionHostCatalogSchema = z$1.strictObject({\n\trevision: z$1.number().int().positive(),\n\texpectedRoutesContractVersion: z$1.literal(\"v4\").optional(),\n\tprofileIds: z$1.array(identityString).max(1e4),\n\troutes: z$1.array(serviceExecutionHostRouteSchema).max(1e4),\n\tskippedProfiles: z$1.array(skippedDaemonProfileSchema).max(1e4),\n\tworkingFolderExpectedProfileIds: z$1.array(identityString).max(1e4).optional(),\n\tworkingFolderObservations: z$1.array(localWakeRouteWorkingFolderObservationSchema).max(1e4).optional()\n}).superRefine((catalog, context) => {\n\tconst ids = new Set(catalog.profileIds);\n\tconst routes = new Set(catalog.routes.map((route) => route.profileId));\n\tif (ids.size !== catalog.profileIds.length || routes.size !== catalog.routes.length || ids.size !== routes.size || catalog.profileIds.some((id) => !routes.has(id))) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"Host catalog must contain exactly one route per profile.\"\n\t});\n});\nconst reportResult = z$1.strictObject({\n\tstatus: z$1.enum([\"skipped\", \"submitted\"]),\n\treasonCodes: z$1.array(z$1.string().max(256)).max(1024),\n\tsubmittedCount: count,\n\tfailedCount: count\n});\nconst executionFrameCodes = /* @__PURE__ */ new Set([\n\t\"daemon.computer_power.request\",\n\t\"daemon.dispatch.deliver\",\n\t\"daemon.dispatch.lifecycle_acknowledged\",\n\t\"daemon.dispatch.accepted\",\n\t\"daemon.dispatch.interaction_response\",\n\t\"daemon.reasoning.preferences\",\n\t\"daemon.local_agent_control.cancel\",\n\t\"daemon.local_agent_control.interrupt\",\n\t\"daemon.local_agent_control.fork_session\",\n\t\"daemon.local_agent_control.manage_installation\",\n\t\"daemon.local_agent_control.set_enabled\",\n\t\"daemon.execution_recovery.resume_controller_conversation\"\n]);\nconst executionOutputFrameCodes = /* @__PURE__ */ new Set([\n\t\"daemon.computer_power.request_result\",\n\t\"daemon.dispatch.result\",\n\t\"daemon.dispatch.lifecycle\",\n\t\"daemon.dispatch.runtime_evidence\",\n\t\"daemon.dispatch.reasoning\",\n\t\"daemon.dispatch.progress\",\n\t\"daemon.dispatch.reply\",\n\t\"daemon.dispatch.tool_activity\",\n\t\"daemon.dispatch.interaction_request\",\n\t\"daemon.dispatch.interaction_delivered\",\n\t\"daemon.dispatch.preview\",\n\t\"daemon.dispatch.preview_end\",\n\t\"daemon.local_agent_control.result\",\n\t\"daemon.execution_recovery.resume_controller_conversation_result\"\n]);\nconst serviceExecutionHostMethods = {\n\tinitialize: {\n\t\tinput: serviceExecutionHostIdentitySchema,\n\t\toutput: serviceExecutionHostSnapshotSchema\n\t},\n\thealth: {\n\t\tinput: empty,\n\t\toutput: serviceExecutionHostSnapshotSchema\n\t},\n\tloadCatalog: {\n\t\tinput: z$1.strictObject({ initial: z$1.boolean() }),\n\t\toutput: serviceExecutionHostCatalogSchema\n\t},\n\tconfigureConnection: {\n\t\tinput: z$1.strictObject({\n\t\t\texecutionAdmissionConfirmation: z$1.boolean().optional(),\n\t\t\tconnectionGeneration: z$1.number().int().positive(),\n\t\t\tcatalogRevision: count,\n\t\t\tleases: z$1.array(runtimeTransportLeaseSchema).max(1e4)\n\t\t}),\n\t\toutput: serviceExecutionHostSnapshotSchema\n\t},\n\tdetachConnection: {\n\t\tinput: z$1.strictObject({ connectionGeneration: z$1.number().int().positive() }),\n\t\toutput: serviceExecutionHostSnapshotSchema\n\t},\n\theartbeat: {\n\t\tinput: z$1.strictObject({\n\t\t\tconnectionGeneration: z$1.number().int().positive(),\n\t\t\tstaleProfileIds: z$1.array(identityString).max(1e4)\n\t\t}),\n\t\toutput: serviceExecutionHostSnapshotSchema\n\t},\n\thandleFrame: {\n\t\tinput: z$1.strictObject({\n\t\t\tconnectionGeneration: z$1.number().int().positive(),\n\t\t\tframe: daemonStreamFrameSchema.refine((frame) => executionFrameCodes.has(frame.code), \"This frame belongs to the connector, not the execution host.\")\n\t\t}),\n\t\toutput: empty\n\t},\n\tcancel: {\n\t\tinput: openMeldDaemonCancelRequestPayloadSchema,\n\t\toutput: openMeldDaemonCancelPayloadSchema\n\t},\n\tinterrupt: {\n\t\tinput: openMeldDaemonInterruptRequestPayloadSchema,\n\t\toutput: openMeldDaemonInterruptPayloadSchema\n\t},\n\texecutionInput: {\n\t\tinput: z$1.strictObject({\n\t\t\toperation: z$1.enum([\"apply\", \"read\"]),\n\t\t\tconnectionGeneration: z$1.number().int().positive(),\n\t\t\tleaseEpoch: z$1.number().int().positive(),\n\t\t\trequest: localExecutionInputRequestSchema\n\t\t}),\n\t\toutput: localExecutionInputResponseSchema\n\t},\n\tconversationStatus: {\n\t\tinput: openMeldDaemonConversationExecutionStatusRequestPayloadSchema,\n\t\toutput: openMeldDaemonConversationExecutionStatusPayloadSchema\n\t},\n\tsetEnabled: {\n\t\tinput: openMeldDaemonSetLocalAgentEnabledRequestPayloadSchema,\n\t\toutput: openMeldDaemonSetLocalAgentEnabledPayloadSchema\n\t},\n\treportControllers: {\n\t\tinput: z$1.strictObject({ probePolicy: z$1.enum([\"background\", \"fresh\"]) }),\n\t\toutput: reportResult.extend({\n\t\t\treportCount: count,\n\t\t\thasArmedReprobe: z$1.boolean()\n\t\t})\n\t},\n\treportConversations: {\n\t\tinput: empty,\n\t\toutput: reportResult.extend({ proofCount: count })\n\t},\n\tpersistCatalog: {\n\t\tinput: z$1.strictObject({ revision: z$1.number().int().positive() }),\n\t\toutput: empty\n\t},\n\tsyncActivity: {\n\t\tinput: z$1.strictObject({ refreshIntegrations: z$1.boolean().optional() }),\n\t\toutput: empty\n\t},\n\tbeginDrain: {\n\t\tinput: z$1.strictObject({ onlyIfIdle: z$1.literal(true).optional() }),\n\t\toutput: serviceExecutionHostSnapshotSchema\n\t},\n\tdrain: {\n\t\tinput: empty,\n\t\toutput: serviceExecutionHostSnapshotSchema\n\t},\n\tsettleResults: {\n\t\tinput: empty,\n\t\toutput: z$1.strictObject({ status: z$1.enum([\n\t\t\t\"acknowledged\",\n\t\t\t\"connection_closed\",\n\t\t\t\"timeout\"\n\t\t]) })\n\t},\n\tstop: {\n\t\tinput: empty,\n\t\toutput: serviceExecutionHostSnapshotSchema\n\t}\n};\nconst method = z$1.enum(Object.keys(serviceExecutionHostMethods));\nconst envelope = {\n\tprotocol: z$1.literal(SERVICE_EXECUTION_HOST_PROTOCOL),\n\thostInstanceId: z$1.uuid()\n};\nconst serviceExecutionHostRequestSchema = z$1.strictObject({\n\t...envelope,\n\trequestId: z$1.uuid(),\n\tmethod,\n\tpayload: z$1.unknown()\n});\nconst serviceExecutionHostMessageSchema = z$1.discriminatedUnion(\"type\", [\n\tz$1.strictObject({\n\t\t...envelope,\n\t\ttype: z$1.literal(\"reply\"),\n\t\trequestId: z$1.uuid(),\n\t\tmethod,\n\t\tresult: z$1.discriminatedUnion(\"ok\", [z$1.strictObject({\n\t\t\tok: z$1.literal(true),\n\t\t\tpayload: z$1.unknown()\n\t\t}), z$1.strictObject({\n\t\t\tok: z$1.literal(false),\n\t\t\terror: z$1.strictObject({\n\t\t\t\tcode: z$1.string().min(1).max(256),\n\t\t\t\tmessage: z$1.string().min(1).max(4096)\n\t\t\t})\n\t\t})])\n\t}),\n\tz$1.strictObject({\n\t\t...envelope,\n\t\ttype: z$1.literal(\"frame\"),\n\t\tconnectionGeneration: z$1.number().int().positive(),\n\t\tframe: daemonStreamFrameSchema.refine((frame) => executionOutputFrameCodes.has(frame.code), \"The execution host cannot emit connector-owned frames.\")\n\t}),\n\tz$1.strictObject({\n\t\t...envelope,\n\t\ttype: z$1.literal(\"invalidate\"),\n\t\tscope: z$1.enum([\n\t\t\t\"routes\",\n\t\t\t\"activity\",\n\t\t\t\"execution\"\n\t\t])\n\t}),\n\tz$1.strictObject({\n\t\t...envelope,\n\t\ttype: z$1.literal(\"authentication_failure\"),\n\t\tconnectionGeneration: z$1.number().int().positive().nullable(),\n\t\tfailure: z$1.strictObject({\n\t\t\tcredentialFingerprint: z$1.string().min(1).max(256).optional(),\n\t\t\tmessage: z$1.string().min(1).max(4096),\n\t\t\treasonCode: z$1.string().min(1).max(256)\n\t\t})\n\t})\n]);\n//#endregion\nexport { SERVICE_EXECUTION_HOST_MAX_FRAME_BYTES, SERVICE_EXECUTION_HOST_MAX_PENDING_REQUESTS, SERVICE_EXECUTION_HOST_PROTOCOL, profileWorkingFolderFactSchema, serviceExecutionHostCatalogSchema, serviceExecutionHostIdentitySchema, serviceExecutionHostMessageSchema, serviceExecutionHostMethods, serviceExecutionHostOwnerSchema, serviceExecutionHostRequestSchema, serviceExecutionHostRouteSchema, serviceExecutionHostSnapshotSchema };\n\n//# sourceMappingURL=service-execution-host.js.map","import { randomUUID } from \"node:crypto\";\nimport {\n SERVICE_EXECUTION_HOST_MAX_FRAME_BYTES,\n SERVICE_EXECUTION_HOST_MAX_PENDING_REQUESTS,\n SERVICE_EXECUTION_HOST_PROTOCOL,\n type ServiceExecutionHostArguments,\n type ServiceExecutionHostInput,\n type ServiceExecutionHostMessage,\n type ServiceExecutionHostMethod,\n type ServiceExecutionHostOutput,\n serviceExecutionHostMessageSchema,\n serviceExecutionHostMethods,\n serviceExecutionHostRequestSchema,\n} from \"@openmeld/schemas\";\n\nexport type ExecutionHostChannel = {\n connected(): boolean;\n send(message: object, completed: (error: Error | null) => void): void;\n onMessage(listener: (message: unknown) => void): () => void;\n onDisconnect(listener: (error?: Error) => void): () => void;\n};\n\nexport class ExecutionHostError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = \"ExecutionHostError\";\n this.code = code;\n }\n}\n\nconst RESERVED_CONTROL_REQUESTS = 4;\nconst controlMethods = new Set<ServiceExecutionHostMethod>([\n \"health\",\n \"beginDrain\",\n \"detachConnection\",\n \"stop\",\n]);\n\nfunction assertFrameSize(message: unknown): number {\n const serialized = JSON.stringify(message);\n if (serialized === undefined) {\n throw new ExecutionHostError(\n \"host.invalid_frame\",\n \"Host IPC requires JSON.\"\n );\n }\n const size = Buffer.byteLength(serialized);\n if (size > SERVICE_EXECUTION_HOST_MAX_FRAME_BYTES) {\n throw new ExecutionHostError(\n \"host.frame_too_large\",\n \"The local execution message exceeds the IPC limit.\"\n );\n }\n return size;\n}\n\nfunction createSender(channel: ExecutionHostChannel) {\n let queuedBytes = 0;\n return (message: object, completed: (error: Error | null) => void): void => {\n const size = assertFrameSize(message);\n if (!channel.connected()) {\n throw new ExecutionHostError(\n \"host.disconnected\",\n \"The Host IPC channel is closed.\"\n );\n }\n if (queuedBytes + size > SERVICE_EXECUTION_HOST_MAX_FRAME_BYTES * 2) {\n throw new ExecutionHostError(\n \"host.backpressure\",\n \"Host IPC is full; no new message was queued.\"\n );\n }\n queuedBytes += size;\n let settled = false;\n const settle = (error: Error | null) => {\n if (settled) {\n return;\n }\n settled = true;\n queuedBytes -= size;\n completed(error);\n };\n try {\n channel.send(message, settle);\n } catch (error) {\n settle(error instanceof Error ? error : new Error(String(error)));\n }\n };\n}\n\ntype PendingRequest = {\n method: ServiceExecutionHostMethod;\n resolve(value: unknown): void;\n reject(error: Error): void;\n timer: ReturnType<typeof setTimeout> | null;\n};\n\nfunction resolveReply(\n request: PendingRequest,\n message: Extract<ServiceExecutionHostMessage, { type: \"reply\" }>\n): void {\n if (!message.result.ok) {\n request.reject(\n new ExecutionHostError(\n message.result.error.code,\n message.result.error.message\n )\n );\n return;\n }\n const result = serviceExecutionHostMethods[request.method].output.safeParse(\n message.result.payload\n );\n if (!result.success) {\n const error = new ExecutionHostError(\n \"host.invalid_response\",\n `Invalid ${request.method} response from the execution host.`\n );\n request.reject(error);\n throw error;\n }\n request.resolve(result.data);\n}\n\nexport function createExecutionHostClient(input: {\n channel: ExecutionHostChannel;\n hostInstanceId: string;\n onEvent?(\n event: Exclude<ServiceExecutionHostMessage, { type: \"reply\" }>\n ): void;\n onFailure?(error: Error): void;\n}) {\n const pending = new Map<string, PendingRequest>();\n const send = createSender(input.channel);\n let failure: Error | null = null;\n\n const fail = (error: Error) => {\n if (failure) {\n return;\n }\n failure = error;\n for (const request of pending.values()) {\n if (request.timer) {\n clearTimeout(request.timer);\n }\n request.reject(error);\n }\n pending.clear();\n input.onFailure?.(error);\n };\n\n const stopMessages = input.channel.onMessage((raw) => {\n if (failure) {\n return;\n }\n try {\n assertFrameSize(raw);\n const parsed = serviceExecutionHostMessageSchema.safeParse(raw);\n if (\n !parsed.success ||\n parsed.data.hostInstanceId !== input.hostInstanceId\n ) {\n throw new ExecutionHostError(\n \"host.invalid_response\",\n \"Host response does not match this process incarnation.\"\n );\n }\n const message = parsed.data;\n if (message.type !== \"reply\") {\n input.onEvent?.(message);\n return;\n }\n const request = pending.get(message.requestId);\n // A timed-out observer is gone, not the accepted operation. Do not retry it\n // or turn its late result into the outcome of a newer request.\n if (!request) {\n return;\n }\n if (request.method !== message.method) {\n throw new ExecutionHostError(\n \"host.invalid_response\",\n \"Host response method does not match its request.\"\n );\n }\n pending.delete(message.requestId);\n if (request.timer) {\n clearTimeout(request.timer);\n }\n resolveReply(request, message);\n } catch (error) {\n fail(error instanceof Error ? error : new Error(String(error)));\n }\n });\n const stopDisconnect = input.channel.onDisconnect((cause) => {\n fail(\n new ExecutionHostError(\n \"host.disconnected\",\n cause\n ? `The execution host disconnected: ${cause.message}. In-flight outcomes are unconfirmed.`\n : \"The execution host disconnected; in-flight outcomes are unconfirmed.\"\n )\n );\n });\n\n return {\n call<M extends ServiceExecutionHostMethod>(\n method: M,\n value: ServiceExecutionHostInput<M>,\n options: { timeoutMs?: number | null } = {}\n ): Promise<ServiceExecutionHostOutput<M>> {\n if (failure) {\n return Promise.reject(failure);\n }\n const limit =\n SERVICE_EXECUTION_HOST_MAX_PENDING_REQUESTS -\n (controlMethods.has(method) ? 0 : RESERVED_CONTROL_REQUESTS);\n if (pending.size >= limit) {\n return Promise.reject(\n new ExecutionHostError(\n \"host.busy\",\n \"Too many outstanding Host requests; no new request was sent.\"\n )\n );\n }\n const payload =\n serviceExecutionHostMethods[method].input.safeParse(value);\n if (!payload.success) {\n return Promise.reject(\n new ExecutionHostError(\n \"host.invalid_request\",\n `Invalid ${method} request.`\n )\n );\n }\n const requestId = randomUUID();\n const timeoutMs =\n options.timeoutMs === undefined ? 30_000 : options.timeoutMs;\n if (\n timeoutMs !== null &&\n (!Number.isFinite(timeoutMs) || timeoutMs <= 0)\n ) {\n return Promise.reject(\n new ExecutionHostError(\n \"host.invalid_timeout\",\n \"The observer deadline must be positive or absent.\"\n )\n );\n }\n return new Promise<ServiceExecutionHostOutput<M>>((resolve, reject) => {\n const request: PendingRequest = {\n method,\n resolve: (result) => resolve(result as ServiceExecutionHostOutput<M>),\n reject,\n timer: null,\n };\n if (timeoutMs !== null) {\n request.timer = setTimeout(() => {\n pending.delete(requestId);\n reject(\n new ExecutionHostError(\n \"host.observation_timeout\",\n `The ${method} response is unconfirmed. No operation was cancelled or retried.`\n )\n );\n }, timeoutMs);\n request.timer.unref?.();\n }\n pending.set(requestId, request);\n try {\n send(\n {\n protocol: SERVICE_EXECUTION_HOST_PROTOCOL,\n hostInstanceId: input.hostInstanceId,\n requestId,\n method,\n payload: payload.data,\n },\n (error) => {\n if (error) {\n fail(error);\n }\n }\n );\n } catch (error) {\n pending.delete(requestId);\n if (request.timer) {\n clearTimeout(request.timer);\n }\n reject(error);\n }\n });\n },\n pendingCount: () => pending.size,\n dispose(): void {\n stopMessages();\n stopDisconnect();\n fail(\n new ExecutionHostError(\n \"host.observer_closed\",\n \"The Host observer closed; accepted work was not cancelled.\"\n )\n );\n },\n };\n}\n\nexport type ExecutionHostHandlers = {\n [M in ServiceExecutionHostMethod]: (\n input: ServiceExecutionHostArguments<M>\n ) => Promise<ServiceExecutionHostOutput<M>> | ServiceExecutionHostOutput<M>;\n};\n\nexport function serveExecutionHost(input: {\n channel: ExecutionHostChannel;\n hostInstanceId: string;\n handlers: ExecutionHostHandlers;\n onFailure(error: Error): void;\n onDisconnect(): void;\n}) {\n const activeIds = new Set<string>();\n const send = createSender(input.channel);\n let closed = false;\n\n const sendMessage = (message: ServiceExecutionHostMessage) => {\n if (closed) {\n throw new ExecutionHostError(\n \"host.disconnected\",\n \"The connector is no longer observing this Host.\"\n );\n }\n send(message, (error) => {\n if (error) {\n input.onFailure(error);\n }\n });\n };\n\n const stopMessages = input.channel.onMessage((raw) => {\n if (closed) {\n return;\n }\n let request: ReturnType<typeof serviceExecutionHostRequestSchema.parse>;\n try {\n assertFrameSize(raw);\n const parsed = serviceExecutionHostRequestSchema.safeParse(raw);\n if (\n !parsed.success ||\n parsed.data.hostInstanceId !== input.hostInstanceId\n ) {\n throw new ExecutionHostError(\n \"host.invalid_request\",\n \"Host request does not match this process incarnation.\"\n );\n }\n request = parsed.data;\n } catch (error) {\n input.onFailure(\n error instanceof Error ? error : new Error(String(error))\n );\n return;\n }\n\n const respond = (\n result: Extract<ServiceExecutionHostMessage, { type: \"reply\" }>[\"result\"]\n ) => {\n if (!closed) {\n sendMessage({\n protocol: SERVICE_EXECUTION_HOST_PROTOCOL,\n hostInstanceId: input.hostInstanceId,\n type: \"reply\",\n requestId: request.requestId,\n method: request.method,\n result,\n });\n }\n };\n const reject = (error: unknown) => {\n try {\n respond({\n ok: false,\n error: {\n code:\n error instanceof ExecutionHostError\n ? error.code\n : \"host.operation_failed\",\n message:\n (error instanceof Error ? error.message : String(error)).slice(\n 0,\n 4096\n ) || \"Host operation failed.\",\n },\n });\n } catch (sendError) {\n input.onFailure(\n sendError instanceof Error ? sendError : new Error(String(sendError))\n );\n }\n };\n\n const limit =\n SERVICE_EXECUTION_HOST_MAX_PENDING_REQUESTS -\n (controlMethods.has(request.method) ? 0 : RESERVED_CONTROL_REQUESTS);\n if (activeIds.has(request.requestId) || activeIds.size >= limit) {\n reject(\n new ExecutionHostError(\n \"host.busy\",\n \"Host request is duplicate or capacity is exhausted; it was not admitted again.\"\n )\n );\n return;\n }\n const method = serviceExecutionHostMethods[request.method];\n const payload = method.input.safeParse(request.payload);\n if (!payload.success) {\n reject(\n new ExecutionHostError(\n \"host.invalid_request\",\n `Invalid ${request.method} payload.`\n )\n );\n return;\n }\n activeIds.add(request.requestId);\n // This cast connects the fixed schema table to its corresponding handler.\n // Both request and response are runtime-validated, including local callers.\n const handler = input.handlers[request.method] as (\n value: unknown\n ) => unknown;\n Promise.resolve()\n .then(() => handler(payload.data))\n .then((result) => {\n const parsed = method.output.safeParse(result);\n if (!parsed.success) {\n throw new ExecutionHostError(\n \"host.invalid_response\",\n `The ${request.method} owner returned an invalid response.`\n );\n }\n respond({ ok: true, payload: parsed.data });\n })\n .catch(reject)\n .finally(() => activeIds.delete(request.requestId));\n });\n const stopDisconnect = input.channel.onDisconnect(() => {\n if (closed) {\n return;\n }\n closed = true;\n input.onDisconnect();\n });\n return {\n emit(event: Exclude<ServiceExecutionHostMessage, { type: \"reply\" }>): void {\n const parsed = serviceExecutionHostMessageSchema.safeParse(event);\n if (!parsed.success || event.hostInstanceId !== input.hostInstanceId) {\n throw new ExecutionHostError(\n \"host.invalid_event\",\n \"Invalid execution-host event.\"\n );\n }\n sendMessage(parsed.data);\n },\n dispose(): void {\n closed = true;\n stopMessages();\n stopDisconnect();\n },\n };\n}\n"],"mappings":";;;;;;;;;AAGA,MAAM,KAAK,IAAI,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI;AACvC,MAAM,0CAA0C;AAChD,MAAM,2CAA2C;AACjD,MAAM,mCAAmC,IAAI,aAAa;CACzD,SAAS;CACT,aAAa;CACb,YAAY;CACZ,+BAA+B;CAC/B,WAAW;CACX,yBAAyB;CACzB,iBAAiB;CACjB,QAAQ,IAAI,aAAa;EACxB,SAAS;EACT,UAAU;EACV,iBAAiB;EACjB,iBAAiB;EACjB,QAAQ,IAAI,QAAQ,OAAO;CAC5B,CAAC;CACD,MAAM,IAAI,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;AACzC,CAAC;AACD,MAAM,oCAAoC,IAAI,mBAAmB,UAAU;CAC1E,kCAAkC,QAAQ,EAAE,CAAC,OAAO,EAAE,SAAS,GAAG,CAAC;CACnE,kCAAkC,QAAQ,EAAE,CAAC,OAAO;EACnD,SAAS;EACT,QAAQ,GAAG,SAAS;CACrB,CAAC;CACD,kCAAkC,QAAQ,EAAE,CAAC,OAAO,EAAE,SAAS,GAAG,CAAC;CACnE,IAAI,aAAa;EAChB,SAAS;EACT,QAAQ,IAAI,KAAK;GAChB;GACA;GACA;EACD,CAAC;CACF,CAAC;AACF,CAAC;AACD,MAAM,qCAAqC,IAAI,aAAa;CAC3D,WAAW,IAAI,KAAK,CAAC,SAAS,MAAM,CAAC;CACrC,SAAS;AACV,CAAC;AACD,MAAM,iCAAiC,mCAAmC,OAAO;CAChF,WAAW;CACX,sBAAsB,IAAI,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS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Q,IAAI,CAAC,CAAC,CACjC,MAAM,WAAW;GAChB,MAAM,SAAS,OAAO,OAAO,UAAU,MAAM;GAC7C,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,mBACR,yBACA,OAAO,QAAQ,OAAO,qCACxB;GAEF,QAAQ;IAAE,IAAI;IAAM,SAAS,OAAO;GAAK,CAAC;EAC5C,CAAC,CAAC,CACD,MAAM,MAAM,CAAC,CACb,cAAc,UAAU,OAAO,QAAQ,SAAS,CAAC;CACtD,CAAC;CACD,MAAM,iBAAiB,MAAM,QAAQ,mBAAmB;EACtD,IAAI,QACF;EAEF,SAAS;EACT,MAAM,aAAa;CACrB,CAAC;CACD,OAAO;EACL,KAAK,OAAsE;GACzE,MAAM,SAAS,kCAAkC,UAAU,KAAK;GAChE,IAAI,CAAC,OAAO,WAAW,MAAM,mBAAmB,MAAM,gBACpD,MAAM,IAAI,mBACR,sBACA,+BACF;GAEF,YAAY,OAAO,IAAI;EACzB;EACA,UAAgB;GACd,SAAS;GACT,aAAa;GACb,eAAe;EACjB;CACF;AACF"}
@@ -1,34 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- export { l as desktopComputerDisconnectRequestSchema } from "./dist-zRc0hA1y.js";
4
- import "./task-result-DhOFm1C_.js";
5
- import "./dist-53uvP0DN.js";
6
- import "./prepare-provider-runtime-B4go-qdR.js";
7
- import "./dist-D7SkvUZW.js";
8
- import "./runtime-transport-Dg7E0ROH.js";
9
- import "./local-components-B3vffkMy.js";
10
- import "./windows-artifact-D99JU1ll.js";
11
- import "./cli-binary-manifest-CaeaM1Nd.js";
12
- import "./controller-contract-Ciy9Smgo.js";
13
- import "./conversation-execution-state-BOWTCU0B.js";
14
- import "./control-plane-dGjd5iC7.js";
15
- import "./daemon-device-id-D-RHe9se.js";
16
- import "./channel-CFIRo4fR.js";
17
- import "./state-Der85tER.js";
18
- import "./service-_kQjYdi5.js";
19
- import "./dispatch-owned-runtime-CZLplr8F.js";
20
- import "./service-account-admission-DN33uHmt.js";
21
- import "./meta-api-BpSn7MBy.js";
22
- import "./updates-api-B8lZk9gI.js";
23
- import "./daemon-service-runtime-CaUu_AdU.js";
24
- import "./daemon-runtime-lease-DRYVXnBQ.js";
25
- import "./daemon-service-update-state-BSn45OHj.js";
26
- import "./windows-system-DsNqYvVr.js";
27
- import "./windows-task-command-COu_6Ke3.js";
28
- import "./openmeld-tools-update-coordinator-B_Dd_-GW.js";
29
- import "./command-DdMi5g2D.js";
30
- import "./auth-session-DRQMn41Z.js";
31
- import "./lock-DP8d33p_.js";
32
- import "./sensitive-operation-credentials-Dr_neVvL.js";
33
- import "./runtime-CxjWWXTL.js";
34
- import "./openmeld-DI9YIFFj.js";
@@ -1 +0,0 @@
1
- {"version":3,"file":"entry-CKyKfeY0.js","names":[],"sources":["../src/local-service/execution-host/identity.ts","../src/local-service/execution-host/ownership.ts","../src/local-service/execution-host/entry.ts"],"sourcesContent":["import { resolve } from \"node:path\";\nimport type { ServiceExecutionHostIdentity } from \"@openmeld/schemas\";\nimport {\n buildStoredAuthSessionIdentity,\n getAuthSessionState,\n} from \"../../config/auth-session\";\nimport { resolveBaseUrl } from \"../../config/base-url\";\nimport { readDaemonServiceContract } from \"../../config/daemon-service-contract\";\nimport { resolveOpenMeldRootDir } from \"../../config/paths\";\nimport { readProcessStartIdentity } from \"../../system/process-identity\";\nimport { ExecutionHostError } from \"./channel\";\n\nexport async function validateExecutionHostIdentity(\n identity: ServiceExecutionHostIdentity\n) {\n if (\n process.ppid !== identity.parentPid ||\n (process.platform !== \"win32\" &&\n readProcessStartIdentity(process.ppid) !==\n identity.parentProcessStartedAt) ||\n resolve(resolveOpenMeldRootDir()) !== resolve(identity.stateRoot)\n ) {\n throw new ExecutionHostError(\n \"host.identity_mismatch\",\n \"The Host's parent or installation changed.\"\n );\n }\n const [auth, contract, gateway] = await Promise.all([\n getAuthSessionState(),\n readDaemonServiceContract(),\n resolveBaseUrl(),\n ]);\n const session = auth.session;\n if (\n auth.state !== \"valid\" ||\n !session ||\n !contract ||\n session.user?.id !== identity.ownerUserId ||\n buildStoredAuthSessionIdentity(session) !== identity.sessionIdentity ||\n session.authBaseUrl !== identity.authBaseUrl ||\n gateway !== identity.gatewayBaseUrl ||\n contract.gatewayUrl !== identity.gatewayBaseUrl ||\n contract.ownerUserId !== identity.ownerUserId ||\n contract.deviceId !== identity.deviceId ||\n contract.lane !== identity.lane ||\n contract.generation !== identity.serviceContractGeneration\n ) {\n throw new ExecutionHostError(\n \"host.identity_mismatch\",\n \"The Host's account, device or Service generation changed.\"\n );\n }\n return { session, contract };\n}\n","import { execFile } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { serviceExecutionHostOwnerSchema } from \"@openmeld/schemas\";\nimport { z } from \"zod/v4\";\nimport { acquireLock, releaseLock } from \"../../config/lock\";\nimport { systemDir } from \"../../config/paths\";\nimport {\n CURRENT_PROCESS_START_IDENTITY,\n isProcessIdentityAlive,\n readProcessStartIdentity,\n} from \"../../system/process-identity\";\nimport { ExecutionHostError } from \"./channel\";\n\nconst run = promisify(execFile);\nconst WINDOWS_BOOT_EVENT = /^\\d+:\\d+$/;\nconst DECIMAL = /^\\d+$/;\n\ntype OwnedProcessEvent = {\n phase: \"process_exit\" | \"process_spawned\";\n processId: number | null;\n signalTarget: \"process\" | \"process_group\";\n};\n\nexport async function readExecutionHostBootIdentity(): Promise<string | null> {\n try {\n return await readBootIdentity();\n } catch {\n // Fresh/quiescent starts do not require reboot evidence. Unknown evidence\n // can never clear an unsafe previous owner, and is not another boot.\n console.warn(\n \"[openmeld.execution_host.boot_unknown] Automatic recovery of unconfirmed work requires operating-system restart evidence.\"\n );\n return null;\n }\n}\n\nasync function readBootIdentity(): Promise<string | null> {\n if (process.platform === \"linux\") {\n const id = z\n .uuid()\n .parse(\n (await readFile(\"/proc/sys/kernel/random/boot_id\", \"utf8\")).trim()\n );\n return `linux:${id.toLowerCase()}`;\n }\n let stdout = \"\";\n if (process.platform === \"darwin\") {\n // XNU's immutable boot-session UUID, not its clock-adjustable boot time.\n ({ stdout } = await run(\n \"/usr/sbin/sysctl\",\n [\"-n\", \"kern.bootsessionuuid\"],\n {\n timeout: 5000,\n }\n ));\n return `darwin:${z.uuid().parse(stdout.trim()).toLowerCase()}`;\n }\n if (process.platform === \"win32\") {\n ({ stdout } = await run(\n \"powershell.exe\",\n [\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n \"$ErrorActionPreference='Stop'; $e=Get-WinEvent -FilterHashtable @{LogName='System';ProviderName='Microsoft-Windows-Kernel-General';Id=12} -MaxEvents 1; if($null -eq $e.RecordId -or $null -eq $e.TimeCreated){throw 'Boot event unavailable'}; [Console]::WriteLine(([string]$e.RecordId)+':'+([string]$e.TimeCreated.ToUniversalTime().Ticks))\",\n ],\n { timeout: 5000, windowsHide: true }\n ));\n if (!WINDOWS_BOOT_EVENT.test(stdout.trim())) {\n throw new Error(\"Invalid Windows boot event\");\n }\n return `win32:${stdout.trim()}`;\n }\n return null;\n}\n\nfunction confirmsNewBoot(\n previous: string | null,\n current: string | null\n): boolean {\n if (!(previous && current) || previous === current) {\n return false;\n }\n const [priorSource, priorId, priorTime] = previous.split(\":\");\n const [source, id, time] = current.split(\":\");\n if (source !== priorSource) {\n return false;\n }\n if (source === \"linux\" || source === \"darwin\") {\n return (\n z.uuid().safeParse(id).success && z.uuid().safeParse(priorId).success\n );\n }\n // Kernel-General 12 records OS startup, not EventLog-service restarts or\n // wall-clock corrections. Require a later retained event in both fields;\n // missing/cleared/rotated evidence cannot authorize replacing unknown work.\n if (\n source !== \"win32\" ||\n !id ||\n !time ||\n !priorId ||\n !priorTime ||\n ![id, time, priorId, priorTime].every((value) => DECIMAL.test(value))\n ) {\n return false;\n }\n return BigInt(id) > BigInt(priorId) && BigInt(time) > BigInt(priorTime);\n}\n\nexport async function acquireExecutionHostOwnership(input: {\n hostInstanceId: string;\n ownerUserId: string;\n deviceId: string;\n lane: \"prod\" | \"dev-local\" | \"canary\";\n stateRoot: string;\n bootIdentity: string | null;\n}) {\n const lock = await acquireLock({\n openMeldProfileId: \"service-execution-host\",\n key: \"process-owner\",\n pathResolution: { env: { ...process.env, OPENMELD_HOME: input.stateRoot } },\n meta: {\n hostInstanceId: input.hostInstanceId,\n ownerUserId: input.ownerUserId,\n },\n });\n const path = join(\n systemDir({ env: { OPENMELD_HOME: input.stateRoot } }),\n \"execution-host-owner.json\"\n );\n try {\n const previous = readOwner(path);\n if (\n previous &&\n !previous.localQuiescent &&\n !confirmsNewBoot(previous.bootIdentity, input.bootIdentity) &&\n !canRecoverPreviousOwnerOnSameBoot(previous)\n ) {\n throw new ExecutionHostError(\n \"host.previous_work_unconfirmed\",\n \"The previous execution host ended before its local work was confirmed stopped. Restart this Computer, then check its connection. If restart evidence is unavailable, inspect the retained Host diagnostics before recovery. Existing results remain saved; no task will be restarted automatically.\"\n );\n }\n let owner = serviceExecutionHostOwnerSchema.parse({\n schema: \"service-execution-host-owner-v2\",\n hostInstanceId: input.hostInstanceId,\n ownerUserId: input.ownerUserId,\n deviceId: input.deviceId,\n lane: input.lane,\n pid: process.pid,\n processStartedAt: CURRENT_PROCESS_START_IDENTITY,\n bootIdentity: input.bootIdentity,\n localQuiescent: true,\n processEvidenceComplete: true,\n ownedProcessTrees: [],\n });\n persist(owner);\n function persist(next: typeof owner) {\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n const temporary = `${path}.${randomUUID()}.tmp`;\n writeFileSync(temporary, JSON.stringify(next), {\n mode: 0o600,\n flag: \"wx\",\n });\n renameSync(temporary, path);\n }\n return {\n observeLocalQuiescence(quiescent: boolean) {\n if (owner.localQuiescent === quiescent) {\n return;\n }\n const next = {\n ...owner,\n localQuiescent: quiescent,\n ...(owner.schema === \"service-execution-host-owner-v2\"\n ? {\n processEvidenceComplete: quiescent,\n ...(quiescent ? { ownedProcessTrees: [] } : {}),\n }\n : {}),\n };\n // The unsafe transition is durable before any provider operation. A\n // failed write refuses that operation rather than weakening the fence.\n persist(next);\n owner = next;\n },\n observeOwnedProcess(event: OwnedProcessEvent) {\n if (owner.schema !== \"service-execution-host-owner-v2\") {\n return;\n }\n if (event.phase === \"process_spawned\") {\n if (event.processId === null) {\n const next = { ...owner, processEvidenceComplete: false };\n persist(next);\n owner = next;\n return;\n }\n const processStartedAt =\n readProcessStartIdentity(event.processId) ??\n `fallback:${event.processId}:unknown`;\n const next = {\n ...owner,\n processEvidenceComplete: true,\n ownedProcessTrees: [\n ...owner.ownedProcessTrees.filter(\n (process) => process.pid !== event.processId\n ),\n {\n pid: event.processId,\n processStartedAt,\n signalTarget: event.signalTarget,\n },\n ],\n };\n persist(next);\n owner = next;\n return;\n }\n if (event.processId === null) {\n return;\n }\n const next = {\n ...owner,\n ownedProcessTrees: owner.ownedProcessTrees.filter(\n (process) =>\n process.pid !== event.processId ||\n isOwnedProcessTreeAlive(process)\n ),\n };\n persist(next);\n owner = next;\n },\n release: () => releaseLock(lock),\n };\n } catch (error) {\n await releaseLock(lock);\n throw error;\n }\n}\n\nfunction canRecoverPreviousOwnerOnSameBoot(\n previous: ReturnType<typeof readOwner>\n): boolean {\n if (\n !previous ||\n previous.schema !== \"service-execution-host-owner-v2\" ||\n !previous.processEvidenceComplete ||\n isProcessIdentityAlive({\n ownerPid: previous.pid,\n ownerProcessStartedAt: previous.processStartedAt,\n })\n ) {\n return false;\n }\n return previous.ownedProcessTrees.every(\n (process) => !isOwnedProcessTreeAlive(process)\n );\n}\n\nfunction isOwnedProcessTreeAlive(input: {\n pid: number;\n processStartedAt: string;\n signalTarget: \"process\" | \"process_group\";\n}): boolean {\n if (input.signalTarget === \"process_group\" && process.platform !== \"win32\") {\n try {\n process.kill(-input.pid, 0);\n return true;\n } catch (error) {\n return !isNodeError(error, \"ESRCH\");\n }\n }\n return isProcessIdentityAlive({\n ownerPid: input.pid,\n ownerProcessStartedAt: input.processStartedAt,\n });\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n return (\n error instanceof Error && \"code\" in error && String(error.code) === code\n );\n}\n\nfunction readOwner(path: string) {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n const parsed = serviceExecutionHostOwnerSchema.safeParse(JSON.parse(raw));\n if (!parsed.success) {\n throw new ExecutionHostError(\n \"host.owner_corrupt\",\n \"The Host ownership record cannot be verified. Preserve it for diagnostics; automatic replacement is refused.\"\n );\n }\n return parsed.data;\n}\n","import {\n type ServiceExecutionHostIdentity,\n serviceExecutionHostMethods,\n} from \"@openmeld/schemas\";\nimport {\n type StoredAuthSession,\n withAdmittedServiceSession,\n} from \"../../config/auth-session\";\nimport { resolveRuntimeContext } from \"../../runtime/context\";\nimport { createPresenter } from \"../../runtime/presenter/index\";\nimport { ensureDaemonRuntimePaths } from \"../state/daemon-device-id\";\nimport {\n ExecutionHostError,\n type ExecutionHostHandlers,\n serveExecutionHost,\n} from \"./channel\";\nimport { validateExecutionHostIdentity } from \"./identity\";\nimport {\n acquireExecutionHostOwnership,\n readExecutionHostBootIdentity,\n} from \"./ownership\";\nimport { parentExecutionHostChannel } from \"./process-channel\";\n\n// This entry has no public listener and accepts no executable/path override.\n// The inherited pipe, parent incarnation and current Service account are all\n// required before the provider graph or any local runtime state is opened.\nexport function runExecutionHost(hostInstanceId: string): Promise<void> {\n const channel = parentExecutionHostChannel();\n const done = Promise.withResolvers<void>();\n let runtime: Awaited<\n ReturnType<typeof import(\"./runtime\").createExecutionHostRuntime>\n > | null = null;\n let ownership: Awaited<\n ReturnType<typeof acquireExecutionHostOwnership>\n > | null = null;\n let session: StoredAuthSession | null = null;\n let acceptedIdentity: ServiceExecutionHostIdentity | null = null;\n let initializing: Promise<void> | null = null;\n let closing: Promise<void> | null = null;\n let disconnected = false;\n\n const close = (): Promise<void> => {\n if (!closing) {\n closing = (async () => {\n try {\n await initializing;\n if (runtime && session) {\n const currentRuntime = runtime;\n await withAdmittedServiceSession(session, () =>\n currentRuntime.closeAfterConnectorLoss()\n );\n }\n } finally {\n await ownership?.release();\n server.dispose();\n if (process.connected) {\n process.disconnect();\n }\n }\n })();\n closing.then(\n () => done.resolve(),\n (error) => done.reject(error)\n );\n }\n return closing;\n };\n\n const handlers = {\n initialize: async (identity: ServiceExecutionHostIdentity) => {\n if (\n acceptedIdentity &&\n JSON.stringify(acceptedIdentity) !== JSON.stringify(identity)\n ) {\n throw new ExecutionHostError(\n \"host.identity_mismatch\",\n \"This Host is already assigned to a different Service incarnation.\"\n );\n }\n if (!initializing) {\n acceptedIdentity = identity;\n initializing = (async () => {\n const verified = await validateExecutionHostIdentity(identity);\n if (disconnected) {\n throw new ExecutionHostError(\n \"host.disconnected\",\n \"The supervising Service left before Host initialization.\"\n );\n }\n const verifiedOwnership = await acquireExecutionHostOwnership({\n ...identity,\n hostInstanceId,\n bootIdentity: await readExecutionHostBootIdentity(),\n });\n ownership = verifiedOwnership;\n session = verified.session;\n await withAdmittedServiceSession(session, async () => {\n const { createExecutionHostRuntime, createExecutionHostResources } =\n await import(\"./runtime\");\n const runtimePaths = await ensureDaemonRuntimePaths();\n const presenter = createPresenter(\n await resolveRuntimeContext({ view: \"agent\" })\n );\n runtime = await createExecutionHostRuntime({\n resources: await createExecutionHostResources({\n runtimePaths,\n presenter,\n observeOwnedProcess: (event) =>\n verifiedOwnership.observeOwnedProcess(event),\n }),\n hostInstanceId,\n identity,\n runtimePaths,\n serviceBundleId: verified.contract.bundleId,\n profileOwnerName: verified.session.user?.name ?? null,\n presenter,\n emit: (event) => {\n if (!disconnected) {\n server.emit(event);\n }\n },\n onWorkStateChange: (quiescent) =>\n verifiedOwnership.observeLocalQuiescence(quiescent),\n });\n });\n })();\n }\n await initializing;\n if (!runtime || disconnected) {\n throw new ExecutionHostError(\n \"host.disconnected\",\n \"The execution Host is not available.\"\n );\n }\n return runtime.snapshot();\n },\n } as ExecutionHostHandlers;\n\n // Each concrete method is still decoded by the shared method table at both\n // ends; the forwarding bridge cannot select a new account or mutate identity.\n for (const method of Object.keys(serviceExecutionHostMethods) as Array<\n keyof ExecutionHostHandlers\n >) {\n if (method === \"initialize\") {\n continue;\n }\n const target = handlers as unknown as Record<\n string,\n (payload: unknown) => Promise<unknown>\n >;\n target[method] = async (payload) => {\n if (!(runtime && session) || disconnected) {\n throw new ExecutionHostError(\n \"host.not_initialized\",\n \"Initialize this Host through its supervising Service first.\"\n );\n }\n const invoke = runtime.handlers[method] as (value: unknown) => unknown;\n return await withAdmittedServiceSession(\n session,\n async () => await invoke(payload)\n );\n };\n }\n\n const server = serveExecutionHost({\n channel,\n hostInstanceId,\n handlers,\n onFailure: (error) => {\n console.error(\"[openmeld.execution_host.channel_failed]\", error);\n disconnected = true;\n close().catch(() => undefined);\n },\n onDisconnect: () => {\n disconnected = true;\n close().catch(() => undefined);\n },\n });\n return done.promise;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAYA,eAAsB,8BACpB,UACA;CACA,IACE,QAAQ,SAAS,SAAS,aACzB,QAAQ,aAAa,WACpB,yBAAyB,QAAQ,IAAI,MACnC,SAAS,0BACb,QAAQ,uBAAuB,CAAC,MAAM,QAAQ,SAAS,SAAS,GAEhE,MAAM,IAAI,mBACR,0BACA,4CACF;CAEF,MAAM,CAAC,MAAM,UAAU,WAAW,MAAM,QAAQ,IAAI;EAClD,oBAAoB;EACpB,0BAA0B;EAC1B,eAAe;CACjB,CAAC;CACD,MAAM,UAAU,KAAK;CACrB,IACE,KAAK,UAAU,WACf,CAAC,WACD,CAAC,YACD,QAAQ,MAAM,OAAO,SAAS,eAC9B,+BAA+B,OAAO,MAAM,SAAS,mBACrD,QAAQ,gBAAgB,SAAS,eACjC,YAAY,SAAS,kBACrB,SAAS,eAAe,SAAS,kBACjC,SAAS,gBAAgB,SAAS,eAClC,SAAS,aAAa,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