openmeld 0.3.122 → 0.3.124

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.
@@ -86,6 +86,16 @@ const DAEMON_SERVICE_EXECUTABLE_WRAPPER_FILENAME_BY_PRESET = {
86
86
  "dev-local": "OpenMeld Service Dev",
87
87
  canary: "OpenMeld Service Canary"
88
88
  };
89
+ const DAEMON_SERVICE_BINARY_EXECUTABLE_FILENAME_BY_PRESET = {
90
+ prod: "OpenMeld Service Binary",
91
+ "dev-local": "OpenMeld Service Binary Dev",
92
+ canary: "OpenMeld Service Binary Canary"
93
+ };
94
+ const DAEMON_SERVICE_UPDATE_WORKER_BINARY_FILENAME_BY_PRESET = {
95
+ prod: "OpenMeld Update Worker Binary",
96
+ "dev-local": "OpenMeld Update Worker Binary Dev",
97
+ canary: "OpenMeld Update Worker Binary Canary"
98
+ };
89
99
  const DAEMON_SERVICE_LEGACY_EXECUTABLE_WRAPPER_FILENAME_BY_PRESET = {
90
100
  prod: "openmeld-service",
91
101
  "dev-local": "openmeld-dev-service",
@@ -396,13 +406,24 @@ function daemonServiceStableExecutableWrapperPath(pathInput = {}) {
396
406
  const preset = resolveOpenMeldEnvPreset(pathInput);
397
407
  return join(daemonRuntimeServiceManagerPath(pathInput), DAEMON_SERVICE_EXECUTABLE_WRAPPER_FILENAME_BY_PRESET[preset]);
398
408
  }
409
+ function daemonServiceStableBinaryExecutablePath(pathInput = {}) {
410
+ const preset = resolveOpenMeldEnvPreset(pathInput);
411
+ return join(daemonRuntimeServiceManagerPath(pathInput), DAEMON_SERVICE_BINARY_EXECUTABLE_FILENAME_BY_PRESET[preset]);
412
+ }
413
+ function daemonServiceUpdateWorkerBinaryExecutablePath(pathInput = {}) {
414
+ const preset = resolveOpenMeldEnvPreset(pathInput);
415
+ return join(daemonRuntimeServiceManagerPath(pathInput), DAEMON_SERVICE_UPDATE_WORKER_BINARY_FILENAME_BY_PRESET[preset]);
416
+ }
399
417
  function daemonServiceLegacyExecutableWrapperPath(pathInput = {}) {
400
418
  const preset = resolveOpenMeldEnvPreset(pathInput);
401
419
  return join(daemonRuntimeServiceManagerPath(pathInput), DAEMON_SERVICE_LEGACY_EXECUTABLE_WRAPPER_FILENAME_BY_PRESET[preset]);
402
420
  }
403
- function daemonServiceRecognizedExecutableWrapperPaths(pathInput = {}) {
421
+ function daemonServiceExecutableWrapperPaths(pathInput = {}) {
404
422
  return [daemonServiceStableExecutableWrapperPath(pathInput), daemonServiceLegacyExecutableWrapperPath(pathInput)];
405
423
  }
424
+ function daemonServiceRecognizedExecutablePaths(pathInput = {}) {
425
+ return [daemonServiceStableBinaryExecutablePath(pathInput), ...daemonServiceExecutableWrapperPaths(pathInput)];
426
+ }
406
427
  function daemonTokenPath(pathInput = {}) {
407
428
  return join(systemDir(pathInput), "daemon-token.json");
408
429
  }
@@ -708,6 +729,6 @@ async function clearDaemonRuntimeLease(pathInput = {}) {
708
729
  await rm(daemonRuntimeLeasePath(pathInput), { force: true });
709
730
  }
710
731
  //#endregion
711
- export { isDaemonServiceRuntimeHeartbeatStale as A, setDaemonServiceRuntimeState as B, daemonServiceStableExecutableWrapperPath as C, getDaemonRuntimeStatus as D, ensureDaemonControlPlaneToken as E, releaseDaemonServiceLifecycleLock as F, withDaemonServiceStopLock as G, withDaemonServiceReconcileLock as H, resolveDaemonControlPlaneEndpoint as I, readDaemonLocalStateFile as K, resolveDaemonServiceRuntimeMetadata as L, readDaemonServiceLifecycleLockMeta as M, readDaemonServiceLifecycleLockMetaWithCleanup as N, getDaemonStatus as O, readDaemonServiceRuntimeSnapshot as P, restoreDaemonInstallStateSnapshot as R, daemonServiceRepairJournalPath as S, daemonStatePath as T, withDaemonServiceRegistrationMutationLock as U, uninstallDaemon as V, withDaemonServiceRunLock as W, daemonRuntimeServiceManagerPath as _, DAEMON_SERVICE_RUNTIME_CONTROLLER_ENV as a, daemonServiceLegacyExecutableWrapperPath as b, DAEMON_SERVICE_RUNTIME_STATE_SCHEMA as c, clearDaemonServiceRuntimeState as d, daemonDispatchJournalPath as f, daemonRuntimeRootPath as g, daemonRuntimeDataPath as h, DAEMON_SERVICE_RUNTIME_AUTO_START_ENV as i, readDaemonControlPlaneToken as j, installDaemon as k, DAEMON_SERVICE_RUNTIME_SYSTEM_SERVICE_ENV as l, daemonRuntimeBundlesPath as m, writeDaemonRuntimeLease as n, DAEMON_SERVICE_RUNTIME_DETACHED_ENV as o, daemonLifecycleJournalPath as p, writeDaemonLocalStateFile as q, DAEMON_HEARTBEAT_STALE_MS as r, DAEMON_SERVICE_RUNTIME_MODE_ENV as s, readDaemonRuntimeLease as t, acquireDaemonServiceLifecycleLock as u, daemonRuntimeStateRootPath as v, daemonServiceStableLauncherPath as w, daemonServiceRecognizedExecutableWrapperPaths as x, daemonServiceActiveBundleStatePath as y, rotateDaemonControlPlaneTokenIfExpired as z };
732
+ export { getDaemonRuntimeStatus as A, resolveDaemonServiceRuntimeMetadata as B, daemonServiceRepairJournalPath as C, daemonServiceUpdateWorkerBinaryExecutablePath as D, daemonServiceStableLauncherPath as E, readDaemonServiceLifecycleLockMeta as F, withDaemonServiceReconcileLock as G, rotateDaemonControlPlaneTokenIfExpired as H, readDaemonServiceLifecycleLockMetaWithCleanup as I, withDaemonServiceStopLock as J, withDaemonServiceRegistrationMutationLock as K, readDaemonServiceRuntimeSnapshot as L, installDaemon as M, isDaemonServiceRuntimeHeartbeatStale as N, daemonStatePath as O, readDaemonControlPlaneToken as P, releaseDaemonServiceLifecycleLock as R, daemonServiceRecognizedExecutablePaths as S, daemonServiceStableExecutableWrapperPath as T, setDaemonServiceRuntimeState as U, restoreDaemonInstallStateSnapshot as V, uninstallDaemon as W, writeDaemonLocalStateFile as X, readDaemonLocalStateFile as Y, daemonRuntimeServiceManagerPath as _, DAEMON_SERVICE_RUNTIME_CONTROLLER_ENV as a, daemonServiceExecutableWrapperPaths as b, DAEMON_SERVICE_RUNTIME_STATE_SCHEMA as c, clearDaemonServiceRuntimeState as d, daemonDispatchJournalPath as f, daemonRuntimeRootPath as g, daemonRuntimeDataPath as h, DAEMON_SERVICE_RUNTIME_AUTO_START_ENV as i, getDaemonStatus as j, ensureDaemonControlPlaneToken as k, DAEMON_SERVICE_RUNTIME_SYSTEM_SERVICE_ENV as l, daemonRuntimeBundlesPath as m, writeDaemonRuntimeLease as n, DAEMON_SERVICE_RUNTIME_DETACHED_ENV as o, daemonLifecycleJournalPath as p, withDaemonServiceRunLock as q, DAEMON_HEARTBEAT_STALE_MS as r, DAEMON_SERVICE_RUNTIME_MODE_ENV as s, readDaemonRuntimeLease as t, acquireDaemonServiceLifecycleLock as u, daemonRuntimeStateRootPath as v, daemonServiceStableBinaryExecutablePath as w, daemonServiceLegacyExecutableWrapperPath as x, daemonServiceActiveBundleStatePath as y, resolveDaemonControlPlaneEndpoint as z };
712
733
 
713
- //# sourceMappingURL=daemon-runtime-lease-Cath1v3w.js.map
734
+ //# sourceMappingURL=daemon-runtime-lease-Cvo63MGd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"daemon-runtime-lease-Cvo63MGd.js","names":[],"sources":["../../../packages/schemas/dist/schemas/daemon/runtime-lease.js","../src/config/daemon-local-state-file.ts","../src/config/daemon-state.ts","../src/config/daemon-runtime-lease.ts"],"sourcesContent":["import { daemonServiceControllerSchema } from \"./service-contract.js\";\nimport * as z$1 from \"zod/v4\";\n//#region src/schemas/daemon/runtime-lease.ts\nconst DAEMON_RUNTIME_LEASE_SCHEMA_VERSION = 1;\nconst daemonRuntimeLeaseModeSchema = z$1.enum([\"foreground\", \"background\"]);\nconst daemonRuntimeLeaseSchema = z$1.strictObject({\n\tschema: z$1.literal(\"openmeld-daemon-runtime-lease-v1\"),\n\tv: z$1.literal(1),\n\tgeneration: z$1.int().nonnegative(),\n\tbundleId: z$1.string().min(1),\n\tpid: z$1.int().positive(),\n\tmode: daemonRuntimeLeaseModeSchema,\n\tstartedAt: z$1.string().min(1),\n\tupdatedAt: z$1.string().min(1),\n\theartbeatAt: z$1.string().nullable(),\n\tserviceController: daemonServiceControllerSchema,\n\tmanagedBySystemService: z$1.boolean()\n});\n//#endregion\nexport { DAEMON_RUNTIME_LEASE_SCHEMA_VERSION, daemonRuntimeLeaseModeSchema, daemonRuntimeLeaseSchema };\n\n//# sourceMappingURL=runtime-lease.js.map","import {\n chmod,\n mkdir,\n readFile,\n rename,\n rm,\n writeFile,\n} from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\ntype SafeParseResult<T> = { success: true; data: T } | { success: false };\n\ntype DaemonLocalStateSchema<T> = {\n safeParse: (value: unknown) => SafeParseResult<T>;\n};\n\nexport async function readDaemonLocalStateFile<T>(input: {\n path: string;\n schema: DaemonLocalStateSchema<T>;\n}): Promise<T | null> {\n const raw = await readFile(input.path, \"utf8\").catch((error) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\n return null;\n }\n throw error;\n });\n if (raw === null) {\n return null;\n }\n\n const parsedJson = safeParseJson(raw);\n if (parsedJson === null) {\n return null;\n }\n const parsed = input.schema.safeParse(parsedJson);\n return parsed.success ? parsed.data : null;\n}\n\nexport async function writeDaemonLocalStateFile<T>(input: {\n path: string;\n schema: DaemonLocalStateSchema<T>;\n value: T;\n mode?: number;\n}): Promise<void> {\n const parsed = input.schema.safeParse(input.value);\n if (!parsed.success) {\n throw new Error(`invalid daemon local state for ${input.path}`);\n }\n\n await mkdir(dirname(input.path), { recursive: true });\n const tempPath = `${input.path}.tmp-${process.pid}-${Date.now()}`;\n let shouldCleanupTemp = true;\n\n try {\n await writeFile(tempPath, `${JSON.stringify(parsed.data, null, 2)}\\n`, {\n encoding: \"utf8\",\n ...(typeof input.mode === \"number\" ? { mode: input.mode } : {}),\n });\n await rename(tempPath, input.path);\n if (typeof input.mode === \"number\") {\n await chmod(input.path, input.mode);\n }\n shouldCleanupTemp = false;\n } finally {\n if (shouldCleanupTemp) {\n await rm(tempPath, { force: true }).catch(() => undefined);\n }\n }\n}\n\nfunction safeParseJson(raw: string): unknown | null {\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport {\n chmod,\n mkdir,\n readFile,\n rename,\n rm,\n stat,\n writeFile,\n} from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n acquireLock,\n type OpenMeldLock,\n readLockMeta,\n releaseLock,\n runWithHeldLock,\n tryCleanupStaleLock,\n} from \"./lock\";\nimport type { OpenMeldEnvPreset, OpenMeldPathResolutionInput } from \"./paths\";\nimport {\n resolveOpenMeldEnvPreset,\n resolveOpenMeldPresetOwnedPathInput,\n resolveOpenMeldRootDir,\n runtimeDir,\n systemDir,\n} from \"./paths\";\n\nconst DAEMON_STATE_SCHEMA = \"openmeld-daemon-install-v1\";\nexport const DAEMON_SERVICE_RUNTIME_STATE_SCHEMA =\n \"openmeld-daemon-service-state-v1\";\nexport const DAEMON_SERVICE_RUNTIME_MODE_ENV = \"OPENMELD_DAEMON_RUNTIME_MODE\";\nexport const DAEMON_SERVICE_RUNTIME_DETACHED_ENV =\n \"OPENMELD_DAEMON_RUNTIME_DETACHED\";\nexport const DAEMON_SERVICE_RUNTIME_CONTROLLER_ENV =\n \"OPENMELD_DAEMON_SERVICE_CONTROLLER\";\nexport const DAEMON_SERVICE_RUNTIME_AUTO_START_ENV =\n \"OPENMELD_DAEMON_SERVICE_AUTO_START\";\nexport const DAEMON_SERVICE_RUNTIME_SYSTEM_SERVICE_ENV =\n \"OPENMELD_DAEMON_RUNTIME_SYSTEM_SERVICE\";\nconst DAEMON_TOKEN_SCHEMA = \"openmeld-daemon-token-v1\";\nconst DAEMON_TOKEN_ROTATE_MAX_AGE_MS = 24 * 60 * 60 * 1000;\nexport const DAEMON_HEARTBEAT_STALE_MS = 3 * 60 * 1000;\nconst DAEMON_ACTIVE_BUNDLE_STATE_FILENAME = \"active-bundle.json\";\nconst DAEMON_DISPATCH_JOURNAL_FILENAME = \"daemon-dispatch-journal.jsonl\";\nconst DAEMON_LIFECYCLE_JOURNAL_FILENAME = \"daemon-lifecycle-journal.jsonl\";\nconst DAEMON_REPAIR_JOURNAL_FILENAME = \"repair-journal.json\";\nconst DAEMON_SERVICE_LOCK_PROFILE = \"daemon-service\";\nconst DAEMON_SERVICE_LOCK_KEY = \"daemon-service-run\";\ntype DaemonServiceLifecycleLockContext = {\n active: boolean;\n failures: unknown[];\n ownerRoot: string;\n pendingOperations: Set<Promise<void>>;\n};\nconst daemonServiceLifecycleLockContext =\n new AsyncLocalStorage<DaemonServiceLifecycleLockContext>();\nconst DAEMON_STABLE_LAUNCHER_FILENAME = \"daemon-service-launcher.mjs\";\nconst DAEMON_SERVICE_EXECUTABLE_WRAPPER_FILENAME_BY_PRESET = {\n prod: \"OpenMeld Service\",\n \"dev-local\": \"OpenMeld Service Dev\",\n canary: \"OpenMeld Service Canary\",\n} as const satisfies Record<OpenMeldEnvPreset, string>;\nconst DAEMON_SERVICE_BINARY_EXECUTABLE_FILENAME_BY_PRESET = {\n prod: \"OpenMeld Service Binary\",\n \"dev-local\": \"OpenMeld Service Binary Dev\",\n canary: \"OpenMeld Service Binary Canary\",\n} as const satisfies Record<OpenMeldEnvPreset, string>;\nconst DAEMON_SERVICE_UPDATE_WORKER_BINARY_FILENAME_BY_PRESET = {\n prod: \"OpenMeld Update Worker Binary\",\n \"dev-local\": \"OpenMeld Update Worker Binary Dev\",\n canary: \"OpenMeld Update Worker Binary Canary\",\n} as const satisfies Record<OpenMeldEnvPreset, string>;\nconst DAEMON_SERVICE_LEGACY_EXECUTABLE_WRAPPER_FILENAME_BY_PRESET = {\n prod: \"openmeld-service\",\n \"dev-local\": \"openmeld-dev-service\",\n canary: \"openmeld-canary-service\",\n} as const satisfies Record<OpenMeldEnvPreset, string>;\nexport const DAEMON_SERVICE_LIFECYCLE_LOCK_PROFILE =\n DAEMON_SERVICE_LOCK_PROFILE;\nexport const DAEMON_SERVICE_LIFECYCLE_LOCK_KEY = DAEMON_SERVICE_LOCK_KEY;\nexport type DaemonServiceLifecycleLock = OpenMeldLock;\n\nexport type DaemonLifecycleIntent =\n | \"run_background\"\n | \"run_foreground\"\n | \"stop\"\n | \"autostart\"\n | \"status_cleanup\"\n | \"startup_check\"\n | \"start\"\n | \"reinstall\"\n | \"uninstall\"\n | \"upgrade_reconcile\";\n\nexport type DaemonLifecycleLockMeta = {\n intent: DaemonLifecycleIntent;\n command: string;\n pid?: number;\n sessionId?: string;\n at?: string;\n};\n\nexport type DaemonInstallSource = \"cli.auto_check\" | \"daemon.command.install\";\nexport type DaemonRunMode = \"foreground\" | \"background\";\nexport type DaemonServiceController =\n | \"launchd\"\n | \"systemd\"\n | \"windows-service\"\n | \"legacy-detached\"\n | \"unknown\";\n\ntype BaseDaemonServiceRuntimeState = {\n mode: DaemonRunMode;\n command: string;\n gatewayUrl: string | null;\n openMeldProfileId: string | null;\n stopRequestedAt: string | null;\n startedAt: string;\n updatedAt: string;\n heartbeatAt: string | null;\n managedBySystemService: boolean;\n serviceController: DaemonServiceController;\n autoStart: boolean;\n};\n\nexport type DaemonServiceRuntimeState = BaseDaemonServiceRuntimeState & {\n v: 1;\n schema: typeof DAEMON_SERVICE_RUNTIME_STATE_SCHEMA;\n status: \"running\";\n pid: number;\n};\n\nexport type DaemonServiceRuntimeStatus = {\n status: \"running\" | \"stale\" | \"not_running\" | \"unknown\";\n mode: DaemonRunMode | null;\n pid: number | null;\n startedAt: string | null;\n updatedAt: string | null;\n managedBySystemService: boolean;\n serviceController: DaemonServiceRuntimeState[\"serviceController\"];\n autoStart: boolean;\n reason?: string;\n};\n\nexport type DaemonServiceRuntimeMetadataInput = {\n managedBySystemService?: boolean;\n serviceController?: string;\n autoStart?: boolean;\n env?: NodeJS.ProcessEnv;\n};\n\nexport type DaemonServiceRuntimeMetadata = {\n managedBySystemService: boolean;\n serviceController: DaemonServiceController;\n autoStart: boolean;\n};\n\nexport type DaemonInstallState = {\n v: 1;\n schema: typeof DAEMON_STATE_SCHEMA;\n daemonVersion: string;\n installSource: DaemonInstallSource;\n installedAt: string;\n updatedAt: string;\n};\n\nexport type DaemonTokenState = {\n v: 1;\n schema: typeof DAEMON_TOKEN_SCHEMA;\n token: string;\n issuedAt: string;\n updatedAt: string;\n};\n\nexport type DaemonInstallResult = {\n status: \"installed\" | \"already_installed\";\n state: DaemonInstallState;\n};\n\nexport type DaemonUninstallResult = {\n removed: boolean;\n};\n\nexport type DaemonStatus =\n | {\n installed: true;\n state: DaemonInstallState;\n }\n | {\n installed: false;\n state: null;\n };\n\nexport async function getDaemonStatus(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<DaemonStatus> {\n const [state, runtimeExists] = await Promise.all([\n readDaemonInstallState(pathInput),\n pathExists(daemonRuntimeRootPath(pathInput)),\n ]);\n if (state && runtimeExists) {\n return {\n installed: true,\n state,\n };\n }\n return {\n installed: false,\n state: null,\n };\n}\n\nexport async function getDaemonRuntimeStatus(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<DaemonServiceRuntimeStatus> {\n const state = await readDaemonServiceRuntimeState(pathInput);\n if (!state) {\n return {\n status: \"not_running\",\n mode: null,\n pid: null,\n startedAt: null,\n updatedAt: null,\n managedBySystemService: false,\n serviceController: \"unknown\",\n autoStart: false,\n };\n }\n if (!Number.isInteger(state.pid) || state.pid <= 0) {\n return {\n status: \"stale\",\n mode: state.mode,\n pid: state.pid,\n startedAt: state.startedAt,\n updatedAt: state.updatedAt,\n managedBySystemService: state.managedBySystemService,\n serviceController: state.serviceController,\n autoStart: state.autoStart,\n reason: \"invalid_pid\",\n };\n }\n if (!isPidAlive(state.pid)) {\n return {\n status: \"stale\",\n mode: state.mode,\n pid: state.pid,\n startedAt: state.startedAt,\n updatedAt: state.updatedAt,\n managedBySystemService: state.managedBySystemService,\n serviceController: state.serviceController,\n autoStart: state.autoStart,\n reason: \"process_not_alive\",\n };\n }\n if (isDaemonServiceRuntimeHeartbeatStale(state)) {\n return {\n status: \"stale\",\n mode: state.mode,\n pid: state.pid,\n startedAt: state.startedAt,\n updatedAt: state.updatedAt,\n managedBySystemService: state.managedBySystemService,\n serviceController: state.serviceController,\n autoStart: state.autoStart,\n reason: \"heartbeat_stale\",\n };\n }\n return {\n status: \"running\",\n mode: state.mode,\n pid: state.pid,\n startedAt: state.startedAt,\n updatedAt: state.updatedAt,\n managedBySystemService: state.managedBySystemService,\n serviceController: state.serviceController,\n autoStart: state.autoStart,\n };\n}\n\nexport async function readDaemonServiceRuntimeSnapshot(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<DaemonServiceRuntimeState | null> {\n return await readDaemonServiceRuntimeState(pathInput);\n}\n\nexport function resolveDaemonServiceRuntimeMetadata(\n input: DaemonServiceRuntimeMetadataInput = {}\n): DaemonServiceRuntimeMetadata {\n const env = input.env ?? process.env;\n const managedBySystemService =\n input.managedBySystemService === true ||\n env[DAEMON_SERVICE_RUNTIME_SYSTEM_SERVICE_ENV] === \"1\";\n const serviceControllerInput =\n typeof input.serviceController === \"string\" &&\n input.serviceController.length > 0\n ? input.serviceController\n : env[DAEMON_SERVICE_RUNTIME_CONTROLLER_ENV];\n const autoStart =\n input.autoStart === true ||\n env[DAEMON_SERVICE_RUNTIME_AUTO_START_ENV] === \"1\";\n\n return {\n managedBySystemService,\n serviceController: parseDaemonServiceController(serviceControllerInput),\n autoStart,\n };\n}\n\nexport async function setDaemonServiceRuntimeState(\n state: DaemonServiceRuntimeState,\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<void> {\n await writeDaemonServiceRuntimeState(state, pathInput);\n}\n\nexport async function clearDaemonServiceRuntimeState(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<void> {\n const { clearDaemonRuntimeLease } = await import(\"./daemon-runtime-lease\");\n await Promise.all([\n rm(daemonServiceRuntimeStatePath(pathInput), { force: true }),\n clearDaemonRuntimeLease(pathInput),\n ]);\n}\n\nexport function withDaemonServiceRunLock<T>(\n callback: () => Promise<T>,\n meta: DaemonLifecycleLockMeta = {\n intent: \"run_background\",\n command: \"openmeld service start\",\n }\n): Promise<T> {\n return withDaemonServiceLifecycleLock(meta, callback);\n}\n\nexport async function acquireDaemonServiceLifecycleLock(\n meta: DaemonLifecycleLockMeta = {\n intent: \"run_background\",\n command: \"openmeld service start\",\n },\n pathResolution: OpenMeldPathResolutionInput = resolveOpenMeldPresetOwnedPathInput()\n): Promise<DaemonServiceLifecycleLock> {\n return await acquireLock({\n openMeldProfileId: DAEMON_SERVICE_LIFECYCLE_LOCK_PROFILE,\n key: DAEMON_SERVICE_LIFECYCLE_LOCK_KEY,\n meta,\n pathResolution,\n });\n}\n\nexport async function releaseDaemonServiceLifecycleLock(\n lock: DaemonServiceLifecycleLock\n): Promise<void> {\n await releaseLock(lock);\n}\n\nexport function withDaemonServiceStopLock<T>(\n callback: () => Promise<T>,\n meta: DaemonLifecycleLockMeta = {\n intent: \"stop\",\n command: \"openmeld service stop\",\n }\n): Promise<T> {\n return withDaemonServiceLifecycleLock(meta, callback);\n}\n\nexport function withDaemonServiceReconcileLock<T>(\n callback: () => Promise<T>,\n meta: DaemonLifecycleLockMeta = {\n intent: \"upgrade_reconcile\",\n command: \"openmeld service update\",\n }\n): Promise<T> {\n return withDaemonServiceLifecycleLock(meta, callback);\n}\n\nexport function withDaemonServiceRegistrationMutationLock<T>(\n callback: () => Promise<T>,\n meta: DaemonLifecycleLockMeta\n): Promise<T> {\n return withDaemonServiceLifecycleLock(meta, callback);\n}\n\nexport function withDaemonServiceLifecycleLock<T>(\n meta: DaemonLifecycleLockMeta,\n callback: () => Promise<T>\n): Promise<T> {\n const pathResolution = resolveOpenMeldPresetOwnedPathInput();\n const ownerRoot = resolveOpenMeldRootDir(pathResolution);\n const currentContext = daemonServiceLifecycleLockContext.getStore();\n if (currentContext?.active && currentContext.ownerRoot === ownerRoot) {\n let operation: Promise<T>;\n try {\n operation = callback();\n } catch (error) {\n operation = Promise.reject(error);\n }\n let trackedOperation: Promise<void>;\n trackedOperation = operation\n .then(\n () => undefined,\n (error: unknown) => {\n currentContext.failures.push(error);\n }\n )\n .finally(() => {\n currentContext.pendingOperations.delete(trackedOperation);\n });\n currentContext.pendingOperations.add(trackedOperation);\n return operation;\n }\n return withDaemonServiceLifecycleOwnerLock({\n callback,\n meta,\n ownerRoot,\n pathResolution,\n });\n}\n\nasync function withDaemonServiceLifecycleOwnerLock<T>(input: {\n callback: () => Promise<T>;\n meta: DaemonLifecycleLockMeta;\n ownerRoot: string;\n pathResolution: OpenMeldPathResolutionInput;\n}): Promise<T> {\n const lock = await acquireDaemonServiceLifecycleLock(\n input.meta,\n input.pathResolution\n );\n return await runWithHeldLock({\n lock,\n run: async () => {\n const context: DaemonServiceLifecycleLockContext = {\n active: true,\n failures: [],\n ownerRoot: input.ownerRoot,\n pendingOperations: new Set(),\n };\n let outcome: { ok: true; value: T } | { ok: false; error: unknown };\n try {\n outcome = {\n ok: true,\n value: await daemonServiceLifecycleLockContext.run(\n context,\n input.callback\n ),\n };\n } catch (error) {\n outcome = { ok: false, error };\n } finally {\n while (context.pendingOperations.size > 0) {\n await Promise.all([...context.pendingOperations]);\n }\n context.active = false;\n }\n const failures = [\n ...(outcome.ok ? [] : [outcome.error]),\n ...context.failures,\n ].filter(\n (failure, index, allFailures) => allFailures.indexOf(failure) === index\n );\n if (failures.length === 1) {\n throw failures[0];\n }\n if (failures.length > 1) {\n throw new AggregateError(\n failures,\n \"daemon service lifecycle mutation failed in more than one operation\"\n );\n }\n if (!outcome.ok) {\n throw outcome.error;\n }\n return outcome.value;\n },\n releaseContext: {\n command: input.meta.command,\n component: \"daemon_service_lifecycle\",\n intent: input.meta.intent,\n lockKey: DAEMON_SERVICE_LIFECYCLE_LOCK_KEY,\n openMeldProfileId: DAEMON_SERVICE_LIFECYCLE_LOCK_PROFILE,\n },\n });\n}\n\nexport async function readDaemonServiceLifecycleLockMeta(): Promise<DaemonLifecycleLockMeta | null> {\n const meta = await readLockMeta({\n openMeldProfileId: DAEMON_SERVICE_LIFECYCLE_LOCK_PROFILE,\n key: DAEMON_SERVICE_LIFECYCLE_LOCK_KEY,\n pathResolution: resolveOpenMeldPresetOwnedPathInput(),\n });\n if (!meta) {\n return null;\n }\n const intent =\n typeof meta.intent === \"string\"\n ? normalizeDaemonLifecycleIntent(meta.intent)\n : null;\n const command = typeof meta.command === \"string\" ? meta.command.trim() : \"\";\n if (!intent || command.length === 0) {\n return null;\n }\n const pid = typeof meta.pid === \"number\" ? meta.pid : undefined;\n const sessionId =\n typeof meta.sessionId === \"string\" && meta.sessionId.trim().length > 0\n ? meta.sessionId.trim()\n : undefined;\n const at =\n typeof meta.at === \"string\" && meta.at.trim().length > 0\n ? meta.at.trim()\n : undefined;\n return {\n intent,\n command,\n ...(typeof pid === \"number\" ? { pid } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(at ? { at } : {}),\n };\n}\n\nexport async function readDaemonServiceLifecycleLockMetaWithCleanup(): Promise<DaemonLifecycleLockMeta | null> {\n await tryCleanupStaleLock({\n openMeldProfileId: DAEMON_SERVICE_LIFECYCLE_LOCK_PROFILE,\n key: DAEMON_SERVICE_LIFECYCLE_LOCK_KEY,\n pathResolution: resolveOpenMeldPresetOwnedPathInput(),\n });\n return await readDaemonServiceLifecycleLockMeta();\n}\n\nexport async function installDaemon(input: {\n daemonVersion: string;\n source: DaemonInstallSource;\n}): Promise<DaemonInstallResult> {\n const existingState = await readDaemonInstallState();\n const runtimeExists = await pathExists(daemonRuntimeRootPath());\n if (\n existingState &&\n runtimeExists &&\n existingState.daemonVersion === input.daemonVersion\n ) {\n await ensureDaemonTokenState();\n return {\n status: \"already_installed\",\n state: existingState,\n };\n }\n\n await ensureDaemonRuntimeLayout();\n const now = new Date().toISOString();\n const nextState: DaemonInstallState = {\n v: 1,\n schema: DAEMON_STATE_SCHEMA,\n daemonVersion: input.daemonVersion,\n installSource: input.source,\n installedAt: existingState?.installedAt ?? now,\n updatedAt: now,\n };\n await writeDaemonInstallState(nextState);\n await ensureDaemonTokenState();\n\n return {\n status: \"installed\",\n state: nextState,\n };\n}\n\nexport async function uninstallDaemon(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<DaemonUninstallResult> {\n const [hasState, hasRuntimeDir, hasToken] = await Promise.all([\n pathExists(daemonStatePath(pathInput)),\n pathExists(daemonRuntimeRootPath(pathInput)),\n pathExists(daemonTokenPath(pathInput)),\n ]);\n\n await Promise.all([\n rm(daemonStatePath(pathInput), { force: true }),\n rm(daemonTokenPath(pathInput), { force: true }),\n rm(daemonServiceRuntimeStatePath(pathInput), { force: true }),\n rm(daemonRuntimeRootPath(pathInput), { recursive: true, force: true }),\n ]);\n\n return {\n removed: hasState || hasRuntimeDir || hasToken,\n };\n}\n\nexport function daemonStatePath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(systemDir(pathInput), \"daemon-install.json\");\n}\n\nexport function daemonRuntimeRootPath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(runtimeDir(pathInput), \"daemon\");\n}\n\nexport function daemonServiceRuntimeStatePath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(daemonRuntimeRootPath(pathInput), \"service-runtime.json\");\n}\n\nexport function daemonRuntimeDataPath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(daemonRuntimeRootPath(pathInput), \"data\");\n}\n\nexport function daemonRuntimeBundlesPath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(daemonRuntimeRootPath(pathInput), \"bundles\");\n}\n\nexport function daemonRuntimeStateRootPath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(daemonRuntimeRootPath(pathInput), \"state\");\n}\n\nexport function daemonLifecycleJournalPath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(\n daemonRuntimeRootPath(pathInput),\n \"logs\",\n DAEMON_LIFECYCLE_JOURNAL_FILENAME\n );\n}\n\nexport function daemonDispatchJournalPath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(\n daemonRuntimeRootPath(pathInput),\n \"logs\",\n DAEMON_DISPATCH_JOURNAL_FILENAME\n );\n}\n\nexport function daemonServiceActiveBundleStatePath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(\n daemonRuntimeStateRootPath(pathInput),\n DAEMON_ACTIVE_BUNDLE_STATE_FILENAME\n );\n}\n\nexport function daemonServiceRepairJournalPath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(\n daemonRuntimeStateRootPath(pathInput),\n DAEMON_REPAIR_JOURNAL_FILENAME\n );\n}\n\nexport function daemonRuntimeServiceManagerPath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(daemonRuntimeRootPath(pathInput), \"service-manager\");\n}\n\nexport function daemonServiceStableLauncherPath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(\n daemonRuntimeServiceManagerPath(pathInput),\n DAEMON_STABLE_LAUNCHER_FILENAME\n );\n}\n\nexport function daemonServiceStableExecutableWrapperPath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n const preset = resolveOpenMeldEnvPreset(pathInput);\n return join(\n daemonRuntimeServiceManagerPath(pathInput),\n DAEMON_SERVICE_EXECUTABLE_WRAPPER_FILENAME_BY_PRESET[preset]\n );\n}\n\nexport function daemonServiceStableBinaryExecutablePath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n const preset = resolveOpenMeldEnvPreset(pathInput);\n return join(\n daemonRuntimeServiceManagerPath(pathInput),\n DAEMON_SERVICE_BINARY_EXECUTABLE_FILENAME_BY_PRESET[preset]\n );\n}\n\nexport function daemonServiceUpdateWorkerBinaryExecutablePath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n const preset = resolveOpenMeldEnvPreset(pathInput);\n return join(\n daemonRuntimeServiceManagerPath(pathInput),\n DAEMON_SERVICE_UPDATE_WORKER_BINARY_FILENAME_BY_PRESET[preset]\n );\n}\n\nexport function daemonServiceLegacyExecutableWrapperPath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n const preset = resolveOpenMeldEnvPreset(pathInput);\n return join(\n daemonRuntimeServiceManagerPath(pathInput),\n DAEMON_SERVICE_LEGACY_EXECUTABLE_WRAPPER_FILENAME_BY_PRESET[preset]\n );\n}\n\nexport function daemonServiceExecutableWrapperPaths(\n pathInput: OpenMeldPathResolutionInput = {}\n): string[] {\n return [\n daemonServiceStableExecutableWrapperPath(pathInput),\n daemonServiceLegacyExecutableWrapperPath(pathInput),\n ];\n}\n\nexport function daemonServiceRecognizedExecutablePaths(\n pathInput: OpenMeldPathResolutionInput = {}\n): string[] {\n return [\n daemonServiceStableBinaryExecutablePath(pathInput),\n ...daemonServiceExecutableWrapperPaths(pathInput),\n ];\n}\n\nexport function daemonTokenPath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(systemDir(pathInput), \"daemon-token.json\");\n}\n\nexport async function restoreDaemonInstallStateSnapshot(\n snapshot: DaemonInstallState | null,\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<void> {\n if (!snapshot) {\n await rm(daemonStatePath(pathInput), { force: true });\n return;\n }\n await writeDaemonInstallState(snapshot, pathInput);\n}\n\nexport function resolveDaemonControlPlaneEndpoint(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n const runtimeRoot = daemonRuntimeRootPath(pathInput);\n const suffix = createHash(\"sha256\")\n .update(runtimeRoot)\n .digest(\"hex\")\n .slice(0, 24);\n if (process.platform === \"win32\") {\n return `\\\\\\\\.\\\\pipe\\\\openmeld-daemon-control-${suffix}`;\n }\n return join(tmpdir(), `openmeld-daemon-control-${suffix}.sock`);\n}\n\nexport async function ensureDaemonControlPlaneToken(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<string> {\n const state = await ensureDaemonTokenState(pathInput);\n return state.token;\n}\n\nexport async function rotateDaemonControlPlaneTokenIfExpired(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<DaemonTokenState> {\n const current = await readDaemonTokenState(pathInput);\n if (current && !isDaemonTokenExpired(current)) {\n await chmod(daemonTokenPath(pathInput), 0o600).catch(() => undefined);\n return current;\n }\n\n return await writeNewDaemonTokenState(pathInput);\n}\n\nexport async function readDaemonControlPlaneToken(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<string | null> {\n const state = await readDaemonTokenState(pathInput);\n return state?.token ?? null;\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return !(\n error instanceof Error &&\n (error as NodeJS.ErrnoException).code === \"ESRCH\"\n );\n }\n}\n\nasync function readDaemonServiceRuntimeState(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<DaemonServiceRuntimeState | null> {\n const raw = await readFile(\n daemonServiceRuntimeStatePath(pathInput),\n \"utf8\"\n ).catch((error) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\n return null;\n }\n throw error;\n });\n if (raw === null) {\n return null;\n }\n return parseDaemonServiceRuntimeState(raw);\n}\n\nfunction parseDaemonServiceRuntimeState(\n raw: string\n): DaemonServiceRuntimeState | null {\n try {\n const parsed = JSON.parse(raw);\n if (!isDaemonServiceRuntimeStateObject(parsed)) {\n return null;\n }\n\n return {\n v: 1,\n schema: DAEMON_SERVICE_RUNTIME_STATE_SCHEMA,\n status: \"running\",\n pid: parsed.pid,\n mode: parsed.mode,\n command: parsed.command,\n gatewayUrl: parseNullableString(parsed.gatewayUrl),\n openMeldProfileId: resolveStoredDaemonServiceOpenMeldProfileId(parsed),\n stopRequestedAt: parseNullableString(parsed.stopRequestedAt),\n heartbeatAt: parseNullableString(parsed.heartbeatAt),\n startedAt: parsed.startedAt,\n updatedAt: parsed.updatedAt,\n managedBySystemService: parsed.managedBySystemService === true,\n serviceController: parseDaemonServiceController(parsed.serviceController),\n autoStart: parsed.autoStart === true,\n };\n } catch {\n return null;\n }\n}\n\nfunction isDaemonServiceRuntimeStateObject(value: unknown): value is {\n v: 1;\n schema: string;\n status: \"running\";\n pid: number;\n mode: DaemonRunMode;\n command: string;\n gatewayUrl: string | null;\n openMeldProfileId?: string | null;\n profile?: string | null;\n stopRequestedAt: string | null;\n heartbeatAt: string | null;\n startedAt: string;\n updatedAt: string;\n managedBySystemService?: boolean;\n serviceController?: string;\n autoStart?: boolean;\n} {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const candidate = value as Record<string, unknown>;\n return (\n candidate.v === 1 &&\n candidate.schema === DAEMON_SERVICE_RUNTIME_STATE_SCHEMA &&\n candidate.status === \"running\" &&\n typeof candidate.pid === \"number\" &&\n candidate.pid > 0 &&\n (candidate.mode === \"foreground\" || candidate.mode === \"background\") &&\n typeof candidate.command === \"string\" &&\n candidate.command.length > 0 &&\n isValidNullableString(candidate.gatewayUrl) &&\n isValidOptionalNullableString(candidate.openMeldProfileId) &&\n isValidOptionalNullableString(candidate.profile) &&\n isValidNullableString(candidate.stopRequestedAt) &&\n isValidNullableString(candidate.heartbeatAt) &&\n typeof candidate.startedAt === \"string\" &&\n candidate.startedAt.length > 0 &&\n typeof candidate.updatedAt === \"string\" &&\n candidate.updatedAt.length > 0\n );\n}\n\nexport function parseDaemonServiceController(\n value: unknown\n): DaemonServiceController {\n if (\n value === \"launchd\" ||\n value === \"systemd\" ||\n value === \"windows-service\" ||\n value === \"legacy-detached\" ||\n value === \"unknown\"\n ) {\n return value;\n }\n return \"unknown\";\n}\n\nfunction isValidNullableString(value: unknown): value is string | null {\n return value === null || typeof value === \"string\";\n}\n\nfunction isValidOptionalNullableString(\n value: unknown\n): value is string | null | undefined {\n return value === undefined || value === null || typeof value === \"string\";\n}\n\nfunction parseNullableString(value: unknown): string | null {\n if (value === null) {\n return null;\n }\n if (typeof value !== \"string\") {\n return null;\n }\n return value;\n}\n\nfunction resolveStoredDaemonServiceOpenMeldProfileId(input: {\n openMeldProfileId?: unknown;\n profile?: unknown;\n}): string | null {\n const openMeldProfileId = parseNullableString(input.openMeldProfileId);\n const legacyProfile = parseNullableString(input.profile);\n if (\n openMeldProfileId &&\n legacyProfile &&\n openMeldProfileId !== legacyProfile\n ) {\n throw new Error(\"conflicting openMeldProfileId values\");\n }\n return openMeldProfileId ?? legacyProfile;\n}\n\nexport function isDaemonServiceRuntimeHeartbeatStale(\n state: DaemonServiceRuntimeState\n): boolean {\n const latestSignalAt = Math.max(\n parseIsoTimestampOrZero(state.heartbeatAt),\n parseIsoTimestampOrZero(state.updatedAt)\n );\n if (latestSignalAt <= 0) {\n return false;\n }\n return Date.now() - latestSignalAt > DAEMON_HEARTBEAT_STALE_MS;\n}\n\nfunction parseIsoTimestampOrZero(value: string | null): number {\n if (!value) {\n return 0;\n }\n const parsed = Date.parse(value);\n return Number.isFinite(parsed) ? parsed : 0;\n}\n\nasync function writeDaemonServiceRuntimeState(\n state: DaemonServiceRuntimeState,\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<void> {\n const path = daemonServiceRuntimeStatePath(pathInput);\n const runtimeRootPath = daemonRuntimeRootPath(pathInput);\n await mkdir(runtimeRootPath, { recursive: true });\n const tempPath = `${path}.tmp-${process.pid}-${Date.now()}`;\n let shouldCleanupTemp = true;\n\n try {\n await writeFile(tempPath, `${JSON.stringify(state, null, 2)}\\n`, {\n encoding: \"utf8\",\n mode: 0o600,\n });\n await rename(tempPath, path);\n await chmod(path, 0o600);\n shouldCleanupTemp = false;\n } finally {\n if (shouldCleanupTemp) {\n await rm(tempPath, { force: true }).catch(() => undefined);\n }\n }\n}\n\nasync function ensureDaemonRuntimeLayout(): Promise<void> {\n await Promise.all([\n mkdir(systemDir(), { recursive: true }),\n mkdir(join(daemonRuntimeRootPath(), \"bin\"), { recursive: true }),\n mkdir(daemonRuntimeBundlesPath(), { recursive: true }),\n mkdir(join(daemonRuntimeRootPath(), \"data\"), { recursive: true }),\n mkdir(join(daemonRuntimeRootPath(), \"logs\"), { recursive: true }),\n mkdir(daemonRuntimeStateRootPath(), { recursive: true }),\n mkdir(daemonRuntimeServiceManagerPath(), { recursive: true }),\n ]);\n}\n\nfunction normalizeDaemonLifecycleIntent(\n value: string\n): DaemonLifecycleIntent | null {\n switch (value) {\n case \"run_background\":\n case \"run_foreground\":\n case \"stop\":\n case \"autostart\":\n case \"status_cleanup\":\n case \"startup_check\":\n case \"start\":\n case \"reinstall\":\n case \"uninstall\":\n case \"upgrade_reconcile\":\n return value;\n default:\n return null;\n }\n}\n\nasync function ensureDaemonTokenState(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<DaemonTokenState> {\n const current = await readDaemonTokenState(pathInput);\n if (current) {\n await chmod(daemonTokenPath(pathInput), 0o600).catch(() => undefined);\n return current;\n }\n\n return await writeNewDaemonTokenState(pathInput);\n}\n\nasync function writeNewDaemonTokenState(\n pathInput: OpenMeldPathResolutionInput\n): Promise<DaemonTokenState> {\n const nowIso = new Date().toISOString();\n const next: DaemonTokenState = {\n v: 1,\n schema: DAEMON_TOKEN_SCHEMA,\n token: createDaemonTokenValue(),\n issuedAt: nowIso,\n updatedAt: nowIso,\n };\n await writeDaemonTokenState(next, pathInput);\n return next;\n}\n\nasync function readDaemonInstallState(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<DaemonInstallState | null> {\n const raw = await readFile(daemonStatePath(pathInput), \"utf8\").catch(\n (error) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\n return null;\n }\n throw error;\n }\n );\n if (raw === null) {\n return null;\n }\n return parseDaemonInstallState(raw);\n}\n\nfunction parseDaemonInstallState(raw: string): DaemonInstallState | null {\n try {\n const parsed = JSON.parse(raw) as Partial<DaemonInstallState>;\n if (parsed.v !== 1) {\n return null;\n }\n if (parsed.schema !== DAEMON_STATE_SCHEMA) {\n return null;\n }\n if (typeof parsed.daemonVersion !== \"string\" || !parsed.daemonVersion) {\n return null;\n }\n if (!isDaemonInstallSource(parsed.installSource)) {\n return null;\n }\n if (typeof parsed.installedAt !== \"string\" || !parsed.installedAt) {\n return null;\n }\n if (typeof parsed.updatedAt !== \"string\" || !parsed.updatedAt) {\n return null;\n }\n return {\n v: 1,\n schema: DAEMON_STATE_SCHEMA,\n daemonVersion: parsed.daemonVersion,\n installSource: parsed.installSource,\n installedAt: parsed.installedAt,\n updatedAt: parsed.updatedAt,\n };\n } catch {\n return null;\n }\n}\n\nfunction isDaemonInstallSource(value: unknown): value is DaemonInstallSource {\n return value === \"cli.auto_check\" || value === \"daemon.command.install\";\n}\n\nasync function writeDaemonInstallState(\n state: DaemonInstallState,\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<void> {\n const path = daemonStatePath(pathInput);\n await mkdir(systemDir(pathInput), { recursive: true });\n const tempPath = `${path}.tmp-${process.pid}-${Date.now()}`;\n let shouldCleanupTemp = true;\n\n try {\n await writeFile(tempPath, `${JSON.stringify(state, null, 2)}\\n`, \"utf8\");\n await rename(tempPath, path);\n shouldCleanupTemp = false;\n } finally {\n if (shouldCleanupTemp) {\n await rm(tempPath, { force: true }).catch(() => undefined);\n }\n }\n}\n\nasync function readDaemonTokenState(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<DaemonTokenState | null> {\n const raw = await readFile(daemonTokenPath(pathInput), \"utf8\").catch(\n (error) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\n return null;\n }\n throw error;\n }\n );\n if (raw === null) {\n return null;\n }\n return parseDaemonTokenState(raw);\n}\n\nfunction parseDaemonTokenState(raw: string): DaemonTokenState | null {\n try {\n const parsed = JSON.parse(raw) as Partial<DaemonTokenState>;\n if (parsed.v !== 1 || parsed.schema !== DAEMON_TOKEN_SCHEMA) {\n return null;\n }\n if (typeof parsed.token !== \"string\" || parsed.token.length < 16) {\n return null;\n }\n if (typeof parsed.issuedAt !== \"string\" || !parsed.issuedAt) {\n return null;\n }\n if (typeof parsed.updatedAt !== \"string\" || !parsed.updatedAt) {\n return null;\n }\n return {\n v: 1,\n schema: DAEMON_TOKEN_SCHEMA,\n token: parsed.token,\n issuedAt: parsed.issuedAt,\n updatedAt: parsed.updatedAt,\n };\n } catch {\n return null;\n }\n}\n\nasync function writeDaemonTokenState(\n state: DaemonTokenState,\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<void> {\n const path = daemonTokenPath(pathInput);\n await mkdir(systemDir(pathInput), { recursive: true });\n const tempPath = `${path}.tmp-${process.pid}-${Date.now()}`;\n let shouldCleanupTemp = true;\n\n try {\n await writeFile(tempPath, `${JSON.stringify(state, null, 2)}\\n`, {\n encoding: \"utf8\",\n mode: 0o600,\n });\n await rename(tempPath, path);\n await chmod(path, 0o600);\n shouldCleanupTemp = false;\n } finally {\n if (shouldCleanupTemp) {\n await rm(tempPath, { force: true }).catch(() => undefined);\n }\n }\n}\n\nfunction isDaemonTokenExpired(state: DaemonTokenState): boolean {\n const updatedAtMs = Date.parse(state.updatedAt);\n if (!Number.isFinite(updatedAtMs)) {\n return true;\n }\n return Date.now() - updatedAtMs >= DAEMON_TOKEN_ROTATE_MAX_AGE_MS;\n}\n\nfunction createDaemonTokenValue(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\n return false;\n }\n throw error;\n }\n}\n","import { rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { daemonRuntimeLeaseSchema } from \"@openmeld/schemas\";\nimport type { DaemonRuntimeLease } from \"@openmeld/schemas/types\";\nimport {\n readDaemonLocalStateFile,\n writeDaemonLocalStateFile,\n} from \"./daemon-local-state-file\";\nimport { daemonRuntimeStateRootPath } from \"./daemon-state\";\nimport type { OpenMeldPathResolutionInput } from \"./paths\";\n\nconst DAEMON_RUNTIME_LEASE_FILENAME = \"runtime-lease.json\";\n\nexport function daemonRuntimeLeasePath(\n pathInput: OpenMeldPathResolutionInput = {}\n): string {\n return join(\n daemonRuntimeStateRootPath(pathInput),\n DAEMON_RUNTIME_LEASE_FILENAME\n );\n}\n\nexport async function readDaemonRuntimeLease(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<DaemonRuntimeLease | null> {\n return await readDaemonLocalStateFile({\n path: daemonRuntimeLeasePath(pathInput),\n schema: daemonRuntimeLeaseSchema,\n });\n}\n\nexport async function writeDaemonRuntimeLease(\n lease: DaemonRuntimeLease,\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<void> {\n await writeDaemonLocalStateFile({\n path: daemonRuntimeLeasePath(pathInput),\n schema: daemonRuntimeLeaseSchema,\n value: lease,\n mode: 0o600,\n });\n}\n\nexport async function clearDaemonRuntimeLease(\n pathInput: OpenMeldPathResolutionInput = {}\n): Promise<void> {\n await rm(daemonRuntimeLeasePath(pathInput), { force: true });\n}\n"],"mappings":";;;;;;;;;;;AAIA,MAAM,+BAA+B,IAAI,KAAK,CAAC,cAAc,YAAY,CAAC;AAC1E,MAAM,2BAA2B,IAAI,aAAa;CACjD,QAAQ,IAAI,QAAQ,kCAAkC;CACtD,GAAG,IAAI,QAAQ,CAAC;CAChB,YAAY,IAAI,IAAI,CAAC,CAAC,YAAY;CAClC,UAAU,IAAI,OAAO,CAAC,CAAC,IAAI,CAAC;CAC5B,KAAK,IAAI,IAAI,CAAC,CAAC,SAAS;CACxB,MAAM;CACN,WAAW,IAAI,OAAO,CAAC,CAAC,IAAI,CAAC;CAC7B,WAAW,IAAI,OAAO,CAAC,CAAC,IAAI,CAAC;CAC7B,aAAa,IAAI,OAAO,CAAC,CAAC,SAAS;CACnC,mBAAmB;CACnB,wBAAwB,IAAI,QAAQ;AACrC,CAAC;;;ACDD,eAAsB,yBAA4B,OAG5B;CACpB,MAAM,MAAM,MAAM,SAAS,MAAM,MAAM,MAAM,CAAC,CAAC,OAAO,UAAU;EAC9D,IACE,SACA,OAAO,UAAU,YACjB,UAAU,SACV,MAAM,SAAS,UAEf,OAAO;EAET,MAAM;CACR,CAAC;CACD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S,WAAW;AAC7C;AAEA,eAAe,WAAW,MAAgC;CACxD,IAAI;EACF,MAAM,KAAK,IAAI;EACf,OAAO;CACT,SAAS,OAAO;EACd,IACE,SACA,OAAO,UAAU,YACjB,UAAU,SACV,MAAM,SAAS,UAEf,OAAO;EAET,MAAM;CACR;AACF;;;;;;;;;AC5sCA,MAAM,gCAAgC;AAEtC,SAAgB,uBACd,YAAyC,CAAC,GAClC;CACR,OAAO,KACL,2BAA2B,SAAS,GACpC,6BACF;AACF;AAEA,eAAsB,uBACpB,YAAyC,CAAC,GACN;CACpC,OAAO,MAAM,yBAAyB;EACpC,MAAM,uBAAuB,SAAS;EACtC,QAAQ;CACV,CAAC;AACH;AAEA,eAAsB,wBACpB,OACA,YAAyC,CAAC,GAC3B;CACf,MAAM,0BAA0B;EAC9B,MAAM,uBAAuB,SAAS;EACtC,QAAQ;EACR,OAAO;EACP,MAAM;CACR,CAAC;AACH;AAEA,eAAsB,wBACpB,YAAyC,CAAC,GAC3B;CACf,MAAM,GAAG,uBAAuB,SAAS,GAAG,EAAE,OAAO,KAAK,CAAC;AAC7D"}
Binary file
package/dist/openmeld.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { $ as runWithHeldLock, A as toSpaceContractUrl, At as openMeldBackupsDir, D as normalizeBaseUrl, E as updateConfiguredStartV1OnboardingState, F as toSpaceDispatchTraceUrl, Ft as openMeldRootDir, G as buildOpenMeldOrphanedLockAction, Gt as resolveOpenMeldRootDir, Ht as resolveOpenMeldCliEntryNameFromArgv, Jt as skillsDir, K as isOpenMeldLockError, Lt as organizationSkillReleaseDir, Mt as openMeldManagedBinaryPath, Nt as openMeldManagedVersionBinaryPath, Ot as normalizeAccountKey, P as toSpaceDispatchLookupUrl, Q as resolveOpenMeldOrphanedLockIssue, Rt as profileDir, S as setConfiguredSkillsConfig, St as accountsDir, Ut as resolveOpenMeldEnvPreset, V as toSpaceResultUrl, W as acquireLock, X as releaseLockSync, Xt as systemDir, Yt as spacesDir, Z as repairOrphanedLegacyLocks, Zt as formatLocalMachineIssueMessage, a as resolveBaseUrl, at as resolveCliContext, b as setConfiguredBaseUrl, bt as accountProfileViewPath, c as resolveExplicitGatewayUrlOrThrow, ct as formatLaneScopeSentence, ft as createActiveSetupConcurrencyIssue, g as getConfiguredSkillsConfig, gt as toRecognizedLocalMachineFailureError, ht as isLocalMachineFailureError, in as agentControllerConversationRefSchema, k as toSpaceBoardUrl, lt as resolveOpenMeldLaneDescriptor, m as getConfiguredOnboardingDisclaimerAcceptedAt, mt as createOrphanedSetupConcurrencyIssue, nt as OPENMELD_CLI_CONTEXT_ENV_KEY, o as resolveBaseUrlOrNull, q as isOpenMeldOrphanedLockError, tt as LEGACY_OPENMELD_AGENT_SESSION_ENV_KEY, u as alignRuntimeConfigStorage, ut as LocalMachineFailureError, w as updateConfiguredOnboardingConfig, yt as accountProfileSpaceCacheDir, zt as profileViewPath } from "./base-url-PkgATS5u.js";
4
- import { $ as runAgentsRepair, $a as defaultManagedIntegrationPaths, $i as readDaemonServiceJobCrashExitCode, $n as formatDaemonServiceMissingRecommendation, $r as resolveOpenClawLocalDiagnosticsValue, $t as readBundledOpenMeldCliSkillDocumentByPath, A as assertFullSignalIdArgument, Aa as resolveOpenMeldProfile, Ai as resolveNativeAgentControllerPermissionModeForController, An as upsertSpaceConfig, Ao as runIfAgentActivityBindingGenerationIsCurrent, Ar as DualViewGuideError, At as shouldEmitAgentOverview, B as persistAgentTransportSelection, Ba as resolveAuthenticationGuidanceFromError, Bi as assessServerRequiredVersion, Bn as promptSearchMultiselect, Bo as errLine, Br as runPendingDaemonServiceUpdate, Bt as parseJsonResponse, C as toSpaceMetaUpsertInput, Ca as requireOpenMeldProfile, Ci as getAgentControllerPermissionModeFieldLabel, Cn as submitRuntimeAgentControllerReport, Co as readAgentActivityOutboxHealth, Cr as SPACE_ADD_MEMBERS_PROGRESS_HEARTBEAT_MS, Ct as runDaemonTeardownStrict, D as formatHumanReadTargetList, Da as deleteOpenMeldProfile, Di as resolveAgentExecutionStatus, Dn as resolveLocalAgentControllerLaunchability, Do as listProjectConnectionsWithStatus, Dr as registerAuthLoginRequestOptions, Dt as reconcileCliVersionView, E as buildHumanReplyContextSummary, Ea as createOpenMeldHumanProfile, Ei as resolveAgentControllerPermissionModeForController, En as resolveLocalAgentControllerBlockerReasonCodes, Eo as listProjectBindings, Er as registerDaemonControlTargetOptions, Et as buildProfileWorkspaceRows, F as emitSpaceAgentOverview, Fa as setSelectedOpenMeldProfileId, Fi as buildDaemonServiceTargetSpec, Fn as buildSignalMessageReadProjection, Fo as readControllerTaskLifecycleOutboxHealth, Fr as SPACE_CONTRACT_ALLOWED_ACTION_ORDER, Ft as fetchSpaceMeta, G as runAgentsCustomList, Ga as validateLocalProjectConnectionPath, Gi as resetCurrentCommandCheckState, Gn as isCliUpdateCheckApplicable, Go as cliJsonSkillsListEnvelopeSchema, Gr as resolveServiceReadinessFromServiceStatus, Gt as runDaemonStartDecisionPrompt, H as runAgents, Ha as getProfileDefaultView, Hi as finishCurrentCommandCheckScope, Hn as isReturnKeypress, Ho as outLine, Hr as ensureDaemonRuntimePaths, Ht as writeInstalledLocalComponentsSnapshot, I as emitSpaceCliAgentOverview, Ia as buildAgentAuthenticationGuide, Ii as resolveDaemonServiceAlignmentDecision, In as buildSpaceRoundReadProjection, Io as renderInfoCard, Ir as areAllowedActionsEquivalent, It as updateSpaceMeta, J as runAgentsDetect, Ja as isAgentActivityRouteRegistered, Ji as resolveVersionChangeDirection, Jn as readDispatchSpaceActionContextFromEnv, Jo as getOrganizationJoinLinkResponseSchema, Jr as formatAgentReplyReadinessLabel, Jt as runSkillsEnsure, K as runAgentsCustomRemove, Ka as LocalDaemonControlPlaneClientError, Ki as startCurrentCommandCheckScope, Kn as assertDispatchOwnedRuntimePublicWriteAllowed, Ko as cliJsonSkillsLoadEnvelopeSchema, Kr as resolveDaemonServiceFreshnessWarning, Kt as collectSkillsReadinessSnapshot, L as prepareLocalAgentReadiness, La as buildHumanAuthenticationCard, Li as classifyDaemonServiceRunStartability, Ln as buildUpdatesReplyWorkflowProjection, Lo as renderTextInfoCard, Lr as buildAgentFacingPublicationModeGuideLines, Lt as readGatewayJsonResponse, M as prepareAuthenticatedSpaceCommandContext, Ma as alignSelectedOpenMeldProfileStorage, Mi as buildDaemonRouteObservationPresentation$1, Mn as buildDispatchResultMessageReadProjection, Mo as unbindProject, Mr as buildDualViewGuideMessage, Mt as readDaemonStartFailureLogTailLines, N as resolveOpenMeldProfileForSpaceCommand, Na as clearSelectedOpenMeldProfileId, Ni as buildOnboardingPlan, Nn as buildDispatchResultReplyWorkflowProjection, No as canonicalizeLocalProjectPath, Nr as formatAgentOverviewPayload, Nt as fetchSpaceUpdates, O as parseEnvelope, Oa as listOpenMeldProfiles, Oi as resolveAgentProfileEditCapabilities, On as resolveLocalAgentControllerReportDecision, Oo as migrateProjectBindingStore, Or as registerBuiltinAgentSelectionOptions, Ot as emitDaemonAgentOverview, P as resolveSpaceAccessLabel, Pa as getSelectedOpenMeldProfileId, Pi as getSetupFlowCopy, Pn as buildSignalIndex, Po as enqueueControllerTaskLifecycleEventWhileLocked, Pr as OPENMELD_AGENT_MENTAL_MODEL_LINES, Pt as createCliSpaceApi, Q as runAgentsManage, Qi as isDaemonServiceJobNeverSpawned, Qn as formatDaemonServiceDowngradeBlockedRecommendation, Qr as resolveGatewayChainReadiness, Qt as ensureLocalSkills, R as buildReplyReadinessGuidance, Ra as createAuthenticationError, Ri as classifyDaemonServiceWakeability, Rn as createSpaceMemberIdentityIndex, Ro as sanitizeTerminalDisplayText, Rr as canonicalizeAllowedActions, Rt as readGatewayTextResponse, S as loadSpaceSignalIndexOrNull, Sa as isSelectedOpenMeldProfileRequiredError, Si as getAgentControllerPermissionModeDisplayMetadata, Sn as submitProfileRuntimeAgentControllerReport, So as removeProjectInbox, Sr as registerSpaceMemberSelectionOptions, St as runDaemonStop, T as buildFormalSignalReadPayload, Ta as createOpenMeldAgentProfile, Ti as parseAgentControllerRef, Tn as collectLocalAgentControllerInventory, To as bindProject, Tr as getCliVersionInfo, Tt as buildProfileWorkspacePresentation, U as runAgentsConfig, Ua as setProfileDefaultView, Ui as getCurrentCommandCheckState, Un as runInteractivePrompt, Uo as cliBinaryDeltaPatchSchema, Ur as resolveDaemonDeviceId, Ut as resolveDaemonServiceParticipationStatus, V as resolveAgentProfileSetup, Va as resolveAuthenticationGuidanceFromMessage, Vi as resolveOpenMeldEnvironmentTarget, Vn as promptSearchSelect, Vo as outJsonLine, Vr as scheduleDaemonServiceUpdate, Vt as resolveLocalComponentsStatus, W as runAgentsCustomAdd, Wa as LocalProjectConnectionError, Wi as isCurrentCommandCheckScopeActive, Wn as assessCliUpdate, Wo as cliJsonOutputEnvelopeSchema, Wr as formatDaemonFailureContextText, Wt as runDaemonServiceParticipationGate, X as runAgentsEnable, Xa as resolveAgentActivityRouteForPath, Xi as readCurrentObservedDaemonRuntimeStatus, Xn as formatElapsedTime, Xo as revokeOrganizationJoinLinkResponseSchema, Xr as formatHumanReplyReadinessReason$1, Xt as runSkillsUninstall, Y as runAgentsDisable, Ya as registerAgentActivityRoute, Yi as readCurrentDaemonRuntimeContext, Yn as writeDispatchSpaceActionRecord, Yo as organizationJoinLinkErrorResponseSchema, Yr as formatDeviceReplyReadinessLabel, Yt as runSkillsInstall, Z as runAgentsList, Za as unregisterAgentActivityRoute, Zi as getDaemonSystemServiceLogPath, Zn as resolveElapsedTimeMs, Zo as compareAgentControllerRefsForDisplay, Zr as mapAgentReplyReadinessToLegacyAutoReply, Zt as runSkillsUpdate, _ as runSpaceWriteWithPasswordRetry, _a as createPresenter, _i as listBuiltinAgentsRegistryEntries, _n as ensureAgentProfileRuntimeBinding, _o as buildAgentActivityEvent, _r as createStartAgentIdentityGuideError, _t as runDaemonInterrupt, a as runSpaceDelete, aa as ensureVersionStateReady, ai as normalizeCustomProfileWorkspacePath, an as evaluateCommandAuthentication, ao as formatOpenMeldCliCommand, ar as createResetConfirmationGuideError, at as printOpenMeldBanner, b as buildIdentityOnlyMembersSnapshotForReadProjection, ba as resolveRuntimeContext, bi as buildAgentControllerRef, bn as assessActionParticipationCandidate, bo as readCodexSessionTitles, br as getCommandEntryContract, bt as runDaemonSnapshot, c as runSpaceLeave, ca as readVersionState, ci as setCustomProfileWorkspace, cn as runAuthMenu, co as formatOpenMeldCliTextBlock, cr as createSpaceContractSetGuideError, ct as renderOpenMeldLogo, d as runSpaceRemoveMembers, da as toStartBackgroundHelperExecutionCompatibility, di as describeProfileWorkspacePathValidationFailure, dn as buildAuthStatusSnapshot, do as resolveUserFacingCliEntryCommand, dr as createSpacePublicationSetGuideError, dt as resolveSpaceSendText, ea as resolveDaemonServiceManager, ei as readRecentDaemonLifecycleEvents, en as readRuntimeReportingHealthState, eo as installAgentActivityIntegrations, er as canUseInteractivePrompts, et as runAgentsShow, f as runSpaceSend, fa as resolveCurrentDaemonExpectedVersion, fi as syncDeviceRuntimeStateProjection, fn as formatActiveOrganizationLabel, fo as syncLocalAgentActivity, fr as createSpaceRemoveMembersGuideError, ft as runDaemon, g as runSpaceReadWithPasswordRetry, ga as renderHumanTextErrorCard, gi as reconcileNewRunnableBuiltinAgentsForSetup, gn as promptTextEntry, go as removeAgentActivityContextCache, gr as createSpaceUpdatesGuideError, gt as runDaemonInstall, h as uploadPreparedSpaceFiles, ha as renderHumanErrorCard, hi as listAgentTargetStates, hn as resolveCreateProfileName, ho as readAgentActivityContextForPath, hr as createSpaceTargetGuideError, ht as runDaemonCancel, i as runSpaceCreate, ia as compareSemver, ii as ensureOpenMeldManagedProfileWorkspace, in as ensureCommandAuthenticationOrCancel, io as formatInlineOpenMeldCliCommands, ir as createProfileMenuGuideError, it as colorizeDisplayProfileLabel, j as assertValidSpaceIdTarget, ja as updateOpenMeldProfile, jn as assertNoRemovedCcSpaceAddressingSyntax, jo as setDefaultProjectConnection, jr as formatDualViewGuideForDisplay, jt as runDaemonStartupPreflight, k as isSpaceCommandOutputHandledError, ka as primeOpenMeldProfilesSessionCache, ki as resolveEvidenceSyncHealth, kn as inspectSpaceCacheFile, ko as removeProjectConnection, kr as buildAgentOverviewFromContract, kt as createDelayedSpinner, l as runSpaceList, la as writeVersionState, li as setOpenMeldManagedProfileWorkspace, ln as runAuthStatus, lo as formatProfileAwareOpenMeldCliCommands, lr as createSpaceLeaveGuideError, lt as renderOpenMeldTagline, m as prepareRequestedSpaceSendFiles, ma as buildHumanErrorCopy, mi as resolveAgentProfilePrimaryAgentControllerReport, mn as resolveCreateProfileKind, mo as upsertDaemonServiceContract, mr as createSpaceSubcommandTargetGuideError, mt as runDaemonBackgroundStartForDecision, n as promptAndConfirmSpacePassword, na as performManagedInstall, ni as createModelCatalogReadSession, nn as connectWebSocket, no as resolveAgentActivityDispatcherCommand, nr as createProfileActionGuideError, nt as postLocalParticipationMutationReconcile, o as runSpaceHistory, oa as fetchLatestCliBinaryRelease, oi as readProfileWorkspaceConfig, on as runAuthLogin, oo as formatOpenMeldCliCommands, or as createSpaceAddMembersGuideError, ot as renderOpenMeldBrandBlockLines, p as runSpaceWatch, pa as OPENMELD_VERSION, pi as createPrimaryBindingReadSession, pn as createProfileByKind, po as readDaemonServiceContract, pr as createSpaceResultGuideError, pt as runDaemonAutostart, q as runAgentsCustomUpdate, qa as requestLocalAgentActivitySync, qi as inspectDaemonServiceInventory, qn as readDispatchOwnedRuntimeGuard, qo as cliJsonSkillsShowEnvelopeSchema, qr as resolveCurrentReplyReadinessSnapshot, qt as runSkillsCheck$1, r as runSpaceAddMembers, ra as buildNextVersionState, ri as resolveProfileWorkspaceRuntime, rn as buildCommandAuthenticationPromptMessage, ro as uninstallAgentActivityIntegrations, rr as createProfileCreateGuideError, rt as colorizeAgentLabel, s as runSpaceJoin, sa as fetchLatestPackageInfo, si as resolveConfiguredProfileWorkspacePath, sn as runAuthLogout, so as formatOpenMeldCliLine, sr as createSpaceAliasTargetGuideError, st as renderOpenMeldHeader, t as buildCreateSpacePasswordPromptConfig, ta as buildInstallSelfJsonPayload, ti as syncProfileWorkspaceState, tn as readRecentDaemonDispatchJournalEvents, to as readAgentActivityIntegrationStatus, tr as createDoctorFailedGuideError, tt as formatTransportModeDisplay, u as runSpacePassword, ua as resolveDaemonRuntimeContractCompatibility, ui as validateCustomProfileWorkspacePath, un as buildAuthStatusRows, uo as resolveSetupFollowUpCliEntryCommand, ur as createSpaceMenuGuideError, ut as resolveGatewayWebOrigin, v as buildHumanReadSignalsTranscriptItems, va as formatMessage, vi as notifyDaemonRouteCatalogChanged, vn as formatServiceParticipationReadinessLabel, vo as resolveObservedAgentActivityBinding, vr as createStartAuthenticationGuideError, vt as runDaemonReinstall, w as buildFormalDispatchResultReadPayload, wa as resolveOpenMeldProfileOrNull, wi as listAgentControllerPermissionModeOptions, wn as submitRuntimeAgentControllerReports, wo as removeProjectOutbox, wr as registerSkillsTargetSelectionOptions, wt as runDaemonUninstall, x as loadSpaceIdentityDirectoryOrNull, xa as resolveViewProfileKey, xi as createAgentExecutionStatusDisplayRows, xn as computeRetryDelayMs, xo as enqueueAgentActivityHookEvent, xr as getCommandHintsFromContract, xt as runDaemonStatusFlow, y as emitHumanReadSignalsTextProjection, ya as parseCliViewMode, yi as resolveLocalRegistryAgentIdFromAgentControllerRef, yn as resolveServiceParticipationReadiness, yo as normalizeSharedSessionTitle, yr as createUpgradeConfirmationGuideError, yt as runDaemonRunAfterEntryChecks, z as resolveHumanControllerDisplayName, za as resolveAuthenticationGuidance, zi as resolveServiceUpdateUrgency, zn as formatRemovedCcRelationMessage, zo as emitCliJsonEnvelope, zr as readOpenMeldToolsUpdateContextFromEnv, zt as toStructuredGatewayFailure } from "./command-D_BRRxBQ.js";
4
+ import { $ as runAgentsRepair, $a as installAgentActivityIntegrations, $i as readRecentDaemonLifecycleEvents, $n as canUseInteractivePrompts, $r as syncProfileWorkspaceState, $t as readRuntimeReportingHealthState, A as assertFullSignalIdArgument, Aa as updateOpenMeldProfile, Ai as buildDaemonRouteObservationPresentation$1, An as assertNoRemovedCcSpaceAddressingSyntax, Ao as setDefaultProjectConnection, Ar as formatDualViewGuideForDisplay, At as runDaemonStartupPreflight, B as persistAgentTransportSelection, Ba as resolveAuthenticationGuidanceFromMessage, Bi as finishCurrentCommandCheckScope, Bn as promptSearchSelect, Bo as outJsonLine, Br as scheduleDaemonServiceUpdate, Bt as resolveLocalComponentsStatus, C as toSpaceMetaUpsertInput, Ca as resolveOpenMeldProfileOrNull, Ci as parseAgentControllerRef, Cn as submitRuntimeAgentControllerReports, Co as removeProjectOutbox, Cr as registerSkillsTargetSelectionOptions, Ct as runDaemonUninstall, D as formatHumanReadTargetList, Da as listOpenMeldProfiles, Di as resolveEvidenceSyncHealth, Dn as resolveLocalAgentControllerReportDecision, Do as migrateProjectBindingStore, Dr as registerBuiltinAgentSelectionOptions, Dt as emitDaemonAgentOverview, E as buildHumanReplyContextSummary, Ea as deleteOpenMeldProfile, Ei as resolveAgentProfileEditCapabilities, En as resolveLocalAgentControllerLaunchability, Eo as listProjectConnectionsWithStatus, Er as registerAuthLoginRequestOptions, Et as reconcileCliVersionView, F as emitSpaceAgentOverview, Fa as buildAgentAuthenticationGuide, Fi as classifyDaemonServiceRunStartability, Fn as buildSpaceRoundReadProjection, Fo as renderInfoCard, Fr as areAllowedActionsEquivalent, Ft as updateSpaceMeta, G as runAgentsCustomList, Ga as LocalDaemonControlPlaneClientError, Gi as inspectDaemonServiceInventory, Gn as assertDispatchOwnedRuntimePublicWriteAllowed, Go as cliJsonSkillsLoadEnvelopeSchema, Gr as resolveDaemonServiceFreshnessWarning, Gt as collectSkillsReadinessSnapshot, H as runAgents, Ha as setProfileDefaultView, Hi as isCurrentCommandCheckScopeActive, Hn as runInteractivePrompt, Ho as cliBinaryDeltaPatchSchema, Hr as resolveDaemonDeviceId, Ht as resolveDaemonServiceParticipationStatus, I as emitSpaceCliAgentOverview, Ia as buildHumanAuthenticationCard, Ii as classifyDaemonServiceWakeability, In as buildUpdatesReplyWorkflowProjection, Io as renderTextInfoCard, Ir as buildAgentFacingPublicationModeGuideLines, It as readGatewayJsonResponse, J as runAgentsDetect, Ja as registerAgentActivityRoute, Ji as readCurrentObservedDaemonRuntimeStatus, Jn as writeDispatchSpaceActionRecord, Jo as organizationJoinLinkErrorResponseSchema, Jr as formatDeviceReplyReadinessLabel, Jt as runSkillsInstall, K as runAgentsCustomRemove, Ka as requestLocalAgentActivitySync, Ki as resolveVersionChangeDirection, Kn as readDispatchOwnedRuntimeGuard, Ko as cliJsonSkillsShowEnvelopeSchema, Kr as resolveCurrentReplyReadinessSnapshot, Kt as runSkillsCheck$1, L as prepareLocalAgentReadiness, La as createAuthenticationError, Li as resolveServiceUpdateUrgency, Ln as createSpaceMemberIdentityIndex, Lo as sanitizeTerminalDisplayText, Lr as canonicalizeAllowedActions, Lt as readGatewayTextResponse, M as prepareAuthenticatedSpaceCommandContext, Ma as clearSelectedOpenMeldProfileId, Mi as getSetupFlowCopy, Mn as buildDispatchResultReplyWorkflowProjection, Mo as canonicalizeLocalProjectPath, Mr as formatAgentOverviewPayload, Mt as fetchSpaceUpdates, N as resolveOpenMeldProfileForSpaceCommand, Na as getSelectedOpenMeldProfileId, Ni as buildDaemonServiceTargetSpec, Nn as buildSignalIndex, No as enqueueControllerTaskLifecycleEventWhileLocked, Nr as OPENMELD_AGENT_MENTAL_MODEL_LINES, Nt as createCliSpaceApi, O as parseEnvelope, Oa as primeOpenMeldProfilesSessionCache, Oi as resolveNativeAgentControllerPermissionModeForController, On as inspectSpaceCacheFile, Oo as removeProjectConnection, Or as buildAgentOverviewFromContract, Ot as createDelayedSpinner, P as resolveSpaceAccessLabel, Pa as setSelectedOpenMeldProfileId, Pi as resolveDaemonServiceAlignmentDecision, Pn as buildSignalMessageReadProjection, Po as readControllerTaskLifecycleOutboxHealth, Pr as SPACE_CONTRACT_ALLOWED_ACTION_ORDER, Pt as fetchSpaceMeta, Q as runAgentsManage, Qa as defaultManagedIntegrationPaths, Qi as resolveDaemonServiceManager, Qn as formatDaemonServiceMissingRecommendation, Qr as resolveOpenClawLocalDiagnosticsValue, Qt as readBundledOpenMeldCliSkillDocumentByPath, R as buildReplyReadinessGuidance, Ra as resolveAuthenticationGuidance, Ri as assessServerRequiredVersion, Rn as formatRemovedCcRelationMessage, Ro as emitCliJsonEnvelope, Rr as readOpenMeldToolsUpdateContextFromEnv, Rt as toStructuredGatewayFailure, S as loadSpaceSignalIndexOrNull, Sa as requireOpenMeldProfile, Si as listAgentControllerPermissionModeOptions, Sn as submitRuntimeAgentControllerReport, So as readAgentActivityOutboxHealth, Sr as SPACE_ADD_MEMBERS_PROGRESS_HEARTBEAT_MS, St as runDaemonTeardownStrict, T as buildFormalSignalReadPayload, Ta as createOpenMeldHumanProfile, Ti as resolveAgentExecutionStatus, Tn as resolveLocalAgentControllerBlockerReasonCodes, To as listProjectBindings, Tr as registerDaemonControlTargetOptions, Tt as buildProfileWorkspaceRows, U as runAgentsConfig, Ua as LocalProjectConnectionError, Ui as resetCurrentCommandCheckState, Un as assessCliUpdate, Uo as cliJsonOutputEnvelopeSchema, Ur as formatDaemonFailureContextText, Ut as runDaemonServiceParticipationGate, V as resolveAgentProfileSetup, Va as getProfileDefaultView, Vi as getCurrentCommandCheckState, Vn as isReturnKeypress, Vo as outLine, Vr as ensureDaemonRuntimePaths, Vt as writeInstalledLocalComponentsSnapshot, W as runAgentsCustomAdd, Wa as validateLocalProjectConnectionPath, Wi as startCurrentCommandCheckScope, Wn as isCliUpdateCheckApplicable, Wo as cliJsonSkillsListEnvelopeSchema, Wr as resolveServiceReadinessFromServiceStatus, Wt as runDaemonStartDecisionPrompt, X as runAgentsEnable, Xa as unregisterAgentActivityRoute, Xi as isDaemonServiceJobNeverSpawned, Xn as resolveElapsedTimeMs, Xo as compareAgentControllerRefsForDisplay, Xr as mapAgentReplyReadinessToLegacyAutoReply, Xt as runSkillsUpdate, Y as runAgentsDisable, Ya as resolveAgentActivityRouteForPath, Yi as getDaemonSystemServiceLogPath, Yn as formatElapsedTime, Yo as revokeOrganizationJoinLinkResponseSchema, Yr as formatHumanReplyReadinessReason$1, Yt as runSkillsUninstall, Z as runAgentsList, Zi as readDaemonServiceJobCrashExitCode, Zn as formatDaemonServiceDowngradeBlockedRecommendation, Zr as resolveGatewayChainReadiness, Zt as ensureLocalSkills, _ as runSpaceWriteWithPasswordRetry, _a as formatMessage, _i as resolveLocalRegistryAgentIdFromAgentControllerRef, _n as formatServiceParticipationReadinessLabel, _o as resolveObservedAgentActivityBinding, _r as createStartAuthenticationGuideError, _t as runDaemonReinstall, a as runSpaceDelete, aa as fetchLatestCliBinaryRelease, ai as resolveConfiguredProfileWorkspacePath, an as runAuthLogin, ao as formatOpenMeldCliCommands, ar as createSpaceAddMembersGuideError, at as renderOpenMeldBrandBlockLines, b as buildIdentityOnlyMembersSnapshotForReadProjection, ba as resolveViewProfileKey, bi as getAgentControllerPermissionModeDisplayMetadata, bn as computeRetryDelayMs, bo as enqueueAgentActivityHookEvent, br as getCommandHintsFromContract, bt as runDaemonStatusFlow, c as runSpaceLeave, ca as writeVersionState, ci as validateCustomProfileWorkspacePath, cn as runAuthStatus, co as formatProfileAwareOpenMeldCliCommands, cr as createSpaceLeaveGuideError, ct as renderOpenMeldTagline, d as runSpaceRemoveMembers, da as resolveCurrentDaemonExpectedVersion, di as createPrimaryBindingReadSession, dn as formatActiveOrganizationLabel, do as syncLocalAgentActivity, dr as createSpaceRemoveMembersGuideError, dt as runDaemon, ea as buildInstallSelfJsonPayload, ei as createModelCatalogReadSession, en as readRecentDaemonDispatchJournalEvents, eo as readAgentActivityIntegrationStatus, er as createDoctorFailedGuideError, et as runAgentsShow, f as runSpaceSend, fa as OPENMELD_VERSION, fi as resolveAgentProfilePrimaryAgentControllerReport, fn as createProfileByKind, fo as readDaemonServiceContract, fr as createSpaceResultGuideError, ft as runDaemonAutostart, g as runSpaceReadWithPasswordRetry, ga as createPresenter, gi as notifyDaemonRouteCatalogChanged, gn as ensureAgentProfileRuntimeBinding, go as buildAgentActivityEvent, gr as createStartAgentIdentityGuideError, gt as runDaemonInterrupt, h as uploadPreparedSpaceFiles, ha as renderHumanTextErrorCard, hi as listBuiltinAgentsRegistryEntries, hn as promptTextEntry, ho as removeAgentActivityContextCache, hr as createSpaceUpdatesGuideError, ht as runDaemonInstall, i as runSpaceCreate, ia as ensureVersionStateReady, ii as readProfileWorkspaceConfig, in as evaluateCommandAuthentication, io as formatOpenMeldCliCommand, ir as createResetConfirmationGuideError, it as printOpenMeldBanner, j as assertValidSpaceIdTarget, ja as alignSelectedOpenMeldProfileStorage, ji as buildOnboardingPlan, jn as buildDispatchResultMessageReadProjection, jo as unbindProject, jr as buildDualViewGuideMessage, jt as readDaemonStartFailureLogTailLines, k as isSpaceCommandOutputHandledError, ka as resolveOpenMeldProfile, kn as upsertSpaceConfig, ko as runIfAgentActivityBindingGenerationIsCurrent, kr as DualViewGuideError, kt as shouldEmitAgentOverview, l as runSpaceList, la as resolveDaemonRuntimeContractCompatibility, li as describeProfileWorkspacePathValidationFailure, ln as buildAuthStatusRows, lo as resolveSetupFollowUpCliEntryCommand, lr as createSpaceMenuGuideError, lt as resolveGatewayWebOrigin, m as prepareRequestedSpaceSendFiles, ma as renderHumanErrorCard, mi as reconcileNewRunnableBuiltinAgentsForSetup, mn as resolveCreateProfileName, mo as readAgentActivityContextForPath, mr as createSpaceTargetGuideError, mt as runDaemonCancel, n as promptAndConfirmSpacePassword, na as buildNextVersionState, ni as ensureOpenMeldManagedProfileWorkspace, nn as buildCommandAuthenticationPromptMessage, no as uninstallAgentActivityIntegrations, nr as createProfileCreateGuideError, nt as colorizeAgentLabel, o as runSpaceHistory, oa as fetchLatestPackageInfo, oi as setCustomProfileWorkspace, on as runAuthLogout, oo as formatOpenMeldCliLine, or as createSpaceAliasTargetGuideError, ot as renderOpenMeldHeader, p as runSpaceWatch, pa as buildHumanErrorCopy, pi as listAgentTargetStates, pn as resolveCreateProfileKind, po as upsertDaemonServiceContract, pr as createSpaceSubcommandTargetGuideError, pt as runDaemonBackgroundStartForDecision, q as runAgentsCustomUpdate, qa as isAgentActivityRouteRegistered, qi as readCurrentDaemonRuntimeContext, qn as readDispatchSpaceActionContextFromEnv, qo as getOrganizationJoinLinkResponseSchema, qr as formatAgentReplyReadinessLabel, qt as runSkillsEnsure, r as runSpaceAddMembers, ra as compareSemver, ri as normalizeCustomProfileWorkspacePath, rn as ensureCommandAuthenticationOrCancel, ro as formatInlineOpenMeldCliCommands, rr as createProfileMenuGuideError, rt as colorizeDisplayProfileLabel, s as runSpaceJoin, sa as readVersionState, si as setOpenMeldManagedProfileWorkspace, sn as runAuthMenu, so as formatOpenMeldCliTextBlock, sr as createSpaceContractSetGuideError, st as renderOpenMeldLogo, t as buildCreateSpacePasswordPromptConfig, ta as performManagedInstall, ti as resolveProfileWorkspaceRuntime, tn as connectWebSocket, to as resolveAgentActivityDispatcherCommand, tr as createProfileActionGuideError, tt as formatTransportModeDisplay, u as runSpacePassword, ua as toStartBackgroundHelperExecutionCompatibility, ui as syncDeviceRuntimeStateProjection, un as buildAuthStatusSnapshot, uo as resolveUserFacingCliEntryCommand, ur as createSpacePublicationSetGuideError, ut as resolveSpaceSendText, v as buildHumanReadSignalsTranscriptItems, va as parseCliViewMode, vi as buildAgentControllerRef, vn as resolveServiceParticipationReadiness, vo as normalizeSharedSessionTitle, vr as createUpgradeConfirmationGuideError, vt as runDaemonRunAfterEntryChecks, w as buildFormalDispatchResultReadPayload, wa as createOpenMeldAgentProfile, wi as resolveAgentControllerPermissionModeForController, wn as collectLocalAgentControllerInventory, wo as bindProject, wr as getCliVersionInfo, wt as buildProfileWorkspacePresentation, x as loadSpaceIdentityDirectoryOrNull, xa as isSelectedOpenMeldProfileRequiredError, xi as getAgentControllerPermissionModeFieldLabel, xn as submitProfileRuntimeAgentControllerReport, xo as removeProjectInbox, xr as registerSpaceMemberSelectionOptions, xt as runDaemonStop, y as emitHumanReadSignalsTextProjection, ya as resolveRuntimeContext, yi as createAgentExecutionStatusDisplayRows, yn as assessActionParticipationCandidate, yo as readCodexSessionTitles, yr as getCommandEntryContract, yt as runDaemonSnapshot, z as resolveHumanControllerDisplayName, za as resolveAuthenticationGuidanceFromError, zi as resolveOpenMeldEnvironmentTarget, zn as promptSearchMultiselect, zo as errLine, zr as runPendingDaemonServiceUpdate, zt as parseJsonResponse } from "./command-Cp18onuk.js";
5
5
  import { $ as ownerComputerDiagnosticsSchema, $t as agentActivityInventorySessionStatusSchema, B as sleep, Bt as agentActivityProviderSchema, Ct as authProfileKindSchema, D as toStructuredApiClientFailure, F as OPENMELD_HEADER_PROFILE_ID, G as projectSpaceDispatchTraceFinalVisibleOutcome, Ht as agentActivitySnapshotQuerySchema, J as spaceDispatchTraceDispatchStatusSchema, K as resolveSpaceDispatchTraceRootCause, Ot as submitFeedbackIssueRequestSchema, Qt as agentActivityInventorySessionOriginSchema, Vt as agentActivitySessionStatusSchema, W as SPACE_DISPATCH_TRACE_RESPONSE_CONTRACT_VERSION_HEADER, X as observabilityWakeTraceSelectorSchema, Y as spaceDispatchTraceResponseSchema, Z as projectObservabilityWakeCorrelation, _ as createOrganizationSkillsApi, b as createProjectsApi, c as createAgentProfileBindingApi, d as createCurrentDeviceApi, dn as START_BOUNDED_ID_SCHEMA, en as agentActivitySessionInventoryQuerySchema, et as projectOwnerComputerLocalRuntimes, f as createFeedbackApi, fn as START_BOUNDED_VERSION_SCHEMA, g as createOrganizationApi, gn as localAgentCatalogSchema, gt as organizationSkillBundleSchema, hn as startReplyReadinessSummarySchema, l as createCenterAgentApi, mn as START_TRIMMED_NON_EMPTY_STRING_SCHEMA, nn as localAgentSessionProviderSchema, nt as DEFAULT_AGENT_PROFILE_CREATION_CONFIGURATION, pn as START_ISO_DATE_TIME_SCHEMA, q as spaceDispatchTraceAttemptStatusSchema, rt as agentProfileCreationConfigurationSchema, s as createAgentActivityApi, tt as summarizeComputerFileAccessPolicy, u as createComputerFileAccessApi, v as createPrepareReadinessApi, wt as authProfileManagedRoleSchema, x as createRoutinesApi, yt as stringifyOrganizationSkillBundleCanonicalJson } from "./dist-DYE9Q3T4.js";
6
6
  import { $n as array, Bt as resolveSpaceFileMimeType, Cr as clientMessageIdSchema, Lt as isSpaceFileTextEditable, Mt as centerAgentInteractionSourceSchema, Wr as openMeldProfileIdSchema, Yr as openMeldRuntimeProfileIdSchema, ar as int, bn as messageEnvelopeSchema, cn as spaceContractSchema, dr as object, er as boolean, hr as string, ii as trimmedStringFromUnknown, ir as enumFactory, jt as spaceStatusSchema, lr as nullFactory, mr as strictObject, ni as nonEmptyTrimmedStringFromUnknown, nn as dispatchExecutionSchema, nr as discriminatedUnion, or as iso, pr as record, rn as spaceThreadContextSchema, sn as spaceContractFieldsSchema, sr as literal, vr as union, yr as unknown } from "./runtime-transport-CWWB2Ily.js";
7
7
  import { r as daemonServiceLaneSchema } from "./service-contract-CRyDcIIf.js";
8
- import { O as getDaemonStatus } from "./daemon-runtime-lease-Cath1v3w.js";
8
+ import { j as getDaemonStatus } from "./daemon-runtime-lease-Cvo63MGd.js";
9
9
  import { a as getCurrentAuthOwnerUserId, c as updateAuthSessionActiveOrganization, d as resolveOpenMeldDistribution, i as getAuthSessionState, l as runMacOsNativeKeychainHelperIfRequested, n as clearAuthSession, o as normalizeStoredActiveOrganization, r as getAuthSessionMetadata, u as isBinaryDistribution } from "./auth-session-qk94UQqs.js";
10
10
  import { c as buildRequestAuthHeaders, d as buildOpenMeldRequestContextFromProfile, n as createCliApiClientFoundation, p as deriveAuthBaseUrlFromGatewayUrl, r as fetchSpaceRequestWithTimeout, s as buildOpenMeldRequestContextHeadersWithAuth } from "./api-client-foundation-w4Oa06t4.js";
11
11
  import { Command, Option } from "commander";
@@ -11959,12 +11959,6 @@ async function runProfileUpdate(input) {
11959
11959
  profile,
11960
11960
  payload
11961
11961
  });
11962
- await postLocalParticipationMutationReconcile({
11963
- codePrefix: "profile.update",
11964
- ownerUserId: updated.ownerUserId,
11965
- presenter,
11966
- shouldReconcile: false
11967
- });
11968
11962
  const agentRuntimeState = await resolveAgentProfileRuntimeState(updated);
11969
11963
  if (runtime.resolvedView === "human") {
11970
11964
  renderProfileReadyCard({
@@ -16431,7 +16425,7 @@ function createSetupGlobalDeadline(input) {
16431
16425
  }
16432
16426
  function handleSetupGlobalDeadlineExpiry(input) {
16433
16427
  const deadlineMs = input.deadlineMs ?? 9e5;
16434
- const message = `OpenMeld setup did not finish within ${Math.max(1, Math.round(deadlineMs / 6e4))} minutes on this computer and was stopped. This computer's setup lock has been released. Copy a fresh setup command from OpenMeld Web and run setup again.`;
16428
+ const message = `OpenMeld setup did not finish within ${Math.max(1, Math.round(deadlineMs / 6e4))} minutes on this computer and was stopped. This computer's setup lock has been released. Return to OpenMeld Web to see the current connection state and recovery action.`;
16435
16429
  runSafely(() => (input.releaseLockSync ?? releaseLockSync)(input.lock));
16436
16430
  runSafely(() => {
16437
16431
  if (input.view === "agent") {
@@ -16850,8 +16844,8 @@ const PREPARE_TOKEN_HEADER = "x-openmeld-prepare-token";
16850
16844
  const REPORT_RUNTIME_CONNECTION_MAX_ATTEMPTS = 9;
16851
16845
  const WAITING_PROGRESS_DELAY_MS = 500;
16852
16846
  const TERMINAL_PREPARE_STEP_ORDER = [
16853
- "prepare_selected_agents",
16854
16847
  "refresh_service",
16848
+ "prepare_selected_agents",
16855
16849
  "report_runtime",
16856
16850
  "verify_setup"
16857
16851
  ];
@@ -16992,20 +16986,17 @@ async function runPrepareSessionExecutorOnce(input) {
16992
16986
  snapshot: connected
16993
16987
  });
16994
16988
  connectionProgress.complete("Terminal connected. Keep this window open.");
16995
- const withLocalAgents = await reportLocalAgentCatalogForSelection({
16989
+ emitHumanSection(input.input, "Setup progress");
16990
+ const serviceConnected = await connectOpenMeldServiceForPrepare({
16996
16991
  input: input.input,
16997
- stream,
16998
- snapshot: connected
16992
+ snapshot: connected,
16993
+ stream
16999
16994
  });
17000
- const selected = await resolveAgentSelection({
16995
+ const selected = await resolveAgentSelectionAfterServiceConnect({
17001
16996
  input: input.input,
17002
16997
  stream,
17003
- snapshot: withLocalAgents
16998
+ snapshot: serviceConnected
17004
16999
  });
17005
- if (selected.selectedLocalAgentIds.length === 0) return {
17006
- snapshot: selected,
17007
- status: "completed"
17008
- };
17009
17000
  const completed = await executeSelectedAgentPreparation({
17010
17001
  input: input.input,
17011
17002
  stream,
@@ -17023,6 +17014,43 @@ async function runPrepareSessionExecutorOnce(input) {
17023
17014
  stream?.close();
17024
17015
  }
17025
17016
  }
17017
+ async function connectOpenMeldServiceForPrepare(input) {
17018
+ if (findStep(input.snapshot, "refresh_service")?.state === "complete") return input.snapshot;
17019
+ const terminalStep = buildTerminalStep({
17020
+ connectedComputerId: input.snapshot.connectedComputerId,
17021
+ openMeldServiceRuntimeIdentity: resolveRuntimeIdentityFromPrepareSessionSnapshot(input.snapshot),
17022
+ humanProfileId: input.snapshot.humanProfileId,
17023
+ input: input.input,
17024
+ localAgentIds: input.snapshot.selectedLocalAgentIds,
17025
+ ownerUserId: input.snapshot.ownerUserId,
17026
+ stepId: "refresh_service"
17027
+ });
17028
+ return await runTerminalStep({
17029
+ connectionEpoch: requireConnectionEpoch(input.snapshot),
17030
+ input: input.input,
17031
+ snapshot: input.snapshot,
17032
+ stepId: "refresh_service",
17033
+ stream: input.stream,
17034
+ ...terminalStep
17035
+ });
17036
+ }
17037
+ async function resolveAgentSelectionAfterServiceConnect(input) {
17038
+ if (hasAgentSelectionBeenSaved(input.snapshot)) return input.snapshot;
17039
+ if (input.input.localAgentSelection) {
17040
+ const withLocalAgents = await reportLocalAgentCatalogForSelection(input);
17041
+ return await resolveAgentSelection({
17042
+ ...input,
17043
+ snapshot: withLocalAgents
17044
+ });
17045
+ }
17046
+ return await writeTerminalAgentSelection({
17047
+ input: input.input,
17048
+ localAgentIds: [],
17049
+ selectionSource: "background",
17050
+ snapshot: input.snapshot,
17051
+ stream: input.stream
17052
+ });
17053
+ }
17026
17054
  async function resolveAgentSelection(input) {
17027
17055
  if (input.input.localAgentSelection) {
17028
17056
  const guideUrl = buildLocalAgentsGuideUrl(input.input.gatewayUrl);
@@ -17141,6 +17169,7 @@ async function writeTerminalAgentSelection(input) {
17141
17169
  }
17142
17170
  function formatTerminalAgentSelectionResult(input) {
17143
17171
  if (input.localAgentIds.length === 0) {
17172
+ if (input.selectionSource === "background") return "Local agents will finish syncing in the background";
17144
17173
  const message = input.selectionSource === "automatic" ? "Enabled local agents: none" : "Selected: no local agents";
17145
17174
  return input.emptySelectionGuideUrl ? appendLocalAgentsGuideUrl({
17146
17175
  guideUrl: input.emptySelectionGuideUrl,
@@ -17240,7 +17269,6 @@ function haveSameLocalAgentIds(left, right) {
17240
17269
  async function executeSelectedAgentPreparation(input) {
17241
17270
  let snapshot = input.snapshot;
17242
17271
  let reportRuntimeResult = null;
17243
- emitHumanSection(input.input, "Setup progress");
17244
17272
  while (snapshot.lifecycleStatus === "active") {
17245
17273
  const stepId = resolveNextTerminalPrepareStep(snapshot);
17246
17274
  if (stepId === null) return { snapshot };
@@ -17328,7 +17356,7 @@ function requireStartedTerminalStepSnapshot(input) {
17328
17356
  throw input.error;
17329
17357
  }
17330
17358
  if (input.error instanceof PrepareSessionRevisionConflictError) {
17331
- const message = "This setup changed while Terminal was working. Copy a fresh setup command from OpenMeld Web and run setup again to continue from the latest step.";
17359
+ const message = "This setup changed while Terminal was working. Return to OpenMeld Web to see the current connection state and its valid recovery action.";
17332
17360
  input.progress.cancel();
17333
17361
  emitHumanStatus(input.executorInput, "Setup changed", [message]);
17334
17362
  throw new Error(message);
@@ -17401,6 +17429,7 @@ function assertTerminalStepCompletedOrThrow(input) {
17401
17429
  throw new PrepareSessionBlockedByCoreError(message);
17402
17430
  }
17403
17431
  function resolveNextTerminalPrepareStep(snapshot) {
17432
+ if (findStep(snapshot, "refresh_service")?.state !== "complete") return "refresh_service";
17404
17433
  if (snapshot.selectedLocalAgentIds.length === 0) return null;
17405
17434
  return TERMINAL_PREPARE_STEP_ORDER.find((stepId) => {
17406
17435
  return findStep(snapshot, stepId)?.state !== "complete";
@@ -17432,24 +17461,10 @@ async function runRefreshServiceTerminalStep(input, progress) {
17432
17461
  code: "prepare.session.progress.refresh_service.identity",
17433
17462
  text: "Saving this computer's OpenMeld Service identity..."
17434
17463
  });
17435
- const openMeldServiceRuntimeIdentity = await syncLocalSetupCurrentDeviceTargetFromServiceContract({
17464
+ return await syncLocalSetupCurrentDeviceTargetFromServiceContract({
17436
17465
  ...input.connectedComputerId ? { connectedComputerId: input.connectedComputerId } : {},
17437
17466
  gatewayUrl: input.input.gatewayUrl
17438
17467
  });
17439
- progress?.detail({
17440
- code: "prepare.session.progress.refresh_service.state",
17441
- text: "Checking local setup state..."
17442
- });
17443
- const readiness = await collectStartLocalReadiness({ auth: {
17444
- status: "valid",
17445
- email: null,
17446
- authBaseUrl: null,
17447
- gatewayUrl: input.input.gatewayUrl
17448
- } });
17449
- return {
17450
- ...openMeldServiceRuntimeIdentity,
17451
- localReadinessSnapshot: buildPrepareLocalReadinessSnapshot(readiness)
17452
- };
17453
17468
  }
17454
17469
  function buildTerminalStep(input) {
17455
17470
  switch (input.stepId) {
@@ -17483,7 +17498,7 @@ function buildTerminalStep(input) {
17483
17498
  case "verify_setup": return {
17484
17499
  message: getSetupFlowCopy("setup").cliProgressFinishingSetup,
17485
17500
  run: async () => {
17486
- return await finishPrepareSetup({ gatewayUrl: input.input.gatewayUrl });
17501
+ return await finishPrepareSetup();
17487
17502
  }
17488
17503
  };
17489
17504
  default: throw new Error(`Terminal cannot run prepare step: ${input.stepId}`);
@@ -17806,18 +17821,8 @@ function isTransientSelectedAgentConnectionError(error) {
17806
17821
  const rawMessage = toErrorMessage$2(error).toLowerCase();
17807
17822
  return rawMessage.includes("service has not finished starting") || rawMessage.includes("openmeld service is not running") || rawMessage.includes("service.not_running") || rawMessage.includes("service_contract_unavailable") || rawMessage.includes("runtime.reporting.write_failed");
17808
17823
  }
17809
- async function finishPrepareSetup(input) {
17810
- const openMeldServiceRuntimeIdentity = await readTerminalRuntimeIdentityFromServiceContract();
17811
- const readiness = await collectStartLocalReadiness({ auth: {
17812
- status: "valid",
17813
- email: null,
17814
- authBaseUrl: null,
17815
- gatewayUrl: input.gatewayUrl
17816
- } });
17817
- return {
17818
- ...openMeldServiceRuntimeIdentity,
17819
- localReadinessSnapshot: buildPrepareLocalReadinessSnapshot(readiness)
17820
- };
17824
+ async function finishPrepareSetup() {
17825
+ return await readTerminalRuntimeIdentityFromServiceContract();
17821
17826
  }
17822
17827
  async function readTerminalRuntimeIdentityFromServiceContract() {
17823
17828
  const serviceContract = await readDaemonServiceContract();
@@ -17854,14 +17859,14 @@ async function resolveRefreshServiceJobVerdict(input) {
17854
17859
  return await (input.resolveServiceJobVerdict ?? resolvePrepareServiceJobVerdict)().catch(() => null);
17855
17860
  }
17856
17861
  function formatTerminalStepFailureMessage(input) {
17857
- if (input.rawMessage.includes("prepare session revision conflict")) return "This setup changed while Terminal was working. Copy a fresh setup command from OpenMeld Web and run setup again to continue from the latest step.";
17862
+ if (input.rawMessage.includes("prepare session revision conflict")) return "This setup changed while Terminal was working. Return to OpenMeld Web to see the current connection state and its valid recovery action.";
17858
17863
  if (input.stepId === "refresh_service") {
17859
- if (input.serviceJobVerdict === "never_spawned") return "macOS didn't start OpenMeld Service. Open System Settings > General > Login Items & Extensions, turn on the OpenMeld background item, then copy a new setup command from OpenMeld Web.";
17860
- if (input.serviceJobVerdict === "crashed") return `OpenMeld Service keeps stopping after it starts. Run \`${formatOpenMeldCliCommand("openmeld service start --mode foreground")}\` to see the live error, then copy a new setup command from OpenMeld Web.`;
17861
- return "OpenMeld couldn't update its background service. Restart your computer, then copy a new setup command from OpenMeld Web.";
17864
+ if (input.serviceJobVerdict === "never_spawned") return "macOS didn't start OpenMeld Service. Open System Settings > General > Login Items & Extensions, turn on the OpenMeld background item, then return to OpenMeld Web and choose Try again.";
17865
+ if (input.serviceJobVerdict === "crashed") return `OpenMeld Service keeps stopping after it starts. Run \`${formatOpenMeldCliCommand("openmeld service repair")}\` once; OpenMeld saved the failure details for support.`;
17866
+ return "OpenMeld couldn't update its background service. Restart your computer; OpenMeld will reconnect automatically after sign-in.";
17862
17867
  }
17863
17868
  const copy = buildHumanErrorCopy(input.rawMessage);
17864
- return [copy.summary, copy.nextStep ?? "Copy a new setup command from OpenMeld Web and run it again."].join(" ");
17869
+ return [copy.summary, copy.nextStep ?? "Return to OpenMeld Web to see the current connection state and recovery action."].join(" ");
17865
17870
  }
17866
17871
  function resolveTerminalStepFailureReasonCode(input) {
17867
17872
  if (input.rawMessage.includes("runtime.registration.device_forgotten")) return "runtime.registration.device_forgotten";
@@ -18948,6 +18953,7 @@ async function runSetup(input) {
18948
18953
  async function runSetupUnlocked(input) {
18949
18954
  await runSetupStartupLocalStateRepair();
18950
18955
  if (shouldUseSetupLocalAgentConnection(input)) {
18956
+ const previousExitCode = process$1.exitCode;
18951
18957
  const setupResult = await runSetupLocalAgentConnection(input);
18952
18958
  if (setupResult.status !== "completed") return;
18953
18959
  await emitSetupCompleteForDelegatedPath({
@@ -18956,6 +18962,7 @@ async function runSetupUnlocked(input) {
18956
18962
  setupInput: input,
18957
18963
  setupResult
18958
18964
  });
18965
+ process$1.exitCode = previousExitCode;
18959
18966
  return;
18960
18967
  }
18961
18968
  const runtime = await resolveRuntimeContext({ view: input.view });
@@ -19316,13 +19323,13 @@ async function resolveDelegatedSetupCompletionFacts(input) {
19316
19323
  gatewayUrl: input.gatewayUrl
19317
19324
  } })
19318
19325
  });
19326
+ const openMeldServiceRuntimeIdentity = resolveRuntimeIdentityFromSetupSession(input.setupResult.setupSessionSnapshot) ?? await syncLocalSetupCurrentDeviceTargetFromServiceContract({ gatewayUrl: input.gatewayUrl });
19319
19327
  if (selectedLocalAgentIds.length === 0) return {
19320
19328
  routeCatalogSync: null,
19321
- openMeldServiceRuntimeIdentity: null,
19329
+ openMeldServiceRuntimeIdentity,
19322
19330
  runtimeReports: [],
19323
19331
  selectedLocalAgentIds
19324
19332
  };
19325
- const openMeldServiceRuntimeIdentity = resolveRuntimeIdentityFromSetupSession(input.setupResult.setupSessionSnapshot) ?? await syncLocalSetupCurrentDeviceTargetFromServiceContract({ gatewayUrl: input.gatewayUrl });
19326
19333
  const runtimeReports = await submitSelectedAgentControllerReports({
19327
19334
  readiness: await collectStartLocalReadiness({ auth: {
19328
19335
  status: "valid",
@@ -19408,9 +19415,11 @@ function emitSetupComplete(input) {
19408
19415
  const setupCopy = getSetupFlowCopy("setup");
19409
19416
  const serviceGuidance = buildSetupServiceGuidance({ cliCommandPrefix });
19410
19417
  const localAgentsGuideUrl = buildLocalAgentsGuideUrl(input.gatewayUrl);
19418
+ let completionTitle = "OpenMeld Setup Partly Complete";
19419
+ if (input.bootstrap.status === "completed") completionTitle = input.path === "setup_session" ? `✓ ${setupCopy.readyTitle}` : setupCopy.cliCompletionTitle;
19411
19420
  renderInfoCard({
19412
19421
  presenter: input.presenter,
19413
- title: input.bootstrap.status === "completed" ? setupCopy.cliCompletionTitle : "OpenMeld Setup Partly Complete",
19422
+ title: completionTitle,
19414
19423
  codePrefix: "setup.complete.card",
19415
19424
  compact: true,
19416
19425
  minContentWidth: 44,
@@ -27426,7 +27435,7 @@ function normalizeOptionalString(value) {
27426
27435
  return normalized.length > 0 ? normalized : null;
27427
27436
  }
27428
27437
  async function runDefaultSpaceAddMeMembership(input) {
27429
- const { runSpaceAddMeMembership } = await import("./add-me-membership-BhI3ntPB.js");
27438
+ const { runSpaceAddMeMembership } = await import("./add-me-membership-NHxQFPU0.js");
27430
27439
  return await runSpaceAddMeMembership(input);
27431
27440
  }
27432
27441
  //#endregion