@koed-labs/server 0.10.3 → 1.0.0

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 (56) hide show
  1. package/README.md +3 -3
  2. package/bin/koed.js +1 -1
  3. package/package.json +2 -2
  4. package/vendor/chunk-273NMYXE.js +605 -0
  5. package/vendor/{chunk-VPC5NLZG.js → chunk-4DHYSJJT.js} +1 -1
  6. package/vendor/{chunk-HK2H3MVE.js → chunk-53ZFCDHP.js} +4 -0
  7. package/vendor/{chunk-YCDEMYY6.js → chunk-54UL4U2E.js} +261 -110
  8. package/vendor/{chunk-X6M525ZJ.js → chunk-64AST7WZ.js} +5 -5
  9. package/vendor/{chunk-JKOG52PE.js → chunk-7FSHVVTZ.js} +1 -1
  10. package/vendor/chunk-7HLNJ2BI.js +1669 -0
  11. package/vendor/chunk-ALJUSOF7.js +175 -0
  12. package/vendor/{chunk-A6WMU2GG.js → chunk-AOZ3LMTF.js} +5 -4
  13. package/vendor/{chunk-KUIWH33N.js → chunk-AVQCUFYQ.js} +1 -1
  14. package/vendor/{chunk-JJNLH5GA.js → chunk-BYN6KXNP.js} +21 -19
  15. package/vendor/{chunk-PY5LYLV7.js → chunk-DWWMBGHX.js} +26 -21
  16. package/vendor/chunk-E6YVGIEW.js +12518 -0
  17. package/vendor/{chunk-C3N4N5HR.js → chunk-EEBIYWTE.js} +26 -21
  18. package/vendor/{chunk-YOFI4PCH.js → chunk-F77ZTTNS.js} +7 -1
  19. package/vendor/{chunk-RVYJKKWA.js → chunk-F7AMEDDU.js} +5 -4
  20. package/vendor/{chunk-473OA62O.js → chunk-FSNLU46W.js} +218 -12497
  21. package/vendor/{chunk-2S3OGPUC.js → chunk-GY5GATZL.js} +2 -2
  22. package/vendor/chunk-ILQVLZ2I.js +50 -0
  23. package/vendor/{chunk-QIIKMG3M.js → chunk-IY2HRXOZ.js} +1 -5
  24. package/vendor/{chunk-ZUGNCQZE.js → chunk-JYK6UL6D.js} +22 -8
  25. package/vendor/chunk-KG3RANR4.js +75 -0
  26. package/vendor/{chunk-YJ6XUZT6.js → chunk-KRBZZ6GS.js} +23 -16
  27. package/vendor/{chunk-AFLKCQHF.js → chunk-L4RD3TAZ.js} +2 -2
  28. package/vendor/{chunk-XNFVSVBS.js → chunk-LHUMBHG7.js} +1 -1
  29. package/vendor/{chunk-J2L726BC.js → chunk-NGV45YWB.js} +3 -3
  30. package/vendor/{chunk-A4NKL2PK.js → chunk-OG7G6DIR.js} +1 -1
  31. package/vendor/{chunk-DXTAWHY3.js → chunk-OZU6JFB4.js} +8 -7
  32. package/vendor/chunk-QV3WPU7A.js +8 -0
  33. package/vendor/{chunk-ZXX4ZNJY.js → chunk-S6HD3MDU.js} +3 -2
  34. package/vendor/{chunk-NEWIOOM6.js → chunk-SQZ2OSP6.js} +3 -2
  35. package/vendor/{chunk-G4IIVVJO.js → chunk-T6UB5PNX.js} +70 -2
  36. package/vendor/{chunk-SKVYP7NY.js → chunk-T7OGE5E5.js} +8 -8
  37. package/vendor/{chunk-GELDEJJ2.js → chunk-TIBYKMRW.js} +173 -51
  38. package/vendor/{chunk-HFM6ROJL.js → chunk-TISYUUEJ.js} +1 -1
  39. package/vendor/{chunk-K2EIFEQF.js → chunk-TSAYTRX3.js} +1 -1
  40. package/vendor/{chunk-PT3AUPGE.js → chunk-UB6JCVQ3.js} +3 -1
  41. package/vendor/{chunk-NM5NXCVM.js → chunk-UCOHFZ77.js} +626 -996
  42. package/vendor/{chunk-2BWTLF7A.js → chunk-UIMUUIH7.js} +45 -21
  43. package/vendor/{chunk-HZJK5RWC.js → chunk-USHFSJT7.js} +695 -280
  44. package/vendor/chunk-VGL5AZN5.js +152 -0
  45. package/vendor/{chunk-TSRPHKAC.js → chunk-VLP72QWX.js} +16 -42
  46. package/vendor/chunk-W6632NOX.js +14 -0
  47. package/vendor/{chunk-YJWREXN6.js → chunk-WBMO7YCO.js} +1 -1
  48. package/vendor/chunk-XCO3RV3Z.js +11 -0
  49. package/vendor/chunk-XKXSC6YS.js +373 -0
  50. package/vendor/{chunk-YK4F4VY2.js → chunk-Y6GE52OP.js} +51 -30
  51. package/vendor/{chunk-UI5RLBKQ.js → chunk-YZLQZU5E.js} +17 -1
  52. package/vendor/chunk-ZKKWLLPU.js +18 -0
  53. package/vendor/cli.js +1 -1
  54. package/vendor/component-manifest-catalog.js +2 -1
  55. package/vendor/control-plane.js +11 -6
  56. package/vendor/chunk-2DA7EFZV.js +0 -924
@@ -1,4 +1,7 @@
1
1
  import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ assertNoReleaseRuntime
4
+ } from "./chunk-YZLQZU5E.js";
2
5
  import "./chunk-BTS4ZTF3.js";
3
6
 
4
7
  // packages/koed-server/dist/runtime-homebrew.js
@@ -209,6 +212,7 @@ var linkRuntimePath = (source, target, koedHome, deps) => {
209
212
  deps.symlinkSync(source, resolvedTarget);
210
213
  };
211
214
  var installHomebrewRuntime = (paths, environment = process.env, dependencies = {}) => {
215
+ assertNoReleaseRuntime(paths);
212
216
  const deps = {
213
217
  platform: dependencies.platform ?? process.platform,
214
218
  existsSync: dependencies.existsSync ?? existsSync,
@@ -1,11 +1,30 @@
1
1
  import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ calculateRuntimeRequirements,
4
+ resolveEffectiveRuntimeConfig
5
+ } from "./chunk-L4RD3TAZ.js";
6
+ import {
7
+ redeemPairingLink
8
+ } from "./chunk-NGV45YWB.js";
9
+ import {
10
+ bundledPdsSecretProviderEnvironment
11
+ } from "./chunk-GY5GATZL.js";
12
+ import {
13
+ resolveLocalModelManifest
14
+ } from "./chunk-JYK6UL6D.js";
15
+ import {
16
+ invalidateUpstreamEnrollmentReferences
17
+ } from "./chunk-T7OGE5E5.js";
2
18
  import {
3
19
  collectKoedServerDoctor,
4
20
  collectKoedServerStartupStatus,
5
21
  collectKoedServerStatus,
6
22
  ensurePackagedLocalServiceSecrets,
23
+ hasCompletePostgresOverride,
7
24
  koedServerStartupBlockingComponentIds,
25
+ localServiceSecretsPath,
8
26
  migrateKoedOwnedCodexRegistrationBestEffort,
27
+ nativeLlamaServerOverride,
9
28
  pinAndResolvePackagedRuntime,
10
29
  provisionDesktopApiToken,
11
30
  provisionLocalApiToken,
@@ -21,77 +40,73 @@ import {
21
40
  startLocalPostgresRuntime,
22
41
  startLocalPrivacyRuntime,
23
42
  stopLocalPostgresRuntime
24
- } from "./chunk-HZJK5RWC.js";
43
+ } from "./chunk-USHFSJT7.js";
25
44
  import {
26
45
  resolveActiveIntegrationApiToken,
27
46
  resolveLocalApiToken,
28
47
  writeLocalAppCredential
29
48
  } from "./chunk-QT24SAW6.js";
30
- import {
31
- invalidateUpstreamEnrollmentReferences
32
- } from "./chunk-SKVYP7NY.js";
33
49
  import {
34
50
  allocateAndPersistLocalPorts
35
- } from "./chunk-HFM6ROJL.js";
36
- import {
37
- calculateRuntimeRequirements,
38
- resolveEffectiveRuntimeConfig
39
- } from "./chunk-AFLKCQHF.js";
40
- import {
41
- acquireKoedServerSupervisorLock,
42
- readCurrentRuntimeOwner,
43
- readSupervisorLock,
44
- releaseKoedServerSupervisorLock,
45
- resolveDesktopRuntimeOwner,
46
- resolveKoedServerConfig,
47
- resolveProcessIdentity,
48
- validateDesktopRuntimeCapability
49
- } from "./chunk-NM5NXCVM.js";
50
- import {
51
- isProcessRunning,
52
- isRuntimeGenerationState
53
- } from "./chunk-G4IIVVJO.js";
54
- import {
55
- maintainSupervisorLog,
56
- startKoedServerDaemon
57
- } from "./chunk-JKOG52PE.js";
58
- import {
59
- assertKoedAppRuntimeAvailable,
60
- resolveKoedAppRuntime,
61
- resolveKoedAppRuntimeExecution,
62
- resolveKoedRuntimeOwner
63
- } from "./chunk-A4NKL2PK.js";
64
- import {
65
- listUpstreamBackends,
66
- refreshUpstreamBackendCapabilities
67
- } from "./chunk-YJWREXN6.js";
51
+ } from "./chunk-TISYUUEJ.js";
68
52
  import {
69
- redeemPairingLink
70
- } from "./chunk-J2L726BC.js";
71
- import {
72
- bundledPdsSecretProviderEnvironment
73
- } from "./chunk-2S3OGPUC.js";
53
+ resolveKoedServerConfig
54
+ } from "./chunk-ALJUSOF7.js";
74
55
  import {
75
56
  ensureDeviceIdentity,
76
57
  inspectDeviceIdentityStatus,
77
58
  rotateDeviceIdentity
78
- } from "./chunk-XNFVSVBS.js";
59
+ } from "./chunk-LHUMBHG7.js";
60
+ import {
61
+ maintainSupervisorLog,
62
+ startKoedServerDaemon
63
+ } from "./chunk-7FSHVVTZ.js";
79
64
  import {
80
65
  ensureKoedHome,
81
66
  resolveKoedServerPaths
82
- } from "./chunk-K2EIFEQF.js";
67
+ } from "./chunk-TSAYTRX3.js";
68
+ import {
69
+ hasReleaseRuntime
70
+ } from "./chunk-YZLQZU5E.js";
83
71
  import {
84
72
  environmentWithRepoEnv,
85
73
  loadRepoEnv,
86
74
  resolveApiUrl
87
75
  } from "./chunk-W2HNI6AA.js";
76
+ import {
77
+ assertKoedAppRuntimeAvailable,
78
+ resolveKoedAppRuntime,
79
+ resolveKoedAppRuntimeExecution,
80
+ resolveKoedRuntimeOwner
81
+ } from "./chunk-OG7G6DIR.js";
82
+ import {
83
+ acquireKoedServerSupervisorLock,
84
+ observeStoppedRuntime,
85
+ readCurrentRuntimeOwner,
86
+ readSupervisorLock,
87
+ releaseKoedServerSupervisorLock,
88
+ removeStaleGenerationPin,
89
+ removeStaleRuntimeRecords,
90
+ resolveDesktopRuntimeOwner,
91
+ resolveProcessIdentity,
92
+ validateDesktopRuntimeCapability,
93
+ withLifecycleLock,
94
+ withSourceNativeStartLock
95
+ } from "./chunk-UCOHFZ77.js";
96
+ import {
97
+ isProcessRunning,
98
+ isRuntimeGenerationState,
99
+ removeOwnedRuntimeState,
100
+ writeRuntimeState
101
+ } from "./chunk-T6UB5PNX.js";
102
+ import {
103
+ listUpstreamBackends,
104
+ refreshUpstreamBackendCapabilities
105
+ } from "./chunk-WBMO7YCO.js";
88
106
  import {
89
107
  createPdsApplicationSecretStore,
90
108
  isPrivateNetworkIpv4Address
91
- } from "./chunk-473OA62O.js";
92
- import {
93
- resolveLocalModelManifest
94
- } from "./chunk-ZUGNCQZE.js";
109
+ } from "./chunk-E6YVGIEW.js";
95
110
 
96
111
  // packages/koed-server/dist/personal-device-request.js
97
112
  import { createHash as createHash2, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "node:crypto";
@@ -599,6 +614,25 @@ var defaultCheckPid = (pid) => {
599
614
  return false;
600
615
  }
601
616
  };
617
+ var defaultIsProcessGroupLeader = (pid) => {
618
+ try {
619
+ const stat = readFileSync2(`/proc/${pid}/stat`, "utf8");
620
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
621
+ return Number(fields[2]) === pid;
622
+ } catch {
623
+ return false;
624
+ }
625
+ };
626
+ var removeStaleRecordsLocked = (paths, observation) => {
627
+ if (observation.state !== "stopped" || !observation.staleRecords?.length)
628
+ return void 0;
629
+ try {
630
+ withLifecycleLock(paths, () => removeStaleRuntimeRecords(observation));
631
+ return void 0;
632
+ } catch (error) {
633
+ return `Stale runtime records were left in place: ${errorMessage(error)}`;
634
+ }
635
+ };
602
636
  var errorCode = (error) => typeof error === "object" && error !== null && "code" in error ? String(error.code) : "";
603
637
  var errorMessage = (error) => error instanceof Error ? error.message : String(error);
604
638
  var defaultSleepSync = (ms) => {
@@ -634,15 +668,16 @@ var stopPid = (label, pid, deps) => {
634
668
  return { stoppedPids: [], missingPids: [pid], errors: [] };
635
669
  if (!identityMatches())
636
670
  return identityError();
671
+ const target = deps.processGroup ? -pid : pid;
637
672
  try {
638
- deps.kill(pid, "SIGTERM");
639
- if (waitForPidExit(pid, deps)) {
673
+ deps.kill(target, "SIGTERM");
674
+ if (waitForPidExit(target, deps)) {
640
675
  return { stoppedPids: [pid], missingPids: [], errors: [] };
641
676
  }
642
677
  if (!identityMatches())
643
678
  return identityError();
644
- deps.kill(pid, "SIGKILL");
645
- if (waitForPidExit(pid, deps)) {
679
+ deps.kill(target, "SIGKILL");
680
+ if (waitForPidExit(target, deps)) {
646
681
  return { stoppedPids: [pid], missingPids: [], errors: [] };
647
682
  }
648
683
  return {
@@ -669,19 +704,24 @@ var stopPid = (label, pid, deps) => {
669
704
  var shouldStopNativePostgres = (runtime) => runtime.dependencyMode === "bundled-local" && runtime.services.includes("postgres-native");
670
705
  var stopKoedServer = ({ environment = process.env, existsSync: pathExists = nodeExistsSync, readFileSync: readFile = readFileSync2, rmSync: remove = rmSync2, spawnSync = nodeSpawnSync, kill = (pid, signal) => {
671
706
  process.kill(pid, signal);
672
- }, checkPid = defaultCheckPid, waitForExitMs = 5e3, pollIntervalMs = 100, sleepSync = defaultSleepSync, readSupervisorLock: readLock = readSupervisorLock, resolveProcessIdentity: resolveProcessIdentity2 = resolveProcessIdentity, desktopRuntimeCapability } = {}) => {
707
+ }, checkPid = defaultCheckPid, waitForExitMs: requestedWait, pollIntervalMs = 100, sleepSync = defaultSleepSync, readSupervisorLock: readLock = readSupervisorLock, resolveProcessIdentity: resolveProcessIdentity2 = resolveProcessIdentity, isProcessGroupLeader = defaultIsProcessGroupLeader, desktopRuntimeCapability } = {}) => {
673
708
  const paths = resolveKoedServerPaths(environment);
709
+ const waitForExitMs = requestedWait ?? 5e3;
710
+ const releaseManaged = hasReleaseRuntime(paths);
674
711
  const runtimeEnvironment = environmentWithRepoEnv(paths.repoRoot, environment);
675
712
  const runtime = readRuntimeState(paths.runtimeStatePath, {
676
713
  existsSync: pathExists,
677
714
  readFileSync: readFile
678
715
  });
679
716
  if (!runtime) {
717
+ const observation = releaseManaged ? observeStoppedRuntime(paths) : void 0;
718
+ const cleanupError = observation ? removeStaleRecordsLocked(paths, observation) : void 0;
719
+ const uncertain = observation && observation.state !== "stopped" || !!cleanupError;
680
720
  return {
681
- ok: true,
682
- state: "not_configured",
721
+ ok: !uncertain,
722
+ state: uncertain ? "needs_attention" : "not_configured",
683
723
  koedHome: paths.koedHome,
684
- message: "No koed runtime state was found.",
724
+ message: cleanupError ?? (uncertain ? observation.message : "No koed runtime state was found."),
685
725
  stoppedPids: [],
686
726
  missingPids: [],
687
727
  stoppedServices: [],
@@ -712,11 +752,31 @@ var stopKoedServer = ({ environment = process.env, existsSync: pathExists = node
712
752
  error: "Supervisor identity changed during stop; refusing fallback signals"
713
753
  });
714
754
  };
755
+ let supervisorExitChecked = false;
756
+ const noteExitedSupervisor = () => {
757
+ if (supervisorExitChecked)
758
+ return;
759
+ supervisorExitChecked = true;
760
+ for (const [name, pid] of Object.entries(runtime.processes ?? {})) {
761
+ if (typeof pid !== "number" || pid <= 0)
762
+ continue;
763
+ if (checkPid(pid))
764
+ errors.push({
765
+ target: `${name} (${pid})`,
766
+ error: "Supervisor exited; refusing to signal a recorded child without supervisor identity"
767
+ });
768
+ else
769
+ missingPids.push(pid);
770
+ }
771
+ };
715
772
  const canSignalFallbackProcesses = () => {
716
773
  if (!supervisorLockMatches)
717
774
  return false;
718
775
  if (expectedSupervisorIdentity && !isExpectedSupervisorRunning(expectedSupervisorIdentity)) {
719
- markSupervisorIdentityUnverified();
776
+ if (runtime.pid > 0 && !checkPid(runtime.pid))
777
+ noteExitedSupervisor();
778
+ else
779
+ markSupervisorIdentityUnverified();
720
780
  return false;
721
781
  }
722
782
  return true;
@@ -730,7 +790,7 @@ var stopKoedServer = ({ environment = process.env, existsSync: pathExists = node
730
790
  const lock = readLock(supervisorLockPath);
731
791
  const supervisorRunning = runtime.pid > 0 && checkPid(runtime.pid);
732
792
  const processIdentity = supervisorRunning ? resolveProcessIdentity2(runtime.pid) : null;
733
- if (ownerPinRequired && !pin || pinExists && !pin || pin !== null && (pin.pid !== runtime.pid || !ownersMatch(pin.owner, owner) || lock?.pid !== runtime.pid || !lock.processIdentity || pin.processIdentity !== lock.processIdentity || supervisorRunning && processIdentity !== pin.processIdentity)) {
793
+ if (lock?.sourceOwner && !ownersMatch(lock.sourceOwner, owner) || ownerPinRequired && !pin || pinExists && !pin || pin !== null && (pin.pid !== runtime.pid || !ownersMatch(pin.owner, owner) || lock?.pid !== runtime.pid || !lock.processIdentity || pin.processIdentity !== lock.processIdentity || supervisorRunning && processIdentity !== pin.processIdentity)) {
734
794
  supervisorLockMatches = false;
735
795
  errors.push({
736
796
  target: `supervisor (${runtime.pid})`,
@@ -768,7 +828,9 @@ var stopKoedServer = ({ environment = process.env, existsSync: pathExists = node
768
828
  });
769
829
  supervisorStoppedGracefully = waitForPidExit(runtime.pid, {
770
830
  checkPid,
771
- waitForExitMs,
831
+ // Let the supervisor finish its bounded per-child shutdown before falling
832
+ // back to direct PID signals, which cannot reach llama-server descendants.
833
+ waitForExitMs: requestedWait ?? 6e4,
772
834
  pollIntervalMs,
773
835
  sleepSync
774
836
  });
@@ -809,16 +871,27 @@ var stopKoedServer = ({ environment = process.env, existsSync: pathExists = node
809
871
  }
810
872
  if (runtime.dependencyMode === "bundled-local") {
811
873
  const embeddingPid = runtime.processes?.embeddingService;
874
+ const embeddingIdentity = runtime.processIdentities?.embeddingService;
812
875
  if (canSignalFallbackProcesses() && runtime.services.includes("embedding-service-native")) {
813
876
  if (!embeddingPid || embeddingPid <= 0) {
814
877
  missingServices.push("embedding-service-native");
878
+ } else if (releaseManaged && !embeddingIdentity) {
879
+ errors.push({
880
+ target: `embedding-service-native (${embeddingPid})`,
881
+ error: "Embedding Service process identity is missing; refusing to signal it"
882
+ });
815
883
  } else {
816
884
  const stopped = stopPid("embedding-service-native", embeddingPid, {
817
885
  kill,
818
886
  checkPid,
819
887
  waitForExitMs,
820
888
  pollIntervalMs,
821
- sleepSync
889
+ sleepSync,
890
+ ...embeddingIdentity ? {
891
+ expectedProcessIdentity: embeddingIdentity,
892
+ resolveProcessIdentity: resolveProcessIdentity2
893
+ } : {},
894
+ processGroup: releaseManaged && embeddingIdentity !== void 0 && checkPid(embeddingPid) && resolveProcessIdentity2(embeddingPid) === embeddingIdentity && isProcessGroupLeader(embeddingPid)
822
895
  });
823
896
  stoppedPids.push(...stopped.stoppedPids);
824
897
  missingPids.push(...stopped.missingPids);
@@ -866,18 +939,26 @@ var stopKoedServer = ({ environment = process.env, existsSync: pathExists = node
866
939
  }
867
940
  }
868
941
  if (errors.length === 0) {
869
- const currentRuntime = readRuntimeState(paths.runtimeStatePath, {
870
- existsSync: pathExists,
871
- readFileSync: readFile
872
- });
873
- if (currentRuntime && (currentRuntime.pid !== runtime.pid || currentRuntime.startedAt !== runtime.startedAt)) {
942
+ try {
943
+ if (!removeOwnedRuntimeState(paths.runtimeStatePath, runtime, readFile, remove))
944
+ errors.push({
945
+ target: "runtime-state",
946
+ error: "Runtime state changed while stop was in progress"
947
+ });
948
+ } catch (error) {
949
+ errors.push({ target: "runtime-state", error: errorMessage(error) });
950
+ }
951
+ }
952
+ if (releaseManaged && errors.length === 0) {
953
+ const observation = observeStoppedRuntime(paths);
954
+ const cleanupError = removeStaleRecordsLocked(paths, observation);
955
+ if (cleanupError)
956
+ errors.push({ target: "runtime records", error: cleanupError });
957
+ if (observation.state !== "stopped")
874
958
  errors.push({
875
- target: "runtime-state",
876
- error: "Runtime state changed while stop was in progress"
959
+ target: observation.pid ? `native process (${observation.pid})` : "native runtime",
960
+ error: observation.message
877
961
  });
878
- } else {
879
- remove(paths.runtimeStatePath, { force: true });
880
- }
881
962
  }
882
963
  return {
883
964
  ok: errors.length === 0,
@@ -1026,11 +1107,11 @@ var maintainUpstreamCapabilities = (paths, options = {}) => {
1026
1107
  import { spawn as nodeSpawn2, spawnSync as nodeSpawnSync2 } from "node:child_process";
1027
1108
  import { randomBytes as randomBytes3 } from "node:crypto";
1028
1109
  import { setTimeout as delay } from "node:timers/promises";
1029
- import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "node:fs";
1110
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3 } from "node:fs";
1030
1111
  import { dirname, resolve as resolve4 } from "node:path";
1031
1112
 
1032
1113
  // packages/koed-server/dist/runtime-lifecycle.js
1033
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
1114
+ import { existsSync as existsSync2, lstatSync as lstatSync2, readFileSync as readFileSync3 } from "node:fs";
1034
1115
  import { resolve as resolve3 } from "node:path";
1035
1116
  var readJson = (path) => {
1036
1117
  try {
@@ -1070,17 +1151,19 @@ function observeRuntimeLifecycle(paths, { resolveProcessIdentity: resolveProcess
1070
1151
  message: "Koed is not running."
1071
1152
  };
1072
1153
  const epoch = `${lock.pid}:${identity}`;
1073
- const pin = readJson(paths.generationStatePath ?? resolve3(paths.runDir, "runtime-generation.json"));
1154
+ const pinPath = paths.generationStatePath ?? resolve3(paths.runDir, "runtime-generation.json");
1155
+ const pin = readJson(pinPath);
1074
1156
  const pinned = isRuntimeGenerationState(pin) && pin.pid === lock.pid && pin.processIdentity === identity ? pin : null;
1075
1157
  const runtime = readJson(paths.runtimeStatePath);
1076
- const running = pinned !== null && runtime?.pid === lock.pid;
1158
+ const owner = pinned?.owner ?? (!lstatSync2(pinPath, { throwIfNoEntry: false }) ? lock.sourceOwner : null);
1159
+ const running = !!owner && runtime?.pid === lock.pid;
1077
1160
  return {
1078
1161
  state: running ? "running" : "starting",
1079
1162
  epoch,
1080
1163
  message: running ? "Koed is running." : "Koed is starting.",
1081
1164
  pid: lock.pid,
1082
1165
  processIdentity: identity,
1083
- owner: pinned ? { ...pinned.owner } : null,
1166
+ owner: owner ? { ...owner } : null,
1084
1167
  ...pinned ? { generationId: pinned.generationId } : {}
1085
1168
  };
1086
1169
  }
@@ -1320,15 +1403,62 @@ var waitForChildExit = (child, timeoutMs) => new Promise((resolveExit) => {
1320
1403
  const timeout = setTimeout(() => finish(false), timeoutMs);
1321
1404
  child.once("exit", onExit);
1322
1405
  });
1323
- var stopChildProcess = async (child, timeoutMs = 5e3, label = "managed child") => {
1324
- if (!child?.pid || child.exitCode != null || child.signalCode != null)
1406
+ var processGroupAlive = (pid) => {
1407
+ try {
1408
+ process.kill(-pid, 0);
1409
+ return true;
1410
+ } catch (error) {
1411
+ const code = error.code;
1412
+ if (code === "ESRCH")
1413
+ return false;
1414
+ if (code === "EPERM")
1415
+ return true;
1416
+ throw error;
1417
+ }
1418
+ };
1419
+ var signalProcessGroup = (pid, value) => {
1420
+ if (!processGroupAlive(pid))
1325
1421
  return;
1326
- child.kill("SIGTERM");
1327
- if (await waitForChildExit(child, timeoutMs))
1422
+ try {
1423
+ process.kill(-pid, value);
1424
+ } catch (error) {
1425
+ if (error.code !== "ESRCH")
1426
+ throw error;
1427
+ }
1428
+ };
1429
+ var waitForProcessGroupExit = async (pid, timeoutMs) => {
1430
+ const deadline = Date.now() + timeoutMs;
1431
+ while (processGroupAlive(pid)) {
1432
+ if (Date.now() >= deadline)
1433
+ return false;
1434
+ await delay(Math.min(50, Math.max(1, deadline - Date.now())));
1435
+ }
1436
+ return true;
1437
+ };
1438
+ var stopChildProcess = async (child, timeoutMs = 5e3, label = "managed child", privateGroup = false) => {
1439
+ if (!child?.pid)
1328
1440
  return;
1329
- child.kill("SIGKILL");
1330
- if (!await waitForChildExit(child, timeoutMs)) {
1331
- throw new Error(`Timed out stopping ${label} process ${child.pid}.`);
1441
+ const pid = child.pid;
1442
+ const exited = () => child.exitCode != null || child.signalCode != null;
1443
+ if (!privateGroup) {
1444
+ if (exited())
1445
+ return;
1446
+ child.kill("SIGTERM");
1447
+ if (await waitForChildExit(child, timeoutMs))
1448
+ return;
1449
+ child.kill("SIGKILL");
1450
+ if (!await waitForChildExit(child, timeoutMs))
1451
+ throw new Error(`Timed out stopping ${label} process ${child.pid}.`);
1452
+ return;
1453
+ }
1454
+ const deadline = Date.now() + timeoutMs;
1455
+ signalProcessGroup(pid, "SIGTERM");
1456
+ await waitForChildExit(child, timeoutMs);
1457
+ if (exited() && await waitForProcessGroupExit(pid, Math.max(0, deadline - Date.now())))
1458
+ return;
1459
+ signalProcessGroup(pid, "SIGKILL");
1460
+ if (!await waitForChildExit(child, timeoutMs) || !await waitForProcessGroupExit(pid, timeoutMs)) {
1461
+ throw new Error(`Timed out stopping ${label} process group ${pid}.`);
1332
1462
  }
1333
1463
  };
1334
1464
  var createManagedProcessMonitor = (options = {}) => {
@@ -1395,12 +1525,16 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1395
1525
  const startupId = randomBytes3(12).toString("hex");
1396
1526
  const startupStartedAt = process.hrtime.bigint();
1397
1527
  const emitStartupMilestone = (milestone) => {
1398
- console.log(JSON.stringify({
1528
+ const line = JSON.stringify({
1399
1529
  event: "koed.supervisor.startup",
1400
1530
  startupId,
1401
1531
  milestone,
1402
1532
  elapsedMs: Number(process.hrtime.bigint() - startupStartedAt) / 1e6
1403
- }));
1533
+ });
1534
+ console.log(line);
1535
+ if (process.env.KOED_SUPERVISOR_STARTUP_TRACE === "1")
1536
+ process.stderr.write(`${line}
1537
+ `);
1404
1538
  };
1405
1539
  emitStartupMilestone("supervisor_entry");
1406
1540
  const execution = resolveKoedAppRuntimeExecution();
@@ -1422,7 +1556,10 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1422
1556
  };
1423
1557
  assertObservedOwner(observeRuntimeLifecycle(paths));
1424
1558
  ensureKoedHome(paths);
1425
- const supervisorLock = acquireKoedServerSupervisorLock(paths);
1559
+ const supervisorLock = acquireKoedServerSupervisorLock(paths, {
1560
+ ...execution === "source" ? { sourceOwner: resolveKoedRuntimeOwner() } : {},
1561
+ exclusive: (action) => withLifecycleLock(paths, action)
1562
+ });
1426
1563
  if (!supervisorLock.acquired) {
1427
1564
  assertObservedOwner(observeRuntimeLifecycle(paths));
1428
1565
  console.log(JSON.stringify({
@@ -1452,6 +1589,12 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1452
1589
  throw error;
1453
1590
  }
1454
1591
  };
1592
+ if (execution === "source") {
1593
+ startupPhase = "stale generation pin cleanup";
1594
+ await initializeUnderSupervisorLock(() => {
1595
+ removeStaleGenerationPin(paths);
1596
+ });
1597
+ }
1455
1598
  startupPhase = "device identity initialization";
1456
1599
  await initializeUnderSupervisorLock(() => ensureDeviceIdentity(paths, { environment }));
1457
1600
  const supervisorStartedAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -1466,10 +1609,11 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1466
1609
  };
1467
1610
  const desktopManagedLocal = environment.KOED_AUTO_PORTS === "1";
1468
1611
  const startupConfig = effectiveRuntimeConfig.config;
1612
+ const bundledPersonal = startupConfig.runtimeMode === "local-personal" && startupConfig.dependencyMode === "bundled-local";
1469
1613
  startupPhase = "packaged local service secrets";
1470
- environment = await initializeUnderSupervisorLock(() => ensurePackagedLocalServiceSecrets(paths, execution === "packaged" || startupConfig.runtimeMode === "local-personal" && startupConfig.dependencyMode === "bundled-local", environment));
1614
+ environment = await initializeUnderSupervisorLock(() => ensurePackagedLocalServiceSecrets(paths, execution === "packaged" || bundledPersonal, environment));
1471
1615
  mkdirSync3(paths.logsDir, { recursive: true, mode: 448 });
1472
- if (startupConfig.runtimeMode === "local-personal" && startupConfig.dependencyMode === "bundled-local" && environment.KOED_AUTO_PORTS === void 0) {
1616
+ if (bundledPersonal && environment.KOED_AUTO_PORTS === void 0) {
1473
1617
  environment = { ...environment, KOED_AUTO_PORTS: "1" };
1474
1618
  }
1475
1619
  const portAllocationEnvironment = { ...environment };
@@ -1533,7 +1677,10 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1533
1677
  const childEnv = initialServiceEnv;
1534
1678
  if (execution === "source") {
1535
1679
  startupPhase = "source environment preparation";
1536
- runCommand(paths, "Prepare Koed environment", process.execPath, [resolve4(paths.repoRoot, "scripts/setup-env.mjs")], childEnv, spawnSync);
1680
+ runCommand(paths, "Prepare Koed environment", process.execPath, [
1681
+ resolve4(paths.repoRoot, "scripts/setup-env.mjs"),
1682
+ ...bundledPersonal ? ["--local-service-secrets", localServiceSecretsPath(paths)] : []
1683
+ ], childEnv, spawnSync);
1537
1684
  }
1538
1685
  startupPhase = "refreshed repository environment and credentials";
1539
1686
  const refreshedRepoEnv = await initializeUnderSupervisorLock(() => execution === "source" || environment.KOED_ENV_PATH?.trim() ? loadRepoEnv(paths.repoRoot, environment) : {});
@@ -1570,14 +1717,6 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1570
1717
  let runtimeStateWritten = false;
1571
1718
  let stopSupervisorExitMonitor = () => void 0;
1572
1719
  let stopCapabilityMaintenance = () => void 0;
1573
- const runtimeStateOwnedByCurrentProcess = () => {
1574
- try {
1575
- const runtime = JSON.parse(readFileSync4(paths.runtimeStatePath, "utf8"));
1576
- return runtime.pid === process.pid && runtime.startedAt === supervisorStartedAt;
1577
- } catch {
1578
- return false;
1579
- }
1580
- };
1581
1720
  let deviceRequestService;
1582
1721
  let cleanupPromise;
1583
1722
  let cleanupCompleted = false;
@@ -1601,14 +1740,14 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1601
1740
  ];
1602
1741
  for (const name of shutdownOrder) {
1603
1742
  try {
1604
- await stopChildProcess(managedChildren[name], 5e3, name);
1743
+ await stopChildProcess(managedChildren[name], 5e3, name, name === "embeddingService" && Boolean(paths.nativeSelectionRoot));
1605
1744
  } catch (error) {
1606
1745
  cleanupErrors.push(error instanceof Error ? error.message : String(error));
1607
1746
  }
1608
1747
  }
1609
1748
  if (nativeEmbeddingProcess && !Object.values(managedChildren).includes(nativeEmbeddingProcess)) {
1610
1749
  try {
1611
- await stopChildProcess(nativeEmbeddingProcess, 5e3, "embeddingService");
1750
+ await stopChildProcess(nativeEmbeddingProcess, 5e3, "embeddingService", Boolean(paths.nativeSelectionRoot));
1612
1751
  } catch (error) {
1613
1752
  cleanupErrors.push(error instanceof Error ? error.message : String(error));
1614
1753
  }
@@ -1689,6 +1828,13 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1689
1828
  appRuntime = resolveKoedAppRuntime(paths, environment, existsSync3, void 0, requiredRuntime);
1690
1829
  assertKoedAppRuntimeAvailable(appRuntime, paths);
1691
1830
  }
1831
+ if (useBundledLocalDependencies && hasReleaseRuntime(paths) && !(hasCompletePostgresOverride(refreshedEnv) && nativeLlamaServerOverride(refreshedEnv))) {
1832
+ const { resolveSelectedCoreForStart } = await import("./chunk-273NMYXE.js");
1833
+ const admitSelection = () => resolveSelectedCoreForStart(paths, refreshedEnv, !nativeLlamaServerOverride(refreshedEnv));
1834
+ const selected = generationPin ? admitSelection() : withSourceNativeStartLock(paths, admitSelection);
1835
+ if (selected)
1836
+ paths.nativeSelectionRoot = selected;
1837
+ }
1692
1838
  if (appRuntime.kind === "source") {
1693
1839
  runCommand(paths, "Check source runtime artifacts", process.execPath, [
1694
1840
  resolve4(paths.repoRoot, "scripts/source-runtime-build.mjs"),
@@ -1766,6 +1912,7 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1766
1912
  const api = appRuntime.kind === "packaged" ? spawnManagedProcess(paths, "API", process.execPath, [appRuntime.apiEntry], appProcessEnvironment(refreshedEnv), spawn, resolve4(appRuntime.root, "api")) : spawnManagedProcess(paths, "API", process.execPath, [resolve4(paths.repoRoot, "apps/api/dist/index.js")], appProcessEnvironment(refreshedEnv), spawn, resolve4(paths.repoRoot, "apps/api"));
1767
1913
  manageChild("api", api);
1768
1914
  emitStartupMilestone("api_process_spawned");
1915
+ const embeddingIdentity = paths.nativeSelectionRoot && nativeEmbeddingProcess?.pid ? resolveProcessIdentity(nativeEmbeddingProcess.pid) : null;
1769
1916
  const runtime = {
1770
1917
  pid: process.pid,
1771
1918
  startedAt: supervisorStartedAt,
@@ -1778,6 +1925,9 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1778
1925
  claudeTranscriptWatcherEnabled: config.claudeTranscriptWatcherEnabled,
1779
1926
  piTranscriptWatcherEnabled: config.piTranscriptWatcherEnabled,
1780
1927
  services: [...runtimeServices, "api"],
1928
+ // The release-managed Embedding Service leads a private process group.
1929
+ // koed stop signals that group only while its leader keeps this identity.
1930
+ ...embeddingIdentity ? { processIdentities: { embeddingService: embeddingIdentity } } : {},
1781
1931
  processes: {
1782
1932
  ...nativeEmbeddingProcess ? { embeddingService: nativeEmbeddingProcess.pid ?? 0 } : {},
1783
1933
  ...nativePrivacyProcess ? { privacyService: nativePrivacyProcess.pid ?? 0 } : {},
@@ -1785,10 +1935,7 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1785
1935
  }
1786
1936
  };
1787
1937
  const persistRuntime = () => {
1788
- writeFileSync2(paths.runtimeStatePath, `${JSON.stringify(runtime, null, 2)}
1789
- `, {
1790
- mode: 384
1791
- });
1938
+ writeRuntimeState(paths.runtimeStatePath, runtime);
1792
1939
  runtimeStateWritten = true;
1793
1940
  };
1794
1941
  persistRuntime();
@@ -1881,7 +2028,7 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1881
2028
  }
1882
2029
  emitStartupMilestone("core_services_ready");
1883
2030
  startupReady = true;
1884
- onReady?.();
2031
+ onReady?.(refreshedEnv);
1885
2032
  console.log(JSON.stringify(status, null, 2));
1886
2033
  emitStartupMilestone("final_supervisor_status_emitted");
1887
2034
  console.log("Koed server supervisor is running. Press Ctrl-C to stop local app processes.");
@@ -1898,9 +2045,6 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1898
2045
  emitStartupMilestone("startup_failed");
1899
2046
  try {
1900
2047
  await cleanupStartedResources();
1901
- if (runtimeStateOwnedByCurrentProcess()) {
1902
- rmSync3(paths.runtimeStatePath, { force: true });
1903
- }
1904
2048
  } catch (cleanupError) {
1905
2049
  throw new Error(`${error instanceof Error ? error.message : String(error)} Cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`, { cause: cleanupError });
1906
2050
  }
@@ -1913,8 +2057,15 @@ var startKoedServer = async ({ environment = process.env, pollIntervalMs = 500,
1913
2057
  process.off("SIGTERM", shutdown);
1914
2058
  signal?.removeEventListener("abort", shutdown);
1915
2059
  managedProcessMonitor.dispose();
1916
- if (runtimeStateWritten && runtimeStateOwnedByCurrentProcess()) {
1917
- rmSync3(paths.runtimeStatePath, { force: true });
2060
+ if (runtimeStateWritten) {
2061
+ try {
2062
+ removeOwnedRuntimeState(paths.runtimeStatePath, {
2063
+ pid: process.pid,
2064
+ startedAt: supervisorStartedAt
2065
+ });
2066
+ } catch (error) {
2067
+ console.warn(`Could not clear runtime state: ${error instanceof Error ? error.message : String(error)}`);
2068
+ }
1918
2069
  }
1919
2070
  if (sourceRuntimeLeaseAcquired) {
1920
2071
  try {
@@ -2018,7 +2169,7 @@ var createCliServiceContext = ({ collectStatus = collectKoedServerStatus, collec
2018
2169
  };
2019
2170
 
2020
2171
  // packages/koed-server/dist/cli-service-output.js
2021
- import { existsSync as existsSync4, mkdirSync as mkdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
2172
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4, writeFileSync as writeFileSync2 } from "node:fs";
2022
2173
  import { resolve as resolve5 } from "node:path";
2023
2174
  var safeLifecycle = (paths) => {
2024
2175
  try {
@@ -2040,7 +2191,7 @@ var persistDoctorVerification = (paths, doctor) => {
2040
2191
  recursive: true,
2041
2192
  mode: 448
2042
2193
  });
2043
- writeFileSync3(paths.lastVerificationPath, `${JSON.stringify({
2194
+ writeFileSync2(paths.lastVerificationPath, `${JSON.stringify({
2044
2195
  ok: doctor.ok,
2045
2196
  checkedAt: doctor.generatedAt,
2046
2197
  message: doctor.summary