@powerhousedao/clint 6.4.0-next.3 → 6.4.0-next.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/{build-skills-Bpbbnin0.mjs → build-skills-BTkuL8ne.mjs} +2 -2
  2. package/dist/{build-skills-Bpbbnin0.mjs.map → build-skills-BTkuL8ne.mjs.map} +1 -1
  3. package/dist/command-control-Dp41aY0o.mjs +224 -0
  4. package/dist/command-control-Dp41aY0o.mjs.map +1 -0
  5. package/dist/{dist-Bd6hUl0J.mjs → dist-BTVqrpN4.mjs} +2 -2
  6. package/dist/{dist-Bd6hUl0J.mjs.map → dist-BTVqrpN4.mjs.map} +1 -1
  7. package/dist/{index-CfHcet4v.d.mts → index-DJlqIVLv.d.mts} +13 -10
  8. package/dist/{index-CfHcet4v.d.mts.map → index-DJlqIVLv.d.mts.map} +1 -1
  9. package/dist/index.d.mts +227 -8
  10. package/dist/index.d.mts.map +1 -1
  11. package/dist/index.mjs +6 -5
  12. package/dist/integrations/mastra/index.d.mts +20 -3
  13. package/dist/integrations/mastra/index.d.mts.map +1 -1
  14. package/dist/integrations/mastra/index.mjs +25 -3
  15. package/dist/integrations/mastra/index.mjs.map +1 -1
  16. package/dist/integrations/powerhouse/index.d.mts +3 -3
  17. package/dist/integrations/powerhouse/index.mjs +1 -1
  18. package/dist/{markdown-BUeGwhbR.mjs → markdown-B-HyDpvO.mjs} +471 -39
  19. package/dist/markdown-B-HyDpvO.mjs.map +1 -0
  20. package/dist/{powerhouse-3XZmdY3_.mjs → powerhouse-C4O-raTW.mjs} +168 -12
  21. package/dist/powerhouse-C4O-raTW.mjs.map +1 -0
  22. package/dist/{proxy-ji3EHzLn.mjs → proxy-DgnOKu1A.mjs} +2 -2
  23. package/dist/proxy-DgnOKu1A.mjs.map +1 -0
  24. package/dist/remote-reactor-oBsHphPT.mjs.map +1 -1
  25. package/dist/{repl-Czb7u0x_.mjs → repl-C4gHgy6P.mjs} +2 -2
  26. package/dist/{repl-Czb7u0x_.mjs.map → repl-C4gHgy6P.mjs.map} +1 -1
  27. package/dist/runners/cli-runner.d.mts +5 -2
  28. package/dist/runners/cli-runner.d.mts.map +1 -1
  29. package/dist/runners/cli-runner.mjs +21 -7
  30. package/dist/runners/cli-runner.mjs.map +1 -1
  31. package/dist/runners/mastra-runner.mjs +1 -1
  32. package/dist/runners/proxy-runner.mjs +1 -1
  33. package/dist/{src-BmMd0Wl4.mjs → src-FF3zDJY7.mjs} +606 -53
  34. package/dist/src-FF3zDJY7.mjs.map +1 -0
  35. package/dist/{start-BHn9LIyX.mjs → start-CCegR8Pi.mjs} +2 -2
  36. package/dist/{start-BHn9LIyX.mjs.map → start-CCegR8Pi.mjs.map} +1 -1
  37. package/dist/testing/index.d.mts +2 -2
  38. package/dist/testing/index.mjs +1 -1
  39. package/dist/{types-3TnDjQ1w.d.mts → types-BnPpIAL6.d.mts} +2 -2
  40. package/dist/{types-3TnDjQ1w.d.mts.map → types-BnPpIAL6.d.mts.map} +1 -1
  41. package/dist/{types-DbQKfvWc.d.mts → types-CIZtG2TY.d.mts} +219 -13
  42. package/dist/types-CIZtG2TY.d.mts.map +1 -0
  43. package/package.json +13 -13
  44. package/dist/markdown-BUeGwhbR.mjs.map +0 -1
  45. package/dist/powerhouse-3XZmdY3_.mjs.map +0 -1
  46. package/dist/proxy-ji3EHzLn.mjs.map +0 -1
  47. package/dist/src-BmMd0Wl4.mjs.map +0 -1
  48. package/dist/types-DbQKfvWc.d.mts.map +0 -1
@@ -1,15 +1,14 @@
1
1
  import { n as slugToTitle, t as getSchemaFields } from "./schema-BEKAZGyT.mjs";
2
+ import { createRequire } from "node:module";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
4
5
  import { z } from "zod";
5
6
  import crypto from "node:crypto";
6
7
  import os from "node:os";
8
+ import { restartDecision } from "@powerhousedao/host-core/instance";
7
9
  import { execSync, spawn } from "node:child_process";
8
10
  import { killTree } from "@powerhousedao/host-core/kill-tree";
9
11
  import net from "node:net";
10
- import { Marked } from "marked";
11
- import { markedTerminal } from "marked-terminal";
12
- import { supportsLanguage } from "cli-highlight";
13
12
  //#region src/core/stream.ts
14
13
  const DIM = "\x1B[2m";
15
14
  const RESET = "\x1B[0m";
@@ -359,6 +358,15 @@ function resolveServiceName(def) {
359
358
  function defineService(opts) {
360
359
  return opts;
361
360
  }
361
+ /** What the supervisor says of an instance beyond its status, as the state
362
+ * keeps it for every listing. */
363
+ function supervisedFacts(held) {
364
+ return {
365
+ ...held.runnerVersion === void 0 ? {} : { runnerVersion: held.runnerVersion },
366
+ ...held.missing.length > 0 ? { missing: held.missing } : {},
367
+ ...held.restart ? { restart: held.restart } : {}
368
+ };
369
+ }
362
370
  /**
363
371
  * Get the directory for a service's instance state files.
364
372
  */
@@ -522,6 +530,14 @@ function isInstanceAlive(state) {
522
530
  return state.pid > 0 && isPidAlive(state.pid);
523
531
  }
524
532
  /**
533
+ * Whether a recorded instance is the supervisor's to manage for any tool of
534
+ * the user: the supervisor holds it and the manager that asked for it has
535
+ * ended. While that manager runs, the instance is managed there.
536
+ */
537
+ function isHeldBySupervisor(state) {
538
+ return state.supervisor !== void 0 && !isOwnerAlive(state) && isPidAlive(state.supervisor.pid) && (isInstanceAlive(state) || state.supervisor.restarting === true);
539
+ }
540
+ /**
525
541
  * Why a live instance this manager did not spawn is not its to manage: it
526
542
  * belongs to another running process, or it is a leftover whose owner is
527
543
  * gone. Either way it is never adopted, stopped or restarted from here (a
@@ -675,6 +691,261 @@ function createServiceManager(definitions, opts) {
675
691
  /** Host services waiting for their run record, by state path: a stop
676
692
  * aborts the wait and awaits `settled`. */
677
693
  const hostStarts = /* @__PURE__ */ new Map();
694
+ const hasHostServices = definitions.some((def) => def.run !== void 0);
695
+ /** This process's lease with the supervisor: what it started there "with
696
+ * the caller" is stopped when the lease's connection ends. */
697
+ let leased;
698
+ /**
699
+ * The user's supervisor, when one runs: host services are then its
700
+ * children, not this process's. One file is looked for when none is
701
+ * recorded, and nothing of the supervisor is loaded. A recorded supervisor
702
+ * that does not answer is an error: supervising here in its place could
703
+ * run an instance twice.
704
+ */
705
+ async function runningSupervisor() {
706
+ if (!hasHostServices) return void 0;
707
+ const { supervisorRecorded } = await import("@powerhousedao/host-core/supervisor-record");
708
+ if (!supervisorRecorded()) return void 0;
709
+ const api = await import("@powerhousedao/host-core/supervisor");
710
+ const found = await api.findSupervisor();
711
+ if (found.status === "none") return void 0;
712
+ if (found.status === "silent") throw new Error(api.silentSupervisorMessage(found));
713
+ return {
714
+ api,
715
+ pid: found.record.pid,
716
+ control: found.record.control
717
+ };
718
+ }
719
+ function holdLease(supervisor) {
720
+ if (leased?.pid === supervisor.pid) return leased.lease;
721
+ const lease = supervisor.api.holdSupervisorLease(supervisor.control);
722
+ const mine = {
723
+ pid: supervisor.pid,
724
+ lease
725
+ };
726
+ leased = mine;
727
+ const forget = () => {
728
+ if (leased === mine) leased = void 0;
729
+ };
730
+ lease.then((held) => held.ended.then(forget), forget);
731
+ return lease;
732
+ }
733
+ /**
734
+ * The instance of `state` as the supervisor lists it, when it holds it:
735
+ * the handle, and the same process or (after the supervisor started it
736
+ * again) the same log file, which this manager named for it alone.
737
+ */
738
+ async function heldInstance(supervisor, state, listed) {
739
+ if (state.supervisor?.pid !== supervisor.pid) return void 0;
740
+ const instances = listed ?? (await supervisor.api.listSupervised(supervisor.control)).instances;
741
+ const logPath = state.logFile === void 0 ? void 0 : path.resolve(serviceDir(servicesDir, state.serviceId), state.logFile);
742
+ return instances.find((i) => i.handle === state.supervisor?.handle && i.mine && (i.pid === state.pid || logPath !== void 0 && i.logFile !== void 0 && path.resolve(i.logFile) === logPath));
743
+ }
744
+ /**
745
+ * Brings the state of an instance the supervisor holds in line with what
746
+ * the supervisor says of it: the process it runs as now, a restart it
747
+ * waits for, or that it was left ended. Returns whether it is settled
748
+ * (false: the supervisor is starting it again).
749
+ */
750
+ function applySupervised(def, state, held) {
751
+ const statePath = stateFilePath(servicesDir, def.id, state.instanceId);
752
+ if (!state.supervisor || state.status === "stopped") return true;
753
+ if (hostStarts.has(statePath) || stopping.has(statePath)) return true;
754
+ const name = resolveServiceName(def);
755
+ const before = JSON.stringify(state);
756
+ const attempt = held?.restart?.attempt;
757
+ let settled = true;
758
+ if (held) {
759
+ const { pid, handle, lifetime, restarting } = state.supervisor;
760
+ state.supervisor = {
761
+ pid,
762
+ handle,
763
+ lifetime,
764
+ ...restarting ? { restarting } : {},
765
+ ...supervisedFacts(held)
766
+ };
767
+ }
768
+ if (held?.status === "starting" || held?.status === "restarting") {
769
+ settled = false;
770
+ const first = !state.supervisor.restarting;
771
+ state.supervisor.restarting = true;
772
+ if (attempt !== void 0 && (first || attempt !== state.restartAttempt)) {
773
+ state.restartAttempt = attempt;
774
+ if (isMine(state) && held.restart) eventBus?.emit("service:restarting", {
775
+ id: def.id,
776
+ instanceId: state.instanceId,
777
+ name,
778
+ attempt,
779
+ maxRetries: held.restart.maxRetries
780
+ });
781
+ }
782
+ } else if (held?.status === "running" && held.pid === state.pid && !isInstanceAlive(state)) settled = false;
783
+ else if (held?.status === "running") {
784
+ const moved = held.pid !== state.pid || state.supervisor.restarting;
785
+ delete state.supervisor.restarting;
786
+ if (moved) {
787
+ state.pid = held.pid;
788
+ state.status = "ready";
789
+ delete state.error;
790
+ if (attempt !== void 0) state.restartAttempt = attempt;
791
+ if (held.record && def.run && def.endpoints) try {
792
+ const endpoints = def.endpoints(held.record);
793
+ state.endpoints = {};
794
+ state.endpointTypes = {};
795
+ for (const [key, endpoint] of Object.entries(endpoints)) {
796
+ state.endpoints[key] = endpoint.url;
797
+ if (endpoint.type) state.endpointTypes[key] = endpoint.type;
798
+ }
799
+ } catch {}
800
+ if (isMine(state)) eventBus?.emit("service:ready", {
801
+ id: def.id,
802
+ instanceId: state.instanceId,
803
+ name,
804
+ endpoints: state.endpoints ?? {},
805
+ endpointTypes: state.endpointTypes ?? {}
806
+ });
807
+ }
808
+ } else if (held?.status === "failed") {
809
+ delete state.supervisor.restarting;
810
+ if (state.status !== "failed") {
811
+ state.status = "failed";
812
+ state.error = `The supervisor left it ended: ${held.restart?.failed ?? "it ended on its own"}.`;
813
+ if (attempt !== void 0) state.restartAttempt = attempt;
814
+ if (isMine(state)) eventBus?.emit("service:failed", {
815
+ id: def.id,
816
+ instanceId: state.instanceId,
817
+ name,
818
+ error: state.error
819
+ });
820
+ }
821
+ } else if (!isInstanceAlive(state) || state.supervisor.restarting) {
822
+ delete state.supervisor.restarting;
823
+ state.status = "stopped";
824
+ state.pid = 0;
825
+ state.stoppedAt ??= (/* @__PURE__ */ new Date()).toISOString();
826
+ }
827
+ if (JSON.stringify(state) !== before) writeStateFile(statePath, state);
828
+ return settled;
829
+ }
830
+ /** Whether this manager speaks for a recorded instance: its own, or one
831
+ * whose manager has ended. */
832
+ const speaksFor = (state) => isMine(state) || !isOwnerAlive(state);
833
+ /**
834
+ * Whether the supervisor is to say what became of an instance it holds
835
+ * under a restart policy: it ended on its own, or is being started again.
836
+ */
837
+ function awaitsSupervisor(def, state) {
838
+ return state.supervisor !== void 0 && def.restart?.enabled === true && speaksFor(state) && state.status !== "stopped" && state.status !== "failed" && isPidAlive(state.supervisor.pid) && (state.supervisor.restarting === true || !isInstanceAlive(state));
839
+ }
840
+ /** State paths whose instance the supervisor is asked about until it is
841
+ * settled. */
842
+ const following = /* @__PURE__ */ new Set();
843
+ const FOLLOW_POLL_MS = 250;
844
+ /**
845
+ * An instance the supervisor holds has ended on its own: the supervisor
846
+ * decides whether it starts again, and this follows what it does until
847
+ * the instance runs again or is left ended.
848
+ */
849
+ function followSupervised(def, statePath) {
850
+ if (following.has(statePath)) return;
851
+ following.add(statePath);
852
+ (async () => {
853
+ try {
854
+ for (;;) {
855
+ const state = readStateFile(statePath);
856
+ if (!state?.supervisor || !speaksFor(state)) return;
857
+ if (state.status === "stopped" || stopping.has(statePath)) return;
858
+ let held;
859
+ try {
860
+ const supervisor = await runningSupervisor();
861
+ if (supervisor) held = await heldInstance(supervisor, state);
862
+ } catch {}
863
+ const now = readStateFile(statePath);
864
+ if (!now?.supervisor || !speaksFor(now) || now.status === "stopped" || stopping.has(statePath)) return;
865
+ if (applySupervised(def, now, held)) return;
866
+ await new Promise((resolve) => {
867
+ setTimeout(resolve, FOLLOW_POLL_MS).unref();
868
+ });
869
+ }
870
+ } finally {
871
+ following.delete(statePath);
872
+ }
873
+ })();
874
+ }
875
+ /**
876
+ * Asks the supervisor about every instance it holds for this manager or
877
+ * for one that has ended, and brings their state in line. Returns the
878
+ * supervisor, when one runs.
879
+ */
880
+ async function syncSupervised() {
881
+ const supervisor = await runningSupervisor();
882
+ if (!supervisor) return void 0;
883
+ let listed;
884
+ for (const def of definitions) {
885
+ if (!def.run) continue;
886
+ for (const state of scanInstances(servicesDir, def.id)) {
887
+ if (state.supervisor?.pid !== supervisor.pid) continue;
888
+ if (state.status === "stopped") continue;
889
+ if (!isMine(state) && isOwnerAlive(state)) continue;
890
+ listed ??= (await supervisor.api.listSupervised(supervisor.control)).instances;
891
+ applySupervised(def, state, await heldInstance(supervisor, state, listed));
892
+ }
893
+ }
894
+ return supervisor;
895
+ }
896
+ /** Stops, at the supervisor, the instance it holds for `state`: also one
897
+ * it would start again. False when it holds none. */
898
+ async function stopAtSupervisor(state) {
899
+ if (!state.supervisor) return false;
900
+ const supervisor = await runningSupervisor();
901
+ if (!supervisor || !await heldInstance(supervisor, state)) return false;
902
+ await supervisor.api.stopSupervised(supervisor.control, state.supervisor.handle);
903
+ return true;
904
+ }
905
+ /** The status of an instance whose restart the supervisor decides on. */
906
+ function awaitedStatus(def, state) {
907
+ return {
908
+ serviceId: def.id,
909
+ instanceId: state.instanceId,
910
+ name: resolveServiceName(def),
911
+ status: "starting",
912
+ restartAttempt: state.restartAttempt,
913
+ params: state.params,
914
+ workdir: state.workdir,
915
+ ...state.supervisor ? { supervisor: state.supervisor } : {}
916
+ };
917
+ }
918
+ /** The status of an instance the supervisor's restart policy gave up on:
919
+ * listed as failed, with the reason, until it is started or stopped. */
920
+ function leftEndedStatus(def, state) {
921
+ return {
922
+ serviceId: def.id,
923
+ instanceId: state.instanceId,
924
+ name: resolveServiceName(def),
925
+ status: "failed",
926
+ error: state.error ?? "Process exited unexpectedly",
927
+ restartAttempt: state.restartAttempt,
928
+ params: state.params,
929
+ workdir: state.workdir,
930
+ ...state.supervisor ? { supervisor: state.supervisor } : {}
931
+ };
932
+ }
933
+ /** The status of an instance the supervisor holds for an ended manager. */
934
+ function heldStatus(def, state) {
935
+ return {
936
+ serviceId: def.id,
937
+ instanceId: state.instanceId,
938
+ name: resolveServiceName(def),
939
+ status: state.supervisor?.restarting ? "starting" : state.status,
940
+ ...state.supervisor?.restarting ? { restartAttempt: state.restartAttempt } : {},
941
+ pid: state.pid,
942
+ endpoints: state.endpoints,
943
+ endpointTypes: state.endpointTypes,
944
+ params: state.params,
945
+ workdir: state.workdir,
946
+ supervisor: state.supervisor
947
+ };
948
+ }
678
949
  /**
679
950
  * The status of a recorded instance this manager did not spawn. One whose
680
951
  * process is gone reads as stopped (and, when its owner is gone too, the
@@ -724,12 +995,19 @@ function createServiceManager(definitions, opts) {
724
995
  assertOneForm(def);
725
996
  const instanceId = resolveInstanceId(id, startOpts);
726
997
  const maxInstances = def.maxInstances ?? 1;
727
- if (hostStarts.has(stateFilePath(servicesDir, id, instanceId))) throw new Error(`Service ${id} is already starting`);
998
+ if (hostStarts.has(stateFilePath(servicesDir, id, instanceId))) return instanceId;
728
999
  const existingState = readStateFile(stateFilePath(servicesDir, id, instanceId));
729
1000
  if (existingState && existingState.status === "stopped") removeStateFile(stateFilePath(servicesDir, id, instanceId));
730
- else if (existingState && isInstanceAlive(existingState)) {
731
- if (!isMine(existingState)) throw new Error(`Service ${id}: ${notOursMessage(existingState)}`);
732
- if (existingState.status === "ready" || existingState.status === "starting") throw new Error(`Service ${id} is already running (pid ${existingState.pid})`);
1001
+ else if (existingState && awaitsSupervisor(def, existingState)) {
1002
+ const supervisor = await runningSupervisor();
1003
+ if (!(supervisor !== void 0 && applySupervised(def, existingState, await heldInstance(supervisor, existingState))) || existingState.status === "ready") return instanceId;
1004
+ if (existingState.status === "stopped") removeStateFile(stateFilePath(servicesDir, id, instanceId));
1005
+ } else if (existingState && isInstanceAlive(existingState)) {
1006
+ if (!isMine(existingState)) {
1007
+ if (isHeldBySupervisor(existingState) && existingState.status === "ready") return instanceId;
1008
+ throw new Error(`Service ${id}: ${notOursMessage(existingState)}`);
1009
+ }
1010
+ if (existingState.status === "ready" || existingState.status === "starting") return instanceId;
733
1011
  }
734
1012
  if (scanInstances(servicesDir, id).filter((s) => s.instanceId !== instanceId && s.status !== "stopped" && isMine(s) && (isInstanceAlive(s) || hostStarts.has(stateFilePath(servicesDir, id, s.instanceId)))).length >= maxInstances) throw new Error(`Service ${id} has reached max instances (${maxInstances})`);
735
1013
  ensureServiceDir(id);
@@ -753,6 +1031,14 @@ function createServiceManager(definitions, opts) {
753
1031
  }
754
1032
  }
755
1033
  }
1034
+ const lifetime = startOpts?.lifetime ?? "caller";
1035
+ const supervisor = def.run ? await runningSupervisor() : void 0;
1036
+ if (lifetime === "supervisor" && !supervisor) throw new Error(def.run ? `Service ${id}: no supervisor runs for this user, so nothing can outlive this process. Start one with \`ph run supervisor\`.` : `Service ${id} is no host service: it lives with the process that starts it.`);
1037
+ const supervised = supervisor ? {
1038
+ supervisor,
1039
+ lifetime,
1040
+ ...lifetime === "caller" ? { lease: (await holdLease(supervisor)).id } : {}
1041
+ } : void 0;
756
1042
  if (closing) throw new Error(`Service ${id}: the service manager is stopping`);
757
1043
  const logFile = newRunLogFile(servicesDir, id, instanceId);
758
1044
  const logPath = path.join(serviceDir(servicesDir, id), logFile);
@@ -776,7 +1062,8 @@ function createServiceManager(definitions, opts) {
776
1062
  ...def.run.env,
777
1063
  ...def.env ? def.env(buildCtx) : {}
778
1064
  },
779
- restartAttempt
1065
+ restartAttempt,
1066
+ ...supervised ? { supervised } : {}
780
1067
  });
781
1068
  }
782
1069
  const env = {
@@ -967,7 +1254,31 @@ function createServiceManager(definitions, opts) {
967
1254
  return startFailure(id, error, run.cwd, run.command, tailLogFile(run.logPath));
968
1255
  };
969
1256
  const abort = new AbortController();
1257
+ const { supervised } = run;
1258
+ let handle;
1259
+ let startedAs;
970
1260
  const spawning = (async () => {
1261
+ if (supervised) {
1262
+ const { api, control } = supervised.supervisor;
1263
+ const held = await api.startSupervisedHost(control, {
1264
+ host: def.run.host,
1265
+ projectDir: run.cwd,
1266
+ dataDir: run.cwd,
1267
+ ...def.run.verb === void 0 ? {} : { verb: def.run.verb },
1268
+ ...def.run.argv ? { argv: [...def.run.argv] } : {},
1269
+ env: run.env,
1270
+ baseEnv: Object.fromEntries(Object.entries(run.baseEnv).filter((entry) => entry[1] !== void 0)),
1271
+ lifetime: supervised.lifetime,
1272
+ ...supervised.lease ? { lease: supervised.lease } : {},
1273
+ logFile: run.logPath,
1274
+ ...def.readiness ? { readyTimeoutMs: def.readiness.timeout } : {},
1275
+ ...def.shutdown ? { stopTimeoutMs: def.shutdown.timeout } : {},
1276
+ ...def.restart ? { restart: def.restart } : {}
1277
+ }, { signal: abort.signal });
1278
+ handle = held.handle;
1279
+ startedAs = held.instance;
1280
+ return held;
1281
+ }
971
1282
  const { spawnHost } = await import("@powerhousedao/host-core");
972
1283
  return spawnHost({
973
1284
  projectRoot: run.cwd,
@@ -1017,6 +1328,12 @@ function createServiceManager(definitions, opts) {
1017
1328
  state.pid = spawned.pid;
1018
1329
  state.status = "ready";
1019
1330
  state.restartAttempt = 0;
1331
+ if (supervised && handle !== void 0 && !spawned.existing) state.supervisor = {
1332
+ pid: supervised.supervisor.pid,
1333
+ handle,
1334
+ lifetime: supervised.lifetime,
1335
+ ...startedAs ? supervisedFacts(startedAs) : {}
1336
+ };
1020
1337
  state.endpoints = {};
1021
1338
  state.endpointTypes = {};
1022
1339
  for (const [key, endpoint] of Object.entries(endpoints)) {
@@ -1027,6 +1344,7 @@ function createServiceManager(definitions, opts) {
1027
1344
  hostRuns.set(statePath, spawned);
1028
1345
  spawned.exited.then(() => {
1029
1346
  if (hostRuns.get(statePath) === spawned) hostRuns.delete(statePath);
1347
+ if (state.supervisor) followSupervised(def, statePath);
1030
1348
  });
1031
1349
  eventBus?.emit("service:ready", {
1032
1350
  id,
@@ -1058,10 +1376,34 @@ function createServiceManager(definitions, opts) {
1058
1376
  if (state?.status === "stopped") return;
1059
1377
  throw new Error(`Service ${serviceId} is not running`);
1060
1378
  }
1379
+ /** Stopped at the supervisor: a stop that was asked for, so its restart
1380
+ * policy leaves the instance ended. */
1381
+ const stoppedThere = async () => {
1382
+ stopping.add(statePath);
1383
+ try {
1384
+ if (!await stopAtSupervisor(state)) return false;
1385
+ hostRuns.delete(statePath);
1386
+ if (state.supervisor) delete state.supervisor.restarting;
1387
+ state.status = "stopped";
1388
+ state.pid = 0;
1389
+ state.stoppedAt = (/* @__PURE__ */ new Date()).toISOString();
1390
+ writeStateFile(statePath, state);
1391
+ } finally {
1392
+ stopping.delete(statePath);
1393
+ }
1394
+ eventBus?.emit("service:stopped", {
1395
+ id: serviceId,
1396
+ instanceId,
1397
+ name: resolveServiceName(def)
1398
+ });
1399
+ return true;
1400
+ };
1061
1401
  if (!isMine(state)) {
1402
+ if ((isHeldBySupervisor(state) || awaitsSupervisor(def, state)) && await stoppedThere()) return;
1062
1403
  if (foreignStatus(def, state).status === "stopped") return;
1063
1404
  throw new Error(`Service ${serviceId}: ${notOursMessage(state)}`);
1064
1405
  }
1406
+ if (state.supervisor && def.restart?.enabled && isPidAlive(state.supervisor.pid) && await stoppedThere()) return;
1065
1407
  if (!isPidAlive(state.pid)) {
1066
1408
  state.status = "stopped";
1067
1409
  state.pid = 0;
@@ -1125,7 +1467,7 @@ function createServiceManager(definitions, opts) {
1125
1467
  if (instanceId) return stopInstance(def, id, instanceId);
1126
1468
  const instances = scanInstances(servicesDir, id);
1127
1469
  if (instances.length === 0) throw new Error(`Service ${id} is not running`);
1128
- const mine = instances.filter((s) => s.status !== "stopped" && isMine(s));
1470
+ const mine = instances.filter((s) => s.status !== "stopped" && (isMine(s) || isHeldBySupervisor(s) || awaitsSupervisor(def, s)));
1129
1471
  if (mine.length === 0) {
1130
1472
  const theirs = instances.find((s) => s.status !== "stopped" && isInstanceAlive(s));
1131
1473
  if (theirs) throw new Error(`Service ${id}: ${notOursMessage(theirs)}`);
@@ -1137,7 +1479,8 @@ function createServiceManager(definitions, opts) {
1137
1479
  }
1138
1480
  /** Stop every instance this manager started, gracefully (each service's
1139
1481
  * shutdown signal and timeout), and cancel pending restarts. Nothing
1140
- * starts while it runs. */
1482
+ * starts while it runs. An instance started to live with the supervisor
1483
+ * stays: it is the supervisor's from here on. */
1141
1484
  async function stopAll() {
1142
1485
  closing = true;
1143
1486
  for (const timer of restartTimers) clearTimeout(timer);
@@ -1145,10 +1488,14 @@ function createServiceManager(definitions, opts) {
1145
1488
  try {
1146
1489
  for (const def of definitions) for (const state of scanInstances(servicesDir, def.id)) {
1147
1490
  if (state.status === "stopped" || !isMine(state)) continue;
1491
+ if (state.supervisor?.lifetime === "supervisor") continue;
1148
1492
  try {
1149
1493
  await stopInstance(def, def.id, state.instanceId);
1150
1494
  } catch {}
1151
1495
  }
1496
+ const held = leased;
1497
+ leased = void 0;
1498
+ if (held) await held.lease.then((lease) => lease.release()).catch(() => {});
1152
1499
  } finally {
1153
1500
  closing = false;
1154
1501
  }
@@ -1180,7 +1527,16 @@ function createServiceManager(definitions, opts) {
1180
1527
  continue;
1181
1528
  }
1182
1529
  if (!isMine(state)) {
1183
- results.push(foreignStatus(def, state));
1530
+ if (awaitsSupervisor(def, state)) {
1531
+ followSupervised(def, stateFilePath(servicesDir, def.id, state.instanceId));
1532
+ results.push(awaitedStatus(def, state));
1533
+ continue;
1534
+ }
1535
+ if (state.supervisor && state.status === "failed" && !isOwnerAlive(state) && !isInstanceAlive(state)) {
1536
+ results.push(leftEndedStatus(def, state));
1537
+ continue;
1538
+ }
1539
+ results.push(isHeldBySupervisor(state) ? heldStatus(def, state) : foreignStatus(def, state));
1184
1540
  continue;
1185
1541
  }
1186
1542
  const statePath = stateFilePath(servicesDir, def.id, state.instanceId);
@@ -1207,9 +1563,41 @@ function createServiceManager(definitions, opts) {
1207
1563
  });
1208
1564
  continue;
1209
1565
  }
1566
+ if (awaitsSupervisor(def, state)) {
1567
+ followSupervised(def, statePath);
1568
+ results.push(awaitedStatus(def, state));
1569
+ continue;
1570
+ }
1571
+ if (state.supervisor && def.restart?.enabled) {
1572
+ if (state.status === "failed") {
1573
+ results.push(leftEndedStatus(def, state));
1574
+ continue;
1575
+ }
1576
+ if (!isInstanceAlive(state)) {
1577
+ delete state.supervisor.restarting;
1578
+ state.status = "stopped";
1579
+ state.pid = 0;
1580
+ state.stoppedAt = (/* @__PURE__ */ new Date()).toISOString();
1581
+ writeStateFile(statePath, state);
1582
+ results.push({
1583
+ serviceId: def.id,
1584
+ instanceId: state.instanceId,
1585
+ name: state.name,
1586
+ status: "stopped",
1587
+ params: state.params,
1588
+ workdir: state.workdir
1589
+ });
1590
+ continue;
1591
+ }
1592
+ }
1210
1593
  if (!state.pid || !isPidAlive(state.pid)) {
1211
- if (!closing && def.restart?.enabled && (state.restartAttempt ?? 0) < def.restart.maxRetries && state.status === "ready") {
1212
- const attempt = (state.restartAttempt ?? 0) + 1;
1594
+ const decision = restartDecision(def.restart, {
1595
+ attempt: state.restartAttempt ?? 0,
1596
+ wasReady: state.status === "ready",
1597
+ closing
1598
+ });
1599
+ if (decision.action === "restart" && def.restart) {
1600
+ const attempt = decision.attempt;
1213
1601
  eventBus?.emit("service:restarting", {
1214
1602
  id: def.id,
1215
1603
  instanceId: state.instanceId,
@@ -1249,7 +1637,7 @@ function createServiceManager(definitions, opts) {
1249
1637
  name: restartName
1250
1638
  });
1251
1639
  } catch {}
1252
- }, def.restart.delay);
1640
+ }, decision.delayMs);
1253
1641
  restartTimers.add(timer);
1254
1642
  results.push({
1255
1643
  serviceId: def.id,
@@ -1261,8 +1649,9 @@ function createServiceManager(definitions, opts) {
1261
1649
  workdir: state.workdir
1262
1650
  });
1263
1651
  } else {
1264
- const isFailed = state.status === "failed" || def.restart?.enabled && (state.restartAttempt ?? 0) >= def.restart.maxRetries;
1265
- if (def.restart?.enabled && (state.restartAttempt ?? 0) >= def.restart.maxRetries) eventBus?.emit("service:failed", {
1652
+ const gaveUp = decision.action === "give-up";
1653
+ const isFailed = state.status === "failed" || gaveUp;
1654
+ if (gaveUp) eventBus?.emit("service:failed", {
1266
1655
  id: def.id,
1267
1656
  instanceId: state.instanceId,
1268
1657
  name: resolveServiceName(def),
@@ -1305,7 +1694,8 @@ function createServiceManager(definitions, opts) {
1305
1694
  endpointTypes: state.endpointTypes,
1306
1695
  restartAttempt: state.restartAttempt,
1307
1696
  params: state.params,
1308
- workdir: state.workdir
1697
+ workdir: state.workdir,
1698
+ ...state.supervisor ? { supervisor: state.supervisor } : {}
1309
1699
  });
1310
1700
  }
1311
1701
  }
@@ -1380,7 +1770,11 @@ function createServiceManager(definitions, opts) {
1380
1770
  watchLogs,
1381
1771
  watchChunks,
1382
1772
  scanProjects: scanProjectsForService,
1383
- purgeStoppedInstances
1773
+ purgeStoppedInstances,
1774
+ supervisor: async () => {
1775
+ const running = await syncSupervised();
1776
+ return running ? { pid: running.pid } : void 0;
1777
+ }
1384
1778
  };
1385
1779
  }
1386
1780
  //#endregion
@@ -1547,26 +1941,64 @@ function getEnumValues(schema, fieldName) {
1547
1941
  }
1548
1942
  //#endregion
1549
1943
  //#region src/interactive/markdown.ts
1550
- const marked = new Marked();
1551
- const terminalExt = markedTerminal();
1552
- const originalCode = terminalExt.renderer.code;
1553
- terminalExt.renderer.code = function(...args) {
1554
- const [first, second, third] = args;
1555
- if (first && typeof first === "object") {
1556
- const token = first;
1557
- if (token.lang && !supportsLanguage(token.lang)) return originalCode.call(this, {
1558
- ...token,
1559
- lang: ""
1944
+ let renderer;
1945
+ /**
1946
+ * Build the Marked instance with terminal rendering.
1947
+ * A dedicated instance avoids mutating the global marked instance.
1948
+ */
1949
+ function createRenderer({ Marked, markedTerminal, supportsLanguage }) {
1950
+ const marked = new Marked();
1951
+ const terminalExt = markedTerminal();
1952
+ const originalCode = terminalExt.renderer.code;
1953
+ terminalExt.renderer.code = function(...args) {
1954
+ const [first, second, third] = args;
1955
+ if (first && typeof first === "object") {
1956
+ const token = first;
1957
+ if (token.lang && !supportsLanguage(token.lang)) return originalCode.call(this, {
1958
+ ...token,
1959
+ lang: ""
1960
+ });
1961
+ return originalCode.call(this, first);
1962
+ }
1963
+ if (typeof second === "string" && !supportsLanguage(second)) return originalCode.call(this, first, "", third);
1964
+ return originalCode.call(this, ...args);
1965
+ };
1966
+ marked.use(terminalExt);
1967
+ marked.use({ walkTokens(token) {
1968
+ if (token.type === "list" || token.type === "list_item") token.loose = false;
1969
+ } });
1970
+ return marked;
1971
+ }
1972
+ /**
1973
+ * Load the markdown renderer ahead of a render. marked, marked-terminal and
1974
+ * cli-highlight stay off the start path: they load here or on the first
1975
+ * sync call.
1976
+ */
1977
+ async function loadMarkdown() {
1978
+ if (renderer) return;
1979
+ const [{ Marked }, { markedTerminal }, { supportsLanguage }] = await Promise.all([
1980
+ import("marked"),
1981
+ import("marked-terminal"),
1982
+ import("cli-highlight")
1983
+ ]);
1984
+ renderer ??= createRenderer({
1985
+ Marked,
1986
+ markedTerminal,
1987
+ supportsLanguage
1988
+ });
1989
+ }
1990
+ /** Renderer for sync callers; required on first use unless already loaded. */
1991
+ function markdownRenderer() {
1992
+ if (!renderer) {
1993
+ const require = createRequire(import.meta.url);
1994
+ renderer = createRenderer({
1995
+ Marked: require("marked").Marked,
1996
+ markedTerminal: require("marked-terminal").markedTerminal,
1997
+ supportsLanguage: require("cli-highlight").supportsLanguage
1560
1998
  });
1561
- return originalCode.call(this, first);
1562
1999
  }
1563
- if (typeof second === "string" && !supportsLanguage(second)) return originalCode.call(this, first, "", third);
1564
- return originalCode.call(this, ...args);
1565
- };
1566
- marked.use(terminalExt);
1567
- marked.use({ walkTokens(token) {
1568
- if (token.type === "list" || token.type === "list_item") token.loose = false;
1569
- } });
2000
+ return renderer;
2001
+ }
1570
2002
  /**
1571
2003
  * Render a markdown string for terminal display.
1572
2004
  * Returns ANSI-formatted text suitable for terminal output.
@@ -1576,13 +2008,13 @@ marked.use({ walkTokens(token) {
1576
2008
  */
1577
2009
  function renderMarkdown(text) {
1578
2010
  if (!text) return "";
1579
- const rendered = marked.parse(text);
2011
+ const rendered = markdownRenderer().parse(text);
1580
2012
  /* istanbul ignore next -- marked.parse() always returns string with sync config */
1581
2013
  if (typeof rendered !== "string") return text;
1582
2014
  const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
1583
2015
  return rendered.split("\n").filter((line) => line.length === 0 || stripAnsi(line).trim().length > 0).join("\n").trimEnd();
1584
2016
  }
1585
2017
  //#endregion
1586
- export { renderStream as S, isPortFree as _, getGhostSuggestion as a, supervisedSpawnOptions as b, hostCommandLine as c, watchLogFile as d, PROJECT_INDICATORS as f, checkWorkdir as g, checkPort as h, getCompletions as i, resolveServiceName as l, checkCommand as m, applyCompletion as n, createServiceManager as o, scanProjects as p, getCompletionSuffix as r, defineService as s, renderMarkdown as t, sanitizeLogText as u, killTree as v, formatStreamChunk as x, superviseChild as y };
2018
+ export { renderStream as C, formatStreamChunk as S, checkWorkdir as _, getCompletions as a, superviseChild as b, defineService as c, sanitizeLogText as d, watchLogFile as f, checkPort as g, checkCommand as h, getCompletionSuffix as i, hostCommandLine as l, scanProjects as m, renderMarkdown as n, getGhostSuggestion as o, PROJECT_INDICATORS as p, applyCompletion as r, createServiceManager as s, loadMarkdown as t, resolveServiceName as u, isPortFree as v, supervisedSpawnOptions as x, killTree as y };
1587
2019
 
1588
- //# sourceMappingURL=markdown-BUeGwhbR.mjs.map
2020
+ //# sourceMappingURL=markdown-B-HyDpvO.mjs.map