@cotal-ai/cli 0.173.0 → 0.174.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 (157) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +17 -9
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +22 -11
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/channel-members.d.ts.map +1 -1
  8. package/dist/commands/channel-members.js +29 -2
  9. package/dist/commands/channel-members.js.map +1 -1
  10. package/dist/commands/channels.js +5 -1
  11. package/dist/commands/channels.js.map +1 -1
  12. package/dist/commands/clean.d.ts +1 -0
  13. package/dist/commands/clean.d.ts.map +1 -1
  14. package/dist/commands/clean.js +19 -3
  15. package/dist/commands/clean.js.map +1 -1
  16. package/dist/commands/doctor.d.ts.map +1 -1
  17. package/dist/commands/doctor.js +31 -12
  18. package/dist/commands/doctor.js.map +1 -1
  19. package/dist/commands/ext.d.ts.map +1 -1
  20. package/dist/commands/ext.js +22 -5
  21. package/dist/commands/ext.js.map +1 -1
  22. package/dist/commands/help.d.ts +1 -1
  23. package/dist/commands/help.js +1 -1
  24. package/dist/commands/history.d.ts +10 -2
  25. package/dist/commands/history.d.ts.map +1 -1
  26. package/dist/commands/history.js +21 -9
  27. package/dist/commands/history.js.map +1 -1
  28. package/dist/commands/join.js +5 -1
  29. package/dist/commands/join.js.map +1 -1
  30. package/dist/commands/mint-endpoint-caller.d.ts.map +1 -1
  31. package/dist/commands/mint-endpoint-caller.js +13 -2
  32. package/dist/commands/mint-endpoint-caller.js.map +1 -1
  33. package/dist/commands/mint.d.ts.map +1 -1
  34. package/dist/commands/mint.js +10 -2
  35. package/dist/commands/mint.js.map +1 -1
  36. package/dist/commands/persona.js +3 -3
  37. package/dist/commands/persona.js.map +1 -1
  38. package/dist/commands/personas.js +1 -1
  39. package/dist/commands/personas.js.map +1 -1
  40. package/dist/commands/send.d.ts.map +1 -1
  41. package/dist/commands/send.js +10 -6
  42. package/dist/commands/send.js.map +1 -1
  43. package/dist/commands/setup.d.ts.map +1 -1
  44. package/dist/commands/setup.js +17 -1
  45. package/dist/commands/setup.js.map +1 -1
  46. package/dist/commands/space.js +1 -1
  47. package/dist/commands/space.js.map +1 -1
  48. package/dist/commands/spawn-managed-launch.d.ts.map +1 -1
  49. package/dist/commands/spawn-managed-launch.js +6 -4
  50. package/dist/commands/spawn-managed-launch.js.map +1 -1
  51. package/dist/commands/spawn-preview.d.ts.map +1 -1
  52. package/dist/commands/spawn-preview.js +3 -0
  53. package/dist/commands/spawn-preview.js.map +1 -1
  54. package/dist/commands/stack-up.d.ts.map +1 -1
  55. package/dist/commands/stack-up.js +13 -6
  56. package/dist/commands/stack-up.js.map +1 -1
  57. package/dist/commands/status.d.ts.map +1 -1
  58. package/dist/commands/status.js +17 -22
  59. package/dist/commands/status.js.map +1 -1
  60. package/dist/commands/team-deploy-apply.d.ts.map +1 -1
  61. package/dist/commands/team-deploy-apply.js +0 -2
  62. package/dist/commands/team-deploy-apply.js.map +1 -1
  63. package/dist/commands/up-pending.d.ts +24 -0
  64. package/dist/commands/up-pending.d.ts.map +1 -0
  65. package/dist/commands/up-pending.js +5 -0
  66. package/dist/commands/up-pending.js.map +1 -0
  67. package/dist/commands/up.d.ts +1 -1
  68. package/dist/commands/up.d.ts.map +1 -1
  69. package/dist/commands/up.js +45 -50
  70. package/dist/commands/up.js.map +1 -1
  71. package/dist/commands/update-continuity.d.ts +47 -0
  72. package/dist/commands/update-continuity.d.ts.map +1 -0
  73. package/dist/commands/update-continuity.js +430 -0
  74. package/dist/commands/update-continuity.js.map +1 -0
  75. package/dist/commands/update-process.d.ts +26 -0
  76. package/dist/commands/update-process.d.ts.map +1 -0
  77. package/dist/commands/update-process.js +283 -0
  78. package/dist/commands/update-process.js.map +1 -0
  79. package/dist/commands/update-release.d.ts +32 -0
  80. package/dist/commands/update-release.d.ts.map +1 -0
  81. package/dist/commands/update-release.js +232 -0
  82. package/dist/commands/update-release.js.map +1 -0
  83. package/dist/commands/update.d.ts +6 -54
  84. package/dist/commands/update.d.ts.map +1 -1
  85. package/dist/commands/update.js +25 -949
  86. package/dist/commands/update.js.map +1 -1
  87. package/dist/commands/use.d.ts.map +1 -1
  88. package/dist/commands/use.js +4 -7
  89. package/dist/commands/use.js.map +1 -1
  90. package/dist/console/commands.js +2 -2
  91. package/dist/console/commands.js.map +1 -1
  92. package/dist/help.d.ts +1 -1
  93. package/dist/help.d.ts.map +1 -1
  94. package/dist/help.js +3 -1
  95. package/dist/help.js.map +1 -1
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +4 -3
  98. package/dist/index.js.map +1 -1
  99. package/dist/lib/choose-target.d.ts +2 -0
  100. package/dist/lib/choose-target.d.ts.map +1 -1
  101. package/dist/lib/choose-target.js +16 -1
  102. package/dist/lib/choose-target.js.map +1 -1
  103. package/dist/lib/credential-authority.d.ts +1 -1
  104. package/dist/lib/credential-authority.d.ts.map +1 -1
  105. package/dist/lib/credential-authority.js +8 -3
  106. package/dist/lib/credential-authority.js.map +1 -1
  107. package/dist/lib/foreground-hold.d.ts +2 -0
  108. package/dist/lib/foreground-hold.d.ts.map +1 -1
  109. package/dist/lib/foreground-hold.js +47 -1
  110. package/dist/lib/foreground-hold.js.map +1 -1
  111. package/dist/lib/mint-renewal.d.ts +5 -0
  112. package/dist/lib/mint-renewal.d.ts.map +1 -0
  113. package/dist/lib/mint-renewal.js +60 -0
  114. package/dist/lib/mint-renewal.js.map +1 -0
  115. package/dist/lib/persona-files.d.ts +1 -1
  116. package/dist/lib/persona-files.d.ts.map +1 -1
  117. package/dist/lib/persona-files.js +5 -5
  118. package/dist/lib/persona-files.js.map +1 -1
  119. package/dist/lib/restore-streams.d.ts +18 -0
  120. package/dist/lib/restore-streams.d.ts.map +1 -0
  121. package/dist/lib/restore-streams.js +275 -0
  122. package/dist/lib/restore-streams.js.map +1 -0
  123. package/dist/lib/restore.d.ts +2 -0
  124. package/dist/lib/restore.d.ts.map +1 -1
  125. package/dist/lib/restore.js +5 -273
  126. package/dist/lib/restore.js.map +1 -1
  127. package/dist/lib/self-exec.d.ts +5 -2
  128. package/dist/lib/self-exec.d.ts.map +1 -1
  129. package/dist/lib/self-exec.js +6 -3
  130. package/dist/lib/self-exec.js.map +1 -1
  131. package/dist/lib/stack-journal.d.ts +3 -1
  132. package/dist/lib/stack-journal.d.ts.map +1 -1
  133. package/dist/lib/stack-journal.js +10 -0
  134. package/dist/lib/stack-journal.js.map +1 -1
  135. package/dist/lib/update-connector-config.d.ts +2 -0
  136. package/dist/lib/update-connector-config.d.ts.map +1 -1
  137. package/dist/lib/update-connector-config.js +15 -1
  138. package/dist/lib/update-connector-config.js.map +1 -1
  139. package/dist/lib/update-managers.d.ts.map +1 -1
  140. package/dist/lib/update-managers.js +11 -3
  141. package/dist/lib/update-managers.js.map +1 -1
  142. package/dist/lib/update-recovery-state.d.ts +7 -0
  143. package/dist/lib/update-recovery-state.d.ts.map +1 -1
  144. package/dist/lib/update-recovery-state.js +55 -2
  145. package/dist/lib/update-recovery-state.js.map +1 -1
  146. package/dist/lib/update-snapshot.d.ts.map +1 -1
  147. package/dist/lib/update-snapshot.js +14 -7
  148. package/dist/lib/update-snapshot.js.map +1 -1
  149. package/dist/seed/lock.d.ts +1 -1
  150. package/dist/seed/lock.d.ts.map +1 -1
  151. package/dist/seed/lock.js +3 -2
  152. package/dist/seed/lock.js.map +1 -1
  153. package/dist/telemetry.d.ts +6 -0
  154. package/dist/telemetry.d.ts.map +1 -1
  155. package/dist/telemetry.js +6 -3
  156. package/dist/telemetry.js.map +1 -1
  157. package/package.json +5 -5
@@ -1,41 +1,32 @@
1
- import { spawn, spawnSync } from "node:child_process";
2
- import { lookup } from "node:dns/promises";
3
- import { existsSync, lstatSync, mkdtempSync, readFileSync, realpathSync, rmSync, watch, writeFileSync } from "node:fs";
1
+ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs";
4
2
  import { homedir, tmpdir } from "node:os";
5
- import { isIP, SocketAddress } from "node:net";
6
- import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
3
+ import { dirname, isAbsolute, join } from "node:path";
7
4
  import { globalConfigDir } from "@cotal-ai/core";
8
- import { CommandFailure, isCommandFailure, jsonFlag, plainFlag, presentationOf, renderReport, writeResult, cmdSpawnSpec, oneLine, beginGlobalUpdateChild, processGroupMembers, processStartToken, claimUpdateClosureAccess, updateClosureOwner, homeCotalDir, isMeshRegistryError, preparedRecordSkipped, preparedRecordSpace, preparedSpacesDir, readPreparedSpaces, recordOperationWarning, readUpdateRecovery, clearUpdateRecovery, writeUpdateRecovery, readUpdateSettings, observeUpdateVersion, UPDATE_HOUR_MS, recordUpdateCompletion, recordUpdateDeferral, recordUpdateReleaseHold, recordUpdateRefusal, recordUpdateReplacement, setUpdateSetting, bindExtensionPeers, claimGlobalNpmUpdateLock, launcherInstallRoot, logicalExecutionEntry, loadExtensionsManifest, provenance, SEEDED_EXTENSIONS, targetFlags, resolveControlTarget, recoveryDisposition, liveUpdateClosureOwner, recoveryProcessStartToken, observeUnownedRecovery, UnreadableConnectorSelection, } from "@cotal-ai/workspace";
9
- import { retainUnusableRecovery } from "../lib/update-recovery-state.js";
5
+ import { CommandFailure, isCommandFailure, jsonFlag, plainFlag, presentationOf, renderReport, writeResult, cmdSpawnSpec, oneLine, claimUpdateClosureAccess, updateClosureOwner, homeCotalDir, preparedRecordSkipped, preparedRecordSpace, readPreparedSpaces, recordOperationWarning, readUpdateRecovery, clearUpdateRecovery, writeUpdateRecovery, readUpdateSettings, observeUpdateVersion, UPDATE_HOUR_MS, recordUpdateCompletion, recordUpdateDeferral, recordUpdateReleaseHold, recordUpdateRefusal, recordUpdateReplacement, setUpdateSetting, bindExtensionPeers, claimGlobalNpmUpdateLock, launcherInstallRoot, logicalExecutionEntry, loadExtensionsManifest, provenance, SEEDED_EXTENSIONS, targetFlags, recoveryDisposition, liveUpdateClosureOwner, recoveryProcessStartToken, observeUnownedRecovery, UnreadableConnectorSelection, } from "@cotal-ai/workspace";
6
+ import { resumePublishedUpdate, retainUnusableRecovery } from "../lib/update-recovery-state.js";
10
7
  import { readUpdatePending } from "../lib/update-pending.js";
11
8
  import { snapshotUpdateClosure } from "../lib/update-snapshot.js";
12
- import { assertConfigAncestorProtected, prepareUpdateConnectorConfig, repairUpdateConnectorSelection } from "../lib/update-connector-config.js";
9
+ import { assertConfigAncestorProtected, prepareUpdateConnectorConfig, repairCurrentUpdateConnectorSelection, repairUpdateConnectorSelection } from "../lib/update-connector-config.js";
13
10
  import { EXT_UPDATE_PARENT_ENV } from "./ext.js";
14
11
  import { collectUpdateCaches } from "./update-caches.js";
15
12
  import { claimExtensionUpdatePass } from "../lib/ext-mutation.js";
16
13
  import { selfArgv } from "../lib/self-exec.js";
17
- import { repairInstallModes, withInstallUmask } from "../lib/install-umask.js";
14
+ import { repairInstallModes } from "../lib/install-umask.js";
18
15
  import { cliVersion, installedCliVersion } from "../lib/version.js";
19
16
  import { runSeed, compareSemver, seedInstallationCurrent, assertReadableSeedState, readSeedRepairRefusal } from "../seed/reconcile.js";
20
17
  import { operatorInstallDiffers } from "../seed/verify.js";
21
18
  import { cliPackageRoot, entryScript, seedWriterKind } from "../seed/paths.js";
22
19
  import { refreshConnectorInstalls } from "./setup.js";
23
20
  import { c } from "../ui.js";
24
- import { assertEndpointUnreachable } from "../lib/endpoint-cut.js";
25
- import { isCliEntry, supervisorMayServe } from "../lib/manager-proc.js";
26
- import { processGone, readStackJournal, stackScopeRefusals } from "../lib/stack-journal.js";
27
- import { observeServiceProcess, serviceInstances, serviceInstanceStore } from "../lib/service-instances.js";
28
- import { ConnectRefusal, isConnectRefusal, isWorkspaceTargetError, localMeshesForRoot, preparedNeverStarted, pruneStaleMeshes, renderWorkspaceError, resolveMeshTarget, } from "@cotal-ai/workspace";
29
21
  import { refreshOwnedCompletions } from "../lib/completion-install.js";
30
- import { legacyManagerReport, legacySeatLabel } from "../lib/legacy-manager-report.js";
31
- import { recordedStackRemedy } from "../lib/recorded-stack-remedy.js";
32
- import { askManager } from "@cotal-ai/workspace/control";
33
- import { cliControl, onFlag } from "../lib/control.js";
34
- import { managerPin } from "../lib/manager-choice.js";
35
- import { localUpdateManagers, recordedUpdateManagers } from "../lib/update-managers.js";
22
+ import { onFlag } from "../lib/control.js";
23
+ import { RegistryUnavailable, STRICT_SEMVER, installedUpdatePrefix, verifyGlobalEntry, runNpmAsync, runNpm, runProcess, runGlobalProcess, latestNotAvailable, failure, message, } from "./update-process.js";
24
+ import { latestVersion, npmProxyRefused, checkInstalledClosure, checkReleaseArchives, ReleaseNotAvailable, ReleaseDateExcluded, DependencyCheckInterrupted, DependencyCheckNoSpace, registryNetworkFailure, releaseReadError, waitForReleaseArchives, } from "./update-release.js";
25
+ import { refusal, reportRunningManagers } from "./update-continuity.js";
26
+ export { isStoppedLocalMesh, reportRunningManagers, readUpdateManagerContinuity, readManagerContinuity, printLegacyReport } from "./update-continuity.js";
27
+ export { parseNpmVersion, installedUpdatePrefix, verifyGlobalEntry } from "./update-process.js";
36
28
  export { localUpdateManagers } from "../lib/update-managers.js";
37
29
  export { managerPin as updateManagerPin } from "../lib/manager-choice.js";
38
- import { assertRecordIdentity, brokerAddressKey, brokerUrlKey } from "@cotal-ai/workspace";
39
30
  const UPDATE_TARGET_ENV = "COTAL_UPDATE_TARGET_VERSION";
40
31
  const UPDATE_PARENT_ENV = "COTAL_UPDATE_PARENT";
41
32
  /** Set by a parent that waits for the installed daemon generation after its reconcile child and prints
@@ -259,13 +250,11 @@ async function updateInstallation(args, rt) {
259
250
  }
260
251
  }
261
252
  }
262
- const restored = await recoverInterruptedUpdate(rt);
263
- if (restored) {
264
- if (args.values.self !== true)
265
- return;
266
- if (restored.version !== rt.version())
267
- return restored.entry;
268
- }
253
+ const restored = await recoverInterruptedUpdate(rt, false, targetArgv(args.values));
254
+ if (restored && (args.values.self !== true || restored.resumed))
255
+ return;
256
+ if (restored && restored.version !== rt.version())
257
+ return restored.entry;
269
258
  // A folder above the config folder is not one this command repairs. Refuse it before the mode
270
259
  // repair and before seeding, so a refusal writes nothing and does not replace the binary.
271
260
  try {
@@ -295,7 +284,7 @@ async function updateInstallation(args, rt) {
295
284
  }
296
285
  }
297
286
  /** Resume an abandoned replacement before a command or daemon can activate its closure. */
298
- export async function recoverInterruptedUpdate(rt = updateRuntime, startup = false) {
287
+ export async function recoverInterruptedUpdate(rt = updateRuntime, startup = false, flags = []) {
299
288
  if (childBinding(rt).kind === "bound")
300
289
  return;
301
290
  const observed = readUpdateRecovery();
@@ -323,6 +312,8 @@ export async function recoverInterruptedUpdate(rt = updateRuntime, startup = fal
323
312
  }
324
313
  decision = recoveryDisposition(record, now, rt.recoveryOwnerStart ?? recoveryProcessStartToken);
325
314
  }
315
+ if (!startup && (decision.action === "restore" || decision.action === "retire") && record.execution && record.target === rt.version() && (record.phase === "replacing" || record.phase === "verified-ready"))
316
+ return await resumePublishedUpdate(rt, record, flags);
326
317
  if (decision.action === "retire") {
327
318
  let retained;
328
319
  try {
@@ -583,8 +574,8 @@ export async function executeUpdate(self, rt = updateRuntime, target = {}, unrea
583
574
  return code;
584
575
  }
585
576
  if (unreadableSelection) {
586
- rt.err(unreadableSelection.message);
587
- rt.out("No newer CLI version. No connector reconciliation was run.");
577
+ const repaired = repairCurrentUpdateConnectorSelection(Boolean(rt.prepareExecution), unreadableSelection, line => rt.err(line));
578
+ rt.out(repaired ? "No newer CLI version." : "No newer CLI version. No connector reconciliation was run.");
588
579
  reportVersion(current, latest.version, rt, false);
589
580
  return 0;
590
581
  }
@@ -614,11 +605,7 @@ export async function executeUpdate(self, rt = updateRuntime, target = {}, unrea
614
605
  }
615
606
  return reconcileCurrent(current, rt, target, (reconciled) => {
616
607
  const latest = latestVersion(rt);
617
- if (!latest.ok) {
618
- rt.err(c.red(`✗ cotal-ai version check failed: ${latest.error}`));
619
- return 1;
620
- }
621
- reportVersion(current, latest.version, rt, reconciled);
608
+ reportVersion(current, latest.ok ? latest.version : undefined, rt, reconciled);
622
609
  return reconciled ? 0 : 1;
623
610
  });
624
611
  }
@@ -792,644 +779,6 @@ export function verifyCurrentExtension(entry, generation) {
792
779
  provenance.wrote(`${link.peer} link (${link.owner} → this CLI's copy)`, link.destination);
793
780
  return undefined;
794
781
  }
795
- /** The "no mesh running" target refusal: no recorded mesh on this machine, or every recorded mesh
796
- * down with none selected. Either way no manager is running. A mesh selected with `--space` or
797
- * from inside its project, a named space, a broken record, or a dead broker each still names a
798
- * manager this command was asked about, unless {@link isStoppedLocalMesh} proved that mesh stopped
799
- * before the control connect. */
800
- function isNoMeshRefusal(e) {
801
- return e instanceof ConnectRefusal && isWorkspaceTargetError(e.cause) && e.cause.code === "no-meshes";
802
- }
803
- /** Whether `target` is a mesh this machine runs, stopped: no `cotal supervise` process here may be
804
- * serving its space and nothing listens at its recorded broker. Both are required. A manager
805
- * outlives its broker and reconnects when it returns, so a refused connection alone leaves its
806
- * custody in place; a supervisor whose argv names this space or none, a peer that accepts, answers
807
- * or stalls, a mesh registered by hand, or a `--server` the operator named may still have a manager
808
- * behind it. A project that only ran setup has no registry entry yet; its implicit local default
809
- * is eligible for the same process and listener checks, but an explicit server is not. */
810
- export async function isStoppedLocalMesh(target) {
811
- const registered = localMeshesForRoot(target.root).some((m) => m.space === target.space && m.server === target.server);
812
- if (!registered && target.source !== "local-space")
813
- return false;
814
- if (supervisorMayServe(target.space))
815
- return false;
816
- return assertEndpointUnreachable(target.server).then(() => true, () => false);
817
- }
818
- /** A prepared controller that completed down or failed to start any member is cold only while its
819
- * own instance records prove every process gone, no supervisor may serve it, and its broker has no listener.
820
- * The target resolver refuses before returning a MeshTarget for this lifecycle. */
821
- async function stoppedController(d, server) {
822
- if (typeof d.space !== "string" || typeof d.root !== "string" || !d.stopped ||
823
- d.rootMissing === true || d.unsettled !== undefined || d.home !== undefined || d.stackSpace !== undefined)
824
- return false;
825
- const journal = readStackJournal(d.root)?.journal;
826
- if (!journal || journal.space !== d.space)
827
- return false;
828
- const completedDown = journal.operation.kind === "down" && journal.operation.phase === "completed";
829
- const failedStart = journal.operation.kind === "up" && journal.operation.phase === "failed" &&
830
- journal.members.every(member => (member.state === "failed" || member.state === "not-attempted") && !member.process && !member.replacement);
831
- if (!completedDown && !failedStart)
832
- return false;
833
- if (server !== undefined && brokerUrlKey(server) !== brokerUrlKey(journal.server))
834
- return false;
835
- const instances = serviceInstances(d.space);
836
- if (journal.members.some((member) => member.instanceId !== null &&
837
- !instances.some((row) => row.name === member.instanceId && row.record.value.definition === member.definition)))
838
- return false;
839
- if (instances.some((row) => !["stopped", "failed"].includes(row.record.value.state) || !processGone(observeServiceProcess(row.record.value))))
840
- return false;
841
- if (supervisorMayServe(d.space))
842
- return false;
843
- const brokerStopped = await assertEndpointUnreachable(journal.server).then(() => true, () => false);
844
- stackScopeRefusals(journal, `\`cotal update --space ${d.space}\``, { brokerStopped });
845
- return brokerStopped;
846
- }
847
- /** The refusal sentence this command prints. A {@link MeshTargetError} arrives RAW here — the
848
- * control resolver rethrows the codes it does not absorb before the connect helper can wrap them —
849
- * so its `message` is the resolver's bare, command-agnostic text, with none of the recovery copy
850
- * every other surface shows. Render it the way `status` and `ps` do, dropping the rendered line's
851
- * own `✗` because this one is already printed under the command's marker; a `ConnectRefusal`
852
- * already carries that rendering as its message. Keep a CommandFailure's recovery step too. */
853
- function refusal(e) {
854
- const text = isWorkspaceTargetError(e)
855
- ? renderWorkspaceError({ kind: "target", error: e }).replace(/^✗ /, "")
856
- : message(e);
857
- const remedy = e instanceof CommandFailure ? e.remedy : undefined;
858
- return remedy === undefined ? text : `${text}\n\nNext\n ${remedy}`;
859
- }
860
- /** The running meshes an `ambiguous-target` named, or undefined when this refusal names none to act
861
- * on (several tenants on one root, an unreadable account record) and so stands. */
862
- function runningSpaces(e) {
863
- if (!isWorkspaceTargetError(e) || e.code !== "ambiguous-target")
864
- return undefined;
865
- const spaces = e.details.spaces;
866
- return spaces && spaces.length > 1 ? spaces : undefined;
867
- }
868
- /**
869
- * The continuity read for every manager this update is asked about, not just one of them.
870
- *
871
- * `update --self` replaces the single `cotal-ai` install every running manager on the machine
872
- * shares, so with no `--space` / `--server` / `--creds` the question is asked about all of them.
873
- * Reporting one and staying silent about the rest is a partial answer; refusing outright leaves the
874
- * operator with no continuity report at all. So an ambiguous target is enumerated and read once per
875
- * running mesh, and every one of them is observed before this returns and anything is written
876
- * (#1620). A `legacy` verdict on any of them makes the whole run not a hot update. A selector flag
877
- * still selects one, and every other refusal stands.
878
- */
879
- export async function reportRunningManagers(flags, readOne = readManagerContinuity, census = localUpdateManagers, options = {}) {
880
- // Raw credentials are an explicit off-registry target, not an install-wide discovery request.
881
- if (typeof flags.creds === "string")
882
- return readOne(flags);
883
- const on = typeof flags.on === "string" ? await managerPin(flags, "cotal update") : undefined;
884
- const observed = census({ ...flags, on });
885
- // A Manager of another home is named and left alone. It never changes which of this home's
886
- // Managers are selected, nor whether the selected mesh is read.
887
- for (const manager of observed)
888
- if (manager.ownership === "foreign")
889
- await readUpdateManagerContinuity(manager, flags, readOne, options);
890
- const local = observed.filter(manager => manager.ownership !== "foreign");
891
- const selected = local.filter(manager => (typeof flags.space !== "string" || manager.space === flags.space) &&
892
- (typeof flags.server !== "string" || brokerAddressKey(manager.server) === brokerAddressKey(flags.server)) &&
893
- (on === undefined || manager.instanceId === on));
894
- if (selected.length) {
895
- let verdict = "none";
896
- for (const manager of selected) {
897
- if (await readUpdateManagerContinuity(manager, flags, readOne, options) === "legacy")
898
- verdict = "legacy";
899
- }
900
- return verdict;
901
- }
902
- if (on !== undefined && local.length)
903
- throw new Error(`--on ${on} does not name a local Manager sharing this installation`);
904
- try {
905
- return await readOne(flags);
906
- }
907
- catch (e) {
908
- const selected = ["space", "server", "creds", "on"].some((name) => typeof flags[name] === "string");
909
- const spaces = selected ? undefined : runningSpaces(e);
910
- if (!spaces)
911
- throw e;
912
- console.log(c.dim(`${spaces.length} meshes running; reading each manager's continuity`));
913
- let verdict = "none";
914
- for (const space of spaces) {
915
- console.log(c.bold(space));
916
- // Every manager is read, including after a legacy verdict: the report is about all of them,
917
- // and stopping at the first would reintroduce the partial answer from the other direction.
918
- if (await readOne({ ...flags, space }) === "legacy")
919
- verdict = "legacy";
920
- else
921
- console.log(c.dim(" manager custody carries this update"));
922
- }
923
- return verdict;
924
- }
925
- }
926
- /** Read one known local Manager without requiring another home's credentials. */
927
- export async function readUpdateManagerContinuity(manager, flags, readOne = readManagerContinuity, options = {}) {
928
- if (typeof flags.creds === "string")
929
- return readOne(flags);
930
- const pin = () => {
931
- if (manager.process && assertRecordIdentity(manager.process).kind !== "match")
932
- throw new Error(`local Manager ${manager.instanceId} changed during its continuity read`);
933
- };
934
- pin();
935
- if (manager.ownership === "foreign") {
936
- console.log(`Manager pid ${manager.pid}, instance unavailable in space ${JSON.stringify(manager.space)} at ${JSON.stringify(manager.root)} keeps running the version it loaded until it is restarted from its own home; its root is not registered in this home.`);
937
- pin();
938
- return "none";
939
- }
940
- try {
941
- const verdict = await readOne({ ...flags, space: manager.space, server: manager.server, on: manager.instanceId });
942
- pin();
943
- return verdict;
944
- }
945
- catch (error) {
946
- pin();
947
- const cause = isConnectRefusal(error) ? error.cause : undefined;
948
- if (!options.retainGraph || !manager.process || typeof flags.creds === "string" || !isConnectRefusal(error) || error.code !== "AUTH_REQUIRED" ||
949
- (error.native?.code !== "CREDENTIALS_MISSING" && cause?.code !== "signed-out"))
950
- throw error;
951
- console.log(`Manager ${manager.instanceId} in space ${JSON.stringify(manager.space)} at ${JSON.stringify(manager.root)} keeps running the version it loaded until it is restarted from its own home; this home has no credentials for its space.`);
952
- return "none";
953
- }
954
- }
955
- /** Link the answering Manager to the controller's live process before excluding its installation. */
956
- function isForeignStackManager(target, status, installedEntry) {
957
- if (process.platform !== "linux" || !target.root || !status || typeof status.instanceId !== "string" || typeof status.lifecycleUid !== "string")
958
- return false;
959
- try {
960
- const journal = readStackJournal(target.root)?.journal;
961
- if (!journal || journal.operation.kind !== "up" || journal.operation.phase !== "completed" || journal.space !== target.space || brokerAddressKey(journal.server) !== brokerAddressKey(target.server))
962
- return false;
963
- const member = journal.members.find(row => row.role === "manager");
964
- if (!member?.instanceId || !member.process)
965
- return false;
966
- const instance = serviceInstanceStore(target.space).read(member.instanceId)?.record.value;
967
- const native = instance?.adapterReadiness?.native;
968
- if (!instance?.process || instance.definition !== member.definition || instance.state !== "running" ||
969
- instance.process.pid !== member.process.pid || instance.process.token !== member.process.token ||
970
- native?.instanceId !== status.instanceId || native.lifecycleUid !== status.lifecycleUid || observeServiceProcess(instance) !== "running")
971
- return false;
972
- const argv = readFileSync(`/proc/${instance.process.pid}/cmdline`, "utf8").split("\0");
973
- // The controller places only the optional global color flag after its Node entry.
974
- const verb = argv.indexOf("__service-manager");
975
- const launch = argv[verb - (argv[verb - 1] === "--no-color" ? 2 : 1)];
976
- if (!launch || !isAbsolute(launch))
977
- return false;
978
- const entry = realpathSync(launch);
979
- const own = realpathSync(installedEntry ?? logicalExecutionEntry() ?? entryScript());
980
- return entry !== own && isCliEntry(entry) && assertRecordIdentity(instance.process).kind === "match";
981
- }
982
- catch {
983
- // An unreadable record or launch entry cannot prove a different installation.
984
- return false;
985
- }
986
- }
987
- export async function readManagerContinuity(flags, options = {}) {
988
- const { readMeshRegistry } = await import("@cotal-ai/workspace");
989
- const registry = readMeshRegistry();
990
- if (registry.unusable.length)
991
- throw registry.unusable[0];
992
- const local = registry.entries.filter(entry => entry.mode !== "user" &&
993
- (typeof flags.space !== "string" || flags.space === entry.space) &&
994
- (typeof flags.server !== "string" || brokerAddressKey(flags.server) === brokerAddressKey(entry.server)));
995
- const { goneStackRoot } = await import("../lib/stack-journal.js");
996
- const gone = typeof flags.creds === "string" ? [] : local.filter(entry => !existsSync(entry.root) || goneStackRoot(entry.space) !== undefined);
997
- for (const entry of gone)
998
- console.log(` ${entry.space}: folder is gone; leaving its processes untouched, continuity not checked`);
999
- if (gone.length && gone.length === local.length)
1000
- return "none";
1001
- if (gone.length) {
1002
- let verdict = "none";
1003
- for (const entry of local.filter(entry => !gone.includes(entry))) {
1004
- if (await readManagerContinuity({ ...flags, space: entry.space, server: entry.server }, options) === "legacy")
1005
- verdict = "legacy";
1006
- }
1007
- return verdict;
1008
- }
1009
- // `--on` names the manager whose custody this install carries. An owner with several live
1010
- // managers on a user-auth mesh (one per machine, say) gets the exchange's selection refusal
1011
- // without it, naming `--on` as the remedy; the flag has to exist here for that remedy to be real,
1012
- // and it has to reach the MINT below, since a credential cannot gain an instance rail after it is
1013
- // issued. A name or host resolves to an instance id the same way `ps` resolves it.
1014
- let on = await managerPin(flags, "cotal update");
1015
- // #2158: a remote user mesh's manager runs under another install, on another machine. Replacing
1016
- // THIS machine's binary interrupts no manager there, so there is no custody here to preserve and
1017
- // no answer from that mesh's exchange can change what this install does. Peek the mode the same
1018
- // way the control resolver's own peek does (offline-swept when no space is named, `--space`
1019
- // unfiltered) and skip the mint entirely for a remote entry, before it ever reaches the exchange.
1020
- // The control resolve below reads the same sweep, so the whole chain sees one liveness verdict.
1021
- let sweep;
1022
- let remoteSpace;
1023
- if (typeof flags.creds !== "string") {
1024
- const space = typeof flags.space === "string" ? flags.space : undefined;
1025
- const server = typeof flags.server === "string" ? flags.server : undefined;
1026
- let peek;
1027
- try {
1028
- // This sweep only probes. Read-only staged checks need the same liveness verdict.
1029
- sweep = await pruneStaleMeshes(server, space === undefined ? "targets" : "brokers");
1030
- peek = resolveMeshTarget(process.cwd(), { server, space, ...sweep });
1031
- }
1032
- catch (e) {
1033
- // An unreadable prepared record is not evidence about Manager custody. The updater can
1034
- // leave it alone only if it was not asked for a broker or instance and has no potentially
1035
- // running registration or supervisor to check for the affected target.
1036
- if (isMeshRegistryError(e) && e.refusal === "PERMISSION_DENIED" && dirname(e.file) === preparedSpacesDir()) {
1037
- const name = preparedRecordSpace(e.file);
1038
- if (name !== undefined && server === undefined && on === undefined &&
1039
- !registry.entries.some(entry => space === undefined ? !sweep?.offline.includes(entry.space) : entry.space === space) &&
1040
- !supervisorMayServe(name, options.installedEntry))
1041
- return "none";
1042
- }
1043
- if (!isWorkspaceTargetError(e))
1044
- throw e;
1045
- // Sudo can inspect another account's project without owning its controller records.
1046
- // The install-wide census already preserves its Manager. Do not borrow that account's
1047
- // authority or reinterpret its implicit project as this home's selected mesh.
1048
- if (e.code === "not-started" && typeof e.details.root === "string" && typeof e.details.stackSpace === "string" &&
1049
- e.details.recordedRoot === undefined && process.getuid &&
1050
- !["space", "server", "creds", "on"].some(key => typeof flags[key] === "string") &&
1051
- (() => { const directory = lstatSync(join(e.details.root, ".cotal")); return directory.isDirectory() && directory.uid !== process.getuid(); })()) {
1052
- console.log(` ${e.details.stackSpace}: controller records in ${e.details.root} belong to another account; leaving its records and processes untouched, continuity not checked`);
1053
- return "none";
1054
- }
1055
- // Prepared-only spaces have no registry entry for the gone-root check above.
1056
- // As with a registered gone root, leave its records and processes untouched.
1057
- if (e.code === "not-started" && e.details.rootMissing === true) {
1058
- console.log(` ${e.details.space}: folder is gone; leaving its processes untouched, continuity not checked`);
1059
- return "none";
1060
- }
1061
- if (e.code === "not-started" && e.details.recordedRoot !== undefined) {
1062
- console.log(c.dim(` ${e.details.stackSpace ?? e.details.root}: stack records in ${e.details.root} belong to ${e.details.recordedRoot}; leaving its records and processes untouched, continuity not checked`));
1063
- return "none";
1064
- }
1065
- // A refused legacy start can leave a rendered broker config without ever starting a member.
1066
- // That file cannot prove custody or its absence. Leave the project alone without claiming
1067
- // continuity, rather than requiring a successful start before a software update.
1068
- if (e.code === "not-started" && e.details.lastRun === true) {
1069
- console.log(c.dim(` ${e.details.stackSpace ?? e.details.root}: retained broker configuration in ${e.details.root}; leaving its records and processes untouched, continuity not checked`));
1070
- return "none";
1071
- }
1072
- // A space prepared here that never started (`cotal setup --configure-only`, `space create`)
1073
- // has no broker, no stack journal and no manager: a supervisor serves a started stack, and
1074
- // this one never launched a member, so there is nothing this update could interrupt. Run from
1075
- // its folder, or with it selected or named, the resolver refuses it as not started before
1076
- // dialing anything, which is the right answer for a command that needs a mesh and the wrong
1077
- // one for a software update, which needs only to know that no manager here holds custody.
1078
- if (e.code === "not-started" && preparedNeverStarted(e.details)) {
1079
- console.log(c.dim(` ${e.details.space}: prepared in ${e.details.root}, not started; no manager running`));
1080
- return "none";
1081
- }
1082
- if (e.code === "not-started" && await stoppedController(e.details, server)) {
1083
- console.log(c.dim(` ${e.details.space}: stopped; no manager running`));
1084
- return "none";
1085
- }
1086
- if (e.code !== "unknown-space" && e.code !== "no-meshes")
1087
- throw e;
1088
- }
1089
- // The skip holds only while no supervisor that loaded THIS install may be serving that space.
1090
- // A `cotal manager start` or `cotal supervise` process here that loaded this install and serves a
1091
- // remote mesh is read like a local manager. A supervisor whose command resolves in another
1092
- // install is untouched by replacing this one, so it is no custody here, the same as a manager
1093
- // that runs on another machine.
1094
- if (peek?.mode === "user" && peek.userAuth?.remote === true) {
1095
- remoteSpace = peek.space;
1096
- const recorded = on === undefined ? recordedUpdateManagers({ space: peek.space, server: peek.server }, options.installedEntry) : [];
1097
- if (recorded.length > 1) {
1098
- let verdict = "none";
1099
- for (const manager of recorded) {
1100
- if (manager.process && assertRecordIdentity(manager.process).kind !== "match")
1101
- throw new Error(`local Manager ${manager.instanceId} changed before its continuity read`);
1102
- if (await readManagerContinuity({ ...flags, space: manager.space, server: manager.server, on: manager.instanceId }, options) === "legacy")
1103
- verdict = "legacy";
1104
- }
1105
- return verdict;
1106
- }
1107
- if (recorded.length === 1)
1108
- on = recorded[0].instanceId;
1109
- if (on === undefined && process.platform !== "win32" && !supervisorMayServe(peek.space, options.installedEntry)) {
1110
- console.log(c.dim(` ${peek.space}: this mesh's manager runs elsewhere; no custody on this machine`));
1111
- return "none";
1112
- }
1113
- console.log(c.dim(` ${peek.space}: a manager for this mesh runs on this machine; reading its custody`));
1114
- }
1115
- // Explicit and in-folder targets are not filtered by the resolver's offline set.
1116
- if (peek && sweep?.offline.includes(peek.space) && on === undefined &&
1117
- !supervisorMayServe(peek.space, options.installedEntry))
1118
- return "none";
1119
- // #3559: `cotal down` then `cotal update` is the cold path past a `legacy` verdict, so a stopped
1120
- // mesh is no custody rather than a refusal. Decided before the control connect, whose user-mode
1121
- // exchange would refuse on the stopped auth service first.
1122
- if (peek && remoteSpace === undefined && await isStoppedLocalMesh(peek)) {
1123
- console.log(c.dim(` ${peek.space}: stopped; no manager running`));
1124
- return "none";
1125
- }
1126
- }
1127
- let target;
1128
- try {
1129
- target = await resolveControlTarget({
1130
- ...(typeof flags.space === "string" ? { space: flags.space } : {}),
1131
- ...(typeof flags.server === "string" ? { server: flags.server } : {}),
1132
- ...(typeof flags.creds === "string" ? { creds: flags.creds } : {}),
1133
- ...sweep,
1134
- }, "control-caller-admin", on, { onRefusal: "throw", readOnly: true });
1135
- }
1136
- catch (e) {
1137
- const failure = e instanceof ConnectRefusal ? e.failure() : isCommandFailure(e) ? e : undefined;
1138
- if (remoteSpace !== undefined && on === undefined && e instanceof ConnectRefusal && failure?.code === "PERMISSION_DENIED" && /\(view "manager-caller"\) was refused: manager-caller selection found (?:[2-9]|\d{2,}) live remote manager candidates for owner \S+ \([A-Za-z0-9_, -]+\); exactly one is required, so name one with --on <instanceId>/.test(failure.message)) {
1139
- console.log(` ${remoteSpace}: several Managers are live and no local instance could be identified; continuing the software update.`);
1140
- return "none";
1141
- }
1142
- // No running manager means no custody to preserve and nothing this update could interrupt. Only
1143
- // the "no mesh running" refusal reads as "none": no recorded mesh, or every recorded mesh down
1144
- // with none selected. A selected stopped mesh was already read above; a named space that is not
1145
- // running, a broken record, or a broker that did not answer still names a manager this command
1146
- // was asked about, and stays a refusal.
1147
- if (isNoMeshRefusal(e))
1148
- return "none";
1149
- throw e;
1150
- }
1151
- const pin = on === undefined ? {} : { instanceId: on };
1152
- const status = await askManager(cliControl, target.space, target.server, "managerStatus", undefined, target.auth, "owner", undefined, pin);
1153
- if (!status.ok) {
1154
- // The MARKER, not the sentence. `unanswered` is the structural fact `epRailFailure` sets from
1155
- // core's answer-provenance marker; the headline beside it is operator prose and is now scoped to
1156
- // the rail the caller rode (#1630), so this call, which runs under an issued control caller, saw
1157
- // the headline naming the versioned rail and threw instead of reporting "none". Unpinned, an
1158
- // unanswered reply is the verdict that no manager holds custody. Pinned, it is a manager the
1159
- // operator named and this command could not read, which is not "none".
1160
- if (status.unanswered && on === undefined)
1161
- return "none";
1162
- throw new Error(status.error ?? "manager status request failed");
1163
- }
1164
- if (typeof flags.creds !== "string" && isForeignStackManager(target, status.data, options.installedEntry))
1165
- return "none";
1166
- const seats = await askManager(cliControl, target.space, target.server, "ps", undefined, target.auth, "owner", undefined, pin);
1167
- if (!seats.ok)
1168
- throw new Error(seats.error ?? "manager seat inventory request failed");
1169
- if (options.retainGraph) {
1170
- const custody = status.data?.custody;
1171
- if (custody === undefined || custody === "legacy")
1172
- console.log(`Standalone Manager ${on ?? "(instance unavailable)"} in ${JSON.stringify(target.space)} keeps its loaded execution generation; no restart or seat stop is requested. New launches remain subject to the extension generation check.`);
1173
- return "none";
1174
- }
1175
- const report = await legacyManagerReport((status.data ?? {}), Array.isArray(seats.data)
1176
- ? seats.data.map((seat) => {
1177
- const row = seat;
1178
- const id = typeof row.id === "string" && row.id.trim() ? row.id : undefined;
1179
- return { name: typeof row.name === "string" ? row.name : "", agent: typeof row.agent === "string" ? row.agent : "", ...(id ? { id } : {}) };
1180
- })
1181
- : []);
1182
- if (!report)
1183
- return "none";
1184
- const remedy = typeof flags.creds === "string" ? undefined : recordedStackRemedy(target.root, target.space, target.server, (status.data ?? {}));
1185
- printLegacyReport(report, target.space, undefined, console.log, on, remedy);
1186
- return "legacy";
1187
- }
1188
- /** Name legacy custody and the cold update sequence without guessing its hosting lifecycle.
1189
- * An endpoint identity is not a saved service instance or proof of its original starter.
1190
- * The third argument is retained for callers, but an unverified stop command is not a remedy. */
1191
- export function printLegacyReport(report, space, _stop = undefined, out = console.log, manager, recorded) {
1192
- out(c.yellow("! legacy manager custody: PTY continuity is impossible; this update is not a hot update"));
1193
- out(` Manager ${manager ?? "(instance unavailable)"} in space ${JSON.stringify(space)}: ${report.seats.length} seats`);
1194
- for (const seat of report.seats)
1195
- out(c.dim(` ${legacySeatLabel(seat)}: ${seat.continuity}`));
1196
- if (recorded) {
1197
- out(` Recorded stack root: ${recorded.root}`);
1198
- out(" This is a manual cold update. The listed seats end and are not restarted. Nothing was stopped by this command.");
1199
- out(" Run these commands in order:");
1200
- for (const command of recorded.commands)
1201
- out(` ${command}`);
1202
- return;
1203
- }
1204
- out(" Cannot determine this Manager's original hosting command. Obtain its exact stop and start commands before stopping it; do not infer a service instance from its Manager identity.");
1205
- out(" Next: stop this Manager through its original host, ending any seats listed above; run `cotal update --self`, then restart through that host with the original start command. This is a cold update, including for a Manager with 0 seats.");
1206
- }
1207
- /** The registry's latest tag, read through a throwaway npm cache with npm's log files and update
1208
- * notifier off, so the read leaves nothing in npm's own cache, log directory or notifier stamp. */
1209
- function latestVersion(rt) {
1210
- const cache = mkdtempSync(join(tmpdir(), "cotal-npm-view-"));
1211
- try {
1212
- const result = rt.npm(["view", "cotal-ai@latest", "version", "--json", "--cache", cache, "--logs-max=0", "--update-notifier=false", "--fetch-retries=0", "--fetch-timeout=15000"]);
1213
- if (result.errorCode === "ENOENT")
1214
- return { ok: false, error: "npm is not on PATH", missingNpm: true };
1215
- if (result.status !== 0)
1216
- return { ok: false, error: failure(result), npmResult: result };
1217
- try {
1218
- return { ok: true, version: parseNpmVersion(result.stdout) };
1219
- }
1220
- catch (e) {
1221
- return { ok: false, error: message(e) };
1222
- }
1223
- }
1224
- finally {
1225
- rmSync(cache, { recursive: true, force: true, maxRetries: 3 });
1226
- }
1227
- }
1228
- /** npm gives a generic proxy hint even for direct failures. Match the refused socket instead. */
1229
- async function npmProxyRefused(result, env) {
1230
- const httpsProxy = env.https_proxy || env.HTTPS_PROXY;
1231
- const httpProxy = env.http_proxy || env.HTTP_PROXY;
1232
- if ((!httpsProxy && !httpProxy) || result.status === null || result.error)
1233
- return false;
1234
- let error;
1235
- try {
1236
- error = JSON.parse(result.stdout)?.error;
1237
- }
1238
- catch {
1239
- return false;
1240
- }
1241
- if (error?.code !== "ECONNREFUSED" || typeof error.summary !== "string")
1242
- return false;
1243
- const refused = /^(?:FetchError: )?request to (\S+) failed, reason: connect ECONNREFUSED (\S+):(\d+)$/.exec(error.summary);
1244
- if (!refused)
1245
- return false;
1246
- const [, request, address, port] = refused;
1247
- const registry = URL.parse(request);
1248
- if (!registry || (registry.protocol !== "https:" && registry.protocol !== "http:") || !isIP(address))
1249
- return false;
1250
- const setting = httpsProxy || (registry.protocol === "http:" ? httpProxy : undefined);
1251
- const proxy = setting ? URL.parse(setting) : null;
1252
- if (!proxy || (proxy.protocol !== "http:" && proxy.protocol !== "https:"))
1253
- return false;
1254
- const portOf = (url) => url.port || (url.protocol === "https:" ? "443" : "80");
1255
- if (portOf(proxy) !== port)
1256
- return false;
1257
- const normalize = (ip) => isIP(ip) === 6 ? new SocketAddress({ address: ip, family: "ipv6" }).address : ip;
1258
- const matches = async (url) => {
1259
- const host = url.hostname.replace(/^\[|\]$/g, "");
1260
- const addresses = isIP(host) ? [host] : (await lookup(host, { all: true })).map(item => item.address);
1261
- return addresses.some(ip => normalize(ip) === normalize(address));
1262
- };
1263
- try {
1264
- // If the registry could have refused the same socket directly, do not blame the proxy.
1265
- return await matches(proxy) && (portOf(registry) !== port || !await matches(registry));
1266
- }
1267
- catch {
1268
- return false;
1269
- }
1270
- }
1271
- /** Resolve installed first-party surfaces in a disposable prefix, including their npm dependencies. */
1272
- function checkInstalledClosure(version, releasePackages, rt) {
1273
- const names = [...new Set(rt.extensions().filter(entry => entry.pkg.startsWith("@cotal-ai/")).map(entry => entry.pkg))];
1274
- if (!names.length)
1275
- return;
1276
- const staging = mkdtempSync(join(tmpdir(), "cotal-closure-check-"));
1277
- try {
1278
- // Reconciliation supplies first-party peers from the target CLI, not the registry's latest tag.
1279
- // Constrain npm to that verified release graph without skipping third-party peers.
1280
- writeFileSync(join(staging, "package.json"), JSON.stringify({
1281
- overrides: Object.fromEntries([...releasePackages, ...names].map(name => [name, version])),
1282
- }));
1283
- const result = rt.npm(["install", "--prefix", staging, "--cache", join(staging, ".npm-cache"), "--logs-max=0", "--update-notifier=false", "--ignore-scripts", "--package-lock=false", "--no-audit", "--no-fund", "--fetch-retries=2", "--fetch-retry-mintimeout=1000", "--fetch-retry-maxtimeout=2000", "--fetch-timeout=15000", "--prefer-online", ...names.map(name => `${name}@${version}`)]);
1284
- if (result.signal)
1285
- throw new DependencyCheckInterrupted(`npm dependency check was terminated by ${result.signal}`);
1286
- if (result.status !== 0) {
1287
- const detail = `installed extension dependency closure is unavailable: ${failure(result)}`;
1288
- if (/^npm (?:error|ERR!) code ENOSPC\s*$/m.test(result.stderr))
1289
- throw new DependencyCheckNoSpace(detail);
1290
- throw releaseReadError(result, detail);
1291
- }
1292
- }
1293
- finally {
1294
- rmSync(staging, { recursive: true, force: true, maxRetries: 3 });
1295
- }
1296
- }
1297
- /** Fetch the target's first-party install closure through npm, including integrity verification.
1298
- * A private cache forces a registry read without changing the installed packages or running scripts. */
1299
- async function checkReleaseArchives(version, rt) {
1300
- const cache = mkdtempSync(join(tmpdir(), "cotal-release-check-"));
1301
- const options = ["--cache", cache, "--logs-max=0", "--update-notifier=false", "--fetch-retries=2", "--fetch-retry-mintimeout=1000", "--fetch-retry-maxtimeout=2000", "--fetch-timeout=15000", "--prefer-online"];
1302
- const pending = new Set(["cotal-ai"]);
1303
- const names = ["cotal-ai"];
1304
- try {
1305
- if (process.platform === "linux" || process.platform === "darwin") {
1306
- const start = processStartToken(process.pid);
1307
- if (!start)
1308
- throw new Error("cannot identify the archive cache owner");
1309
- writeFileSync(join(cache, ".owner"), `${process.pid}\n${start}\n`, { mode: 0o600, flag: "wx" });
1310
- }
1311
- for (let offset = 0; offset < names.length;) {
1312
- const batch = names.slice(offset, offset + 3);
1313
- // Settle every read before validating or removing its shared private cache. Validation below
1314
- // stays in discovery order, including when independent registry requests finish out of order.
1315
- const manifests = await Promise.allSettled(batch.map(name => rt.npmAsync(["view", `${name}@${version}`, "--json", ...options], cache)));
1316
- offset += batch.length;
1317
- for (const [index, name] of batch.entries()) {
1318
- const spec = `${name}@${version}`;
1319
- const result = manifests[index];
1320
- if (result.status === "rejected")
1321
- throw new Error(`metadata for ${spec} is unavailable`);
1322
- const manifest = result.value;
1323
- if (manifest.status !== 0)
1324
- throw releaseReadError(manifest, `metadata for ${spec} is unavailable`);
1325
- let meta;
1326
- try {
1327
- const payload = JSON.parse(manifest.stdout);
1328
- const parsed = Array.isArray(payload) && payload.length === 1 ? payload[0] : payload;
1329
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1330
- throw new Error();
1331
- meta = parsed;
1332
- if (meta.name !== name || meta.version !== version)
1333
- throw new Error();
1334
- const dist = meta.dist;
1335
- if (typeof dist?.tarball !== "string" || !dist.tarball || typeof dist.integrity !== "string" || !dist.integrity)
1336
- throw new Error();
1337
- }
1338
- catch {
1339
- throw new Error(`metadata for ${spec} is incomplete or invalid`);
1340
- }
1341
- for (const field of ["dependencies", "optionalDependencies", "peerDependencies"]) {
1342
- const deps = meta[field];
1343
- if (deps === undefined)
1344
- continue;
1345
- if (!deps || typeof deps !== "object" || Array.isArray(deps))
1346
- throw new Error(`invalid ${field} for ${spec}`);
1347
- for (const [dependency, range] of Object.entries(deps)) {
1348
- if (!dependency.startsWith("@cotal-ai/"))
1349
- continue;
1350
- if (!/^@cotal-ai\/[a-z0-9][a-z0-9._-]*$/.test(dependency) || typeof range !== "string" ||
1351
- (field !== "peerDependencies" && range !== version))
1352
- throw new Error(`invalid first-party dependency in ${spec}`);
1353
- if (!pending.has(dependency)) {
1354
- pending.add(dependency);
1355
- names.push(dependency);
1356
- }
1357
- }
1358
- }
1359
- }
1360
- }
1361
- // npm verifies each archive's integrity and applies registry, scoped auth and proxy/TLS policy.
1362
- // Its cache add accepts multiple specs. Bound each group rather than starting npm per archive.
1363
- for (let offset = 0; offset < names.length; offset += 6) {
1364
- const specs = names.slice(offset, offset + 6).map(name => `${name}@${version}`);
1365
- const archive = await rt.npmAsync(["cache", "add", ...specs, "--json", "--ignore-scripts", ...options], cache);
1366
- if (archive.status !== 0)
1367
- throw releaseReadError(archive, `archives for ${specs.join(", ")} could not be downloaded and verified`);
1368
- }
1369
- return pending;
1370
- }
1371
- finally {
1372
- rmSync(cache, { recursive: true, force: true, maxRetries: 3 });
1373
- }
1374
- }
1375
- class ReleaseNotAvailable extends Error {
1376
- }
1377
- class ReleaseDateExcluded extends Error {
1378
- }
1379
- class DependencyCheckInterrupted extends Error {
1380
- }
1381
- class DependencyCheckNoSpace extends Error {
1382
- }
1383
- class RegistryUnavailable extends Error {
1384
- }
1385
- const NETWORK_ERROR_CODE = /^(?:ENETUNREACH|EHOSTUNREACH|ENETDOWN|EHOSTDOWN|ECONNRESET|ECONNREFUSED|ECONNABORTED|ETIMEDOUT|EIDLETIMEOUT|ESOCKETTIMEDOUT|EAI_AGAIN|ENOTFOUND)$/;
1386
- function registryNetworkFailure(error) {
1387
- if (error instanceof RegistryUnavailable)
1388
- return true;
1389
- const code = /(?:^|\n|^target staging failed: )npm (?:error|ERR!) code ([A-Z_]+)(?:\s|$)/.exec(message(error))?.[1];
1390
- return code !== undefined && NETWORK_ERROR_CODE.test(code);
1391
- }
1392
- function releaseReadError(result, detail) {
1393
- if (result.status !== null && !result.error) {
1394
- try {
1395
- const error = JSON.parse(result.stdout).error;
1396
- if (error?.code === "ETARGET" && [error.summary, error.detail].some(text => typeof text === "string" && /with a date before\b/i.test(text)))
1397
- return new ReleaseDateExcluded(`${detail}: npm's min-release-age or before setting excludes this release. Adjust that date filter and run \`cotal update --self\` again`);
1398
- // A first-party scoped read can fail while the public registry still answers.
1399
- if (!detail.includes("@cotal-ai/") && typeof error?.code === "string" && NETWORK_ERROR_CODE.test(error.code))
1400
- return new RegistryUnavailable(detail);
1401
- if (error?.code === "E404" || error?.code === "ETARGET")
1402
- return new ReleaseNotAvailable(detail);
1403
- if (typeof error?.code === "string" && /^[A-Z][A-Z0-9_]{0,39}$/.test(error.code)) {
1404
- const registry = detail.includes("@cotal-ai/") ? "the @cotal-ai:registry setting in .npmrc" : "your npm registry settings";
1405
- return new Error(`${detail} (npm ${error.code}${error.code === "ECONNREFUSED" ? ": registry connection refused" : ""}); check ${registry}, authentication, proxy and TLS configuration`);
1406
- }
1407
- }
1408
- catch { /* An unstructured failure is not evidence of registry propagation. */ }
1409
- }
1410
- return registryNetworkFailure(new Error(failure(result))) ? new RegistryUnavailable(detail) : new Error(detail);
1411
- }
1412
- async function waitForReleaseArchives(version, current, rt) {
1413
- const now = rt.now ?? Date.now;
1414
- const deadline = now() + 10 * 60_000;
1415
- for (;;) {
1416
- try {
1417
- return await checkReleaseArchives(version, rt);
1418
- }
1419
- catch (error) {
1420
- if (!(error instanceof ReleaseNotAvailable))
1421
- throw error;
1422
- const remaining = deadline - now();
1423
- if (remaining <= 0) {
1424
- recordUpdateDeferral(version, "waiting for registry or extension closure availability", true);
1425
- rt.out(`cotal-ai@${version} is still reaching the registry. Keeping cotal-ai@${current}; no global install was attempted. A later update check will try again.`);
1426
- return undefined;
1427
- }
1428
- rt.out(`Waiting for cotal-ai@${version} release archives to reach the registry (${Math.ceil(remaining / 1000)} s remaining); cotal-ai@${current} stays installed.`);
1429
- await (rt.sleep ?? (milliseconds => new Promise(resolveSleep => setTimeout(resolveSleep, milliseconds))))(Math.min(15_000, remaining));
1430
- }
1431
- }
1432
- }
1433
782
  function preflightDetail(error) {
1434
783
  return message(error).replace(/[\r\n\u001b]+/g, " ").replace(/(?:[A-Za-z]:[\\/]|\/)[^\s,;"']+/g, "<config path>").slice(0, 500);
1435
784
  }
@@ -1869,9 +1218,9 @@ function targetArgv(target) {
1869
1218
  return argv;
1870
1219
  }
1871
1220
  function reportVersion(current, latest, rt, reconciled) {
1872
- const available = compareSemver(latest, current) > 0;
1221
+ const available = latest !== undefined && compareSemver(latest, current) > 0;
1873
1222
  rt.out(renderReport({ sections: [
1874
- { title: "CLI version", blocks: [{ kind: "fields", rows: [["This process", current], ["Registry latest", latest], ["Update", available ? { text: "available", tone: "waiting" } : "no newer latest tag"]] }, { kind: "lines", lines: [{ text: "Running processes keep the generation they loaded. This version report does not prove every live service was upgraded.", tone: "hint" }] }] },
1223
+ { title: "CLI version", blocks: [{ kind: "fields", rows: [["This process", current], ["Registry latest", latest ?? "not established"], ["Update", latest === undefined ? { text: "unknown", tone: "waiting" } : available ? { text: "available", tone: "waiting" } : "no newer latest tag"]] }, { kind: "lines", lines: [{ text: "Running processes keep the generation they loaded. This version report does not prove every live service was upgraded.", tone: "hint" }] }] },
1875
1224
  ...(reconciled ? [{ title: "Next", blocks: [{ kind: "commands", items: [{ command: available ? "cotal update --self" : "cotal status", description: !available ? "Inspect the machine and selected space" : rt.checkout() ? "Install the validated CLI as a separate global copy and reconcile through it; this checkout does not change" : "Install the validated CLI and reconcile its matching extensions" }] }] }] : []),
1876
1225
  ] }, "rich", process.stdout));
1877
1226
  }
@@ -1888,277 +1237,4 @@ function childBinding(rt) {
1888
1237
  return { kind: "invalid", reason: "parent pid does not match the launching process" };
1889
1238
  return { kind: "bound", target };
1890
1239
  }
1891
- export function parseNpmVersion(output) {
1892
- const parsed = JSON.parse(output.trim());
1893
- // `npm view cotal-ai@latest version --json` returns a bare string ("0.13.2") only while the
1894
- // registry holds a single published version; once more than one exists npm wraps the field query
1895
- // in a JSON array (["0.13.2"]) even for the @latest tag. Accept both, and take the highest valid
1896
- // semver — the @latest query resolves the array to a single element, and the max is the right
1897
- // answer whether npm hands back one element or the whole version list.
1898
- const candidates = typeof parsed === "string" ? [parsed] : Array.isArray(parsed) ? parsed : [];
1899
- const versions = candidates.filter((v) => typeof v === "string" && STRICT_SEMVER.test(v));
1900
- if (versions.length === 0)
1901
- throw new Error(`npm returned an invalid cotal-ai version: ${JSON.stringify(parsed)}`);
1902
- return versions.reduce((max, v) => (compareSemver(v, max) > 0 ? v : max));
1903
- }
1904
- const PRE = "(?:0|[1-9]\\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)";
1905
- const BUILD = "[0-9A-Za-z-]+";
1906
- const STRICT_SEMVER = new RegExp(`^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-${PRE}(?:\\.${PRE})*)?(?:\\+${BUILD}(?:\\.${BUILD})*)?$`);
1907
- /** Bind a POSIX npm global installation to its package and bin link before replacing it.
1908
- * Local/npx copies and source checkouts retain npm's separate global destination. A global-shaped
1909
- * installation with a missing, redirected or escaping entry refuses instead of guessing a prefix. */
1910
- export function installedUpdatePrefix(packageRoot, entry) {
1911
- const root = realpathSync(packageRoot);
1912
- const modules = dirname(root);
1913
- if (process.platform === "win32" || basename(modules) !== "node_modules" || basename(dirname(modules)) !== "lib")
1914
- return undefined;
1915
- const prefix = dirname(dirname(modules));
1916
- const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
1917
- const linked = realpathSync(join(prefix, "bin", "cotal"));
1918
- if (basename(root) !== "cotal-ai" || !meta.version ||
1919
- verifyGlobalEntry(modules, meta.version) !== realpathSync(entry) ||
1920
- (linked !== realpathSync(entry) && linked !== join(root, "dist", "cotal-npm")))
1921
- throw new Error("the invoked cotal package and its global bin link do not identify the same install");
1922
- return prefix;
1923
- }
1924
- export function verifyGlobalEntry(root, expectedVersion) {
1925
- const packageDir = realpathSync(join(resolve(root), "cotal-ai"));
1926
- const meta = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8"));
1927
- if (meta.name !== "cotal-ai" || meta.version !== expectedVersion)
1928
- throw new Error(`expected cotal-ai@${expectedVersion}, found ${meta.name ?? "unnamed"}@${meta.version ?? "unknown"}`);
1929
- const declared = typeof meta.bin === "string" ? meta.bin : meta.bin?.cotal;
1930
- if (!declared)
1931
- throw new Error("the installed package declares no cotal executable");
1932
- const entry = realpathSync(resolve(packageDir, declared));
1933
- const rel = relative(packageDir, entry);
1934
- if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel))
1935
- throw new Error(`the installed cotal executable escapes its package: ${entry}`);
1936
- return entry;
1937
- }
1938
- async function runNpmAsync(args, archiveCache) {
1939
- try {
1940
- const { file, args: spawnArgs, windowsVerbatimArguments } = cmdSpawnSpec("npm", args);
1941
- const gated = archiveCache !== undefined && (process.platform === "linux" || process.platform === "darwin");
1942
- const gate = 'IFS= read -r permit <&3 && [ "$permit" = run ] || exit 1; exec 3<&-; exec "$@"';
1943
- const child = spawn(gated ? "/bin/sh" : file, gated ? ["-c", gate, "cotal-release-check", file, ...spawnArgs] : spawnArgs, {
1944
- cwd: parse(homedir()).root, windowsVerbatimArguments, windowsHide: true,
1945
- ...(gated ? { detached: true, stdio: ["ignore", "pipe", "pipe", "pipe"] } : {}),
1946
- });
1947
- let stdout = "", stderr = "", error;
1948
- child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
1949
- child.stderr?.on("data", (chunk) => { stderr += chunk.toString(); });
1950
- child.once("error", cause => { error = cause.message; });
1951
- if (gated) {
1952
- const permit = child.stdio[3];
1953
- permit.on("error", cause => { error = message(cause); });
1954
- try {
1955
- if (child.pid === undefined)
1956
- permit.end();
1957
- else {
1958
- writeFileSync(join(archiveCache, `.worker-${child.pid}`), "", { mode: 0o600 });
1959
- permit.end("run\n");
1960
- }
1961
- }
1962
- catch (cause) {
1963
- error = message(cause);
1964
- permit.end();
1965
- }
1966
- }
1967
- const status = await new Promise(resolveClose => child.once("close", resolveClose));
1968
- return { status, stdout, stderr, ...(error ? { error } : {}) };
1969
- }
1970
- catch (error) {
1971
- return { status: null, stdout: "", stderr: "", error: message(error) };
1972
- }
1973
- }
1974
- function runNpm(args, inherit = false) {
1975
- try {
1976
- const { file, args: spawnArgs, windowsVerbatimArguments } = cmdSpawnSpec("npm", args);
1977
- const result = spawnSync(file, spawnArgs, {
1978
- cwd: parse(homedir()).root, windowsVerbatimArguments,
1979
- ...(inherit ? { stdio: "inherit" } : { encoding: "utf8" }),
1980
- });
1981
- return {
1982
- status: result.status,
1983
- signal: result.signal,
1984
- stdout: `${result.stdout ?? ""}`,
1985
- stderr: `${result.stderr ?? ""}`,
1986
- error: result.error?.message,
1987
- errorCode: result.error?.code,
1988
- };
1989
- }
1990
- catch (e) {
1991
- return { status: null, stdout: "", stderr: "", error: message(e), errorCode: e?.code };
1992
- }
1993
- }
1994
- function runProcess(file, args, env, inherit = false) {
1995
- const result = withInstallUmask(() => spawnSync(file, args, inherit ? { stdio: "inherit", env } : { encoding: "utf8", env }));
1996
- return {
1997
- status: result.status,
1998
- stdout: `${result.stdout ?? ""}`,
1999
- stderr: `${result.stderr ?? ""}`,
2000
- error: result.error?.message,
2001
- };
2002
- }
2003
- async function runGlobalProcess(root, operation, file, args, env, inherit = false, windowsVerbatimArguments = false, staging) {
2004
- const gated = process.platform === "linux";
2005
- const mutation = beginGlobalUpdateChild(root, operation, gated);
2006
- let cache;
2007
- let published = false;
2008
- let preservePending = false;
2009
- const watchers = [];
2010
- let elapsed;
2011
- let idle;
2012
- let stopping;
2013
- try {
2014
- cache = mkdtempSync(join(tmpdir(), "cotal-update-npm-"));
2015
- const recordCache = gated && staging !== undefined;
2016
- if (recordCache) {
2017
- const start = processStartToken(process.pid);
2018
- if (!start)
2019
- throw new Error("cannot identify the staged npm cache owner");
2020
- writeFileSync(join(cache, ".owner"), `${process.pid}\n${start}\n`, { mode: 0o600, flag: "wx" });
2021
- }
2022
- if (staging !== undefined) {
2023
- // npm is quiet during a download. Its private cache receives the archive bytes and
2024
- // the private prefix changes as packages unpack. Neither depends on terminal output.
2025
- for (const path of [cache, staging]) {
2026
- const watcher = watch(path, { recursive: true }, () => idle?.refresh());
2027
- watcher.on("error", () => { clearTimeout(idle); idle = undefined; watcher.close(); });
2028
- watchers.push(watcher);
2029
- }
2030
- }
2031
- // The pipe closes without permission if the parent dies before publishing the PID.
2032
- // exec keeps the published PID and the real child keeps its original argv and stdin.
2033
- const gate = 'IFS= read -r permit <&3 && [ "$permit" = run ] || exit 1; exec 3<&-; exec "$@"';
2034
- const child = withInstallUmask(() => spawn(gated ? "/bin/sh" : file, gated ? ["-c", gate, "cotal-update", file, ...args] : args, {
2035
- // Corepack searches ancestors for a package manager. Keep only npm at the filesystem root.
2036
- ...(operation === "install" ? { cwd: parse(homedir()).root } : {}),
2037
- env: { ...env, npm_config_cache: cache, npm_config_logs_max: "0", npm_config_update_notifier: "false" },
2038
- // A separate process group keeps terminal interrupts out of npm's live replacement.
2039
- // Keep the ChildProcess referenced and await close; this is not a background update.
2040
- detached: true,
2041
- windowsHide: true,
2042
- windowsVerbatimArguments,
2043
- ...(gated ? { stdio: [inherit ? "inherit" : "pipe", inherit ? "inherit" : "pipe", inherit ? "inherit" : "pipe", "pipe"] } : inherit ? { stdio: "inherit" } : {}),
2044
- }));
2045
- const permit = gated ? child.stdio[3] : undefined;
2046
- let error = "";
2047
- let stdout = "";
2048
- let stderr = "";
2049
- child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
2050
- child.stderr?.on("data", (chunk) => { stderr += chunk.toString(); });
2051
- child.once("error", (e) => { error = e.message; });
2052
- permit?.on("error", (e) => { error = e.message; });
2053
- if (child.pid !== undefined) {
2054
- try {
2055
- // Publish cache custody before the gate permits npm to write to it.
2056
- if (recordCache)
2057
- writeFileSync(join(cache, `.worker-${child.pid}`), "", { mode: 0o600, flag: "wx" });
2058
- mutation.markLive(child.pid);
2059
- published = true;
2060
- }
2061
- catch (e) {
2062
- error = `could not journal ${operation} child ${child.pid}: ${e.message}`;
2063
- preservePending = true;
2064
- }
2065
- }
2066
- permit?.end(published ? "run\n" : undefined);
2067
- let rejectClose;
2068
- const close = new Promise((resolveClose, reject) => {
2069
- rejectClose = reject;
2070
- child.once("close", (status, signal) => resolveClose({ status, signal }));
2071
- });
2072
- if (staging !== undefined && child.pid !== undefined) {
2073
- const pgid = child.pid;
2074
- const signalGroup = (signal) => {
2075
- try {
2076
- process.kill(-pgid, signal);
2077
- }
2078
- catch (error) {
2079
- if (error.code !== "ESRCH")
2080
- throw error;
2081
- }
2082
- };
2083
- const grace = 2000;
2084
- const reap = 1000;
2085
- const stop = () => {
2086
- if (stopping)
2087
- return;
2088
- clearTimeout(elapsed);
2089
- clearTimeout(idle);
2090
- stopping = (async () => {
2091
- signalGroup("SIGTERM");
2092
- await new Promise(resolve => setTimeout(resolve, grace));
2093
- if (processGroupMembers(pgid).length)
2094
- signalGroup("SIGKILL");
2095
- const deadline = performance.now() + reap;
2096
- while (processGroupMembers(pgid).length) {
2097
- if (performance.now() >= deadline)
2098
- throw new Error(`could not stop staging npm process group ${pgid}`);
2099
- await new Promise(resolve => setTimeout(resolve, 25));
2100
- }
2101
- })();
2102
- void stopping.catch(error => {
2103
- child.stdin?.destroy();
2104
- child.stdout?.destroy();
2105
- child.stderr?.destroy();
2106
- child.unref();
2107
- rejectClose(error);
2108
- });
2109
- };
2110
- // Leave room for TERM and KILL within the five-minute staging budget. Idle time
2111
- // covers three 15-second fetch attempts plus their one- and two-second backoffs.
2112
- elapsed = setTimeout(stop, 300_000 - grace - reap);
2113
- idle = setTimeout(stop, 50_000);
2114
- }
2115
- const closed = await close;
2116
- clearTimeout(elapsed);
2117
- clearTimeout(idle);
2118
- if (stopping) {
2119
- await stopping;
2120
- if (published)
2121
- mutation.clear();
2122
- throw new RegistryUnavailable("target staging could not reach the registry");
2123
- }
2124
- if (published)
2125
- mutation.complete(closed.status, closed.signal, closed.signal !== null
2126
- ? `${operation} child terminated by ${closed.signal}`
2127
- : `Windows npm intermediary exited ${closed.status}; descendant completion is unproved`);
2128
- return { status: error ? null : closed.status, signal: closed.signal, stdout, stderr, ...(error ? { error } : {}) };
2129
- }
2130
- catch (e) {
2131
- if (e instanceof RegistryUnavailable)
2132
- throw e;
2133
- return { status: null, stdout: "", stderr: "", error: message(e) };
2134
- }
2135
- finally {
2136
- for (const watcher of watchers)
2137
- watcher.close();
2138
- clearTimeout(elapsed);
2139
- clearTimeout(idle);
2140
- if (!published && !preservePending)
2141
- mutation.clear();
2142
- if (cache)
2143
- rmSync(cache, { recursive: true, force: true, maxRetries: 3 });
2144
- }
2145
- }
2146
- /** npm --json supplies the code, but its summary is the only field naming the missing spec. */
2147
- function latestNotAvailable(result, version) {
2148
- if (result.status === 0 || result.status === null || result.error)
2149
- return false;
2150
- try {
2151
- const error = JSON.parse(result.stdout).error;
2152
- return error?.code === "ETARGET" && error.summary === `No matching version found for cotal-ai@${version}.`;
2153
- }
2154
- catch {
2155
- return false;
2156
- }
2157
- }
2158
- function failure(result) {
2159
- return [result.signal && `process terminated by ${result.signal}`, result.error, result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n") || `process exited ${result.status}`;
2160
- }
2161
- function message(value) {
2162
- return value instanceof Error ? value.message : String(value);
2163
- }
2164
1240
  //# sourceMappingURL=update.js.map